blob: 0237ca10330832a0321aef8f96831c3596838c44 [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#include "net/websockets/websocket_channel.h"
6
[email protected]4256dbb2014-03-24 15:39:367#include <limits.h> // for INT_MAX
8
[email protected]999bcaa2013-07-17 13:42:549#include <algorithm>
[email protected]4256dbb2014-03-24 15:39:3610#include <deque>
[email protected]999bcaa2013-07-17 13:42:5411
12#include "base/basictypes.h" // for size_t
[email protected]d9806a972014-02-26 18:14:5713#include "base/big_endian.h"
[email protected]999bcaa2013-07-17 13:42:5414#include "base/bind.h"
[email protected]f485985e2013-10-24 13:47:4415#include "base/compiler_specific.h"
skyostil4891b25b2015-06-11 11:43:4516#include "base/location.h"
[email protected]4256dbb2014-03-24 15:39:3617#include "base/memory/ref_counted.h"
[email protected]cd48ed12014-01-22 14:34:2218#include "base/memory/weak_ptr.h"
asvitkinec3c93722015-06-17 14:48:3719#include "base/metrics/histogram_macros.h"
[email protected]cb154062014-01-17 03:32:4020#include "base/numerics/safe_conversions.h"
skyostil4891b25b2015-06-11 11:43:4521#include "base/single_thread_task_runner.h"
[email protected]48cc6922014-02-10 14:20:4822#include "base/stl_util.h"
[email protected]ea56b982014-01-27 03:21:0323#include "base/strings/stringprintf.h"
skyostil4891b25b2015-06-11 11:43:4524#include "base/thread_task_runner_handle.h"
[email protected]3a266762013-10-23 08:15:1025#include "base/time/time.h"
[email protected]999bcaa2013-07-17 13:42:5426#include "net/base/io_buffer.h"
[email protected]cd48ed12014-01-22 14:34:2227#include "net/http/http_request_headers.h"
28#include "net/http/http_response_headers.h"
[email protected]53deacb2013-11-22 14:02:4329#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0730#include "net/log/net_log.h"
[email protected]999bcaa2013-07-17 13:42:5431#include "net/websockets/websocket_errors.h"
32#include "net/websockets/websocket_event_interface.h"
33#include "net/websockets/websocket_frame.h"
[email protected]cd48ed12014-01-22 14:34:2234#include "net/websockets/websocket_handshake_request_info.h"
35#include "net/websockets/websocket_handshake_response_info.h"
[email protected]999bcaa2013-07-17 13:42:5436#include "net/websockets/websocket_mux.h"
37#include "net/websockets/websocket_stream.h"
mkwst4997ce82015-07-25 12:00:0538#include "url/origin.h"
[email protected]999bcaa2013-07-17 13:42:5439
40namespace net {
41
42namespace {
43
[email protected]48cc6922014-02-10 14:20:4844using base::StreamingUtf8Validator;
45
[email protected]999bcaa2013-07-17 13:42:5446const int kDefaultSendQuotaLowWaterMark = 1 << 16;
47const int kDefaultSendQuotaHighWaterMark = 1 << 17;
48const size_t kWebSocketCloseCodeLength = 2;
tyoshinod4d1d302014-11-07 04:31:1649// Timeout for waiting for the server to acknowledge a closing handshake.
50const int kClosingHandshakeTimeoutSeconds = 60;
51// We wait for the server to close the underlying connection as recommended in
52// https://tools.ietf.org/html/rfc6455#section-7.1.1
53// We don't use 2MSL since there're server implementations that don't follow
54// the recommendation and wait for the client to close the underlying
55// connection. It leads to unnecessarily long time before CloseEvent
56// invocation. We want to avoid this rather than strictly following the spec
57// recommendation.
58const int kUnderlyingConnectionCloseTimeoutSeconds = 2;
[email protected]999bcaa2013-07-17 13:42:5459
[email protected]f485985e2013-10-24 13:47:4460typedef WebSocketEventInterface::ChannelState ChannelState;
61const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
62const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
63
[email protected]3de65092013-10-24 09:39:4464// Maximum close reason length = max control frame payload -
65// status code length
66// = 125 - 2
67const size_t kMaximumCloseReasonLength = 125 - kWebSocketCloseCodeLength;
68
69// Check a close status code for strict compliance with RFC6455. This is only
70// used for close codes received from a renderer that we are intending to send
71// out over the network. See ParseClose() for the restrictions on incoming close
72// codes. The |code| parameter is type int for convenience of implementation;
[email protected]aa984e5f2014-02-26 07:33:0973// the real type is uint16. Code 1005 is treated specially; it cannot be set
74// explicitly by Javascript but the renderer uses it to indicate we should send
75// a Close frame with no payload.
[email protected]3de65092013-10-24 09:39:4476bool IsStrictlyValidCloseStatusCode(int code) {
77 static const int kInvalidRanges[] = {
78 // [BAD, OK)
79 0, 1000, // 1000 is the first valid code
[email protected]aa984e5f2014-02-26 07:33:0980 1006, 1007, // 1006 MUST NOT be set.
[email protected]3de65092013-10-24 09:39:4481 1014, 3000, // 1014 unassigned; 1015 up to 2999 are reserved.
82 5000, 65536, // Codes above 5000 are invalid.
83 };
84 const int* const kInvalidRangesEnd =
85 kInvalidRanges + arraysize(kInvalidRanges);
86
87 DCHECK_GE(code, 0);
88 DCHECK_LT(code, 65536);
89 const int* upper = std::upper_bound(kInvalidRanges, kInvalidRangesEnd, code);
90 DCHECK_NE(kInvalidRangesEnd, upper);
91 DCHECK_GT(upper, kInvalidRanges);
92 DCHECK_GT(*upper, code);
93 DCHECK_LE(*(upper - 1), code);
94 return ((upper - kInvalidRanges) % 2) == 0;
95}
96
[email protected]8b3d14e2014-02-13 14:24:2897// Sets |name| to the name of the frame type for the given |opcode|. Note that
98// for all of Text, Binary and Continuation opcode, this method returns
99// "Data frame".
100void GetFrameTypeForOpcode(WebSocketFrameHeader::OpCode opcode,
101 std::string* name) {
102 switch (opcode) {
103 case WebSocketFrameHeader::kOpCodeText: // fall-thru
104 case WebSocketFrameHeader::kOpCodeBinary: // fall-thru
105 case WebSocketFrameHeader::kOpCodeContinuation:
106 *name = "Data frame";
107 break;
108
109 case WebSocketFrameHeader::kOpCodePing:
110 *name = "Ping";
111 break;
112
113 case WebSocketFrameHeader::kOpCodePong:
114 *name = "Pong";
115 break;
116
117 case WebSocketFrameHeader::kOpCodeClose:
118 *name = "Close";
119 break;
120
121 default:
122 *name = "Unknown frame type";
123 break;
124 }
125
126 return;
127}
128
[email protected]999bcaa2013-07-17 13:42:54129} // namespace
130
131// A class to encapsulate a set of frames and information about the size of
132// those frames.
133class WebSocketChannel::SendBuffer {
134 public:
135 SendBuffer() : total_bytes_(0) {}
136
[email protected]2f5d9f62013-09-26 12:14:28137 // Add a WebSocketFrame to the buffer and increase total_bytes_.
138 void AddFrame(scoped_ptr<WebSocketFrame> chunk);
[email protected]999bcaa2013-07-17 13:42:54139
140 // Return a pointer to the frames_ for write purposes.
[email protected]2f5d9f62013-09-26 12:14:28141 ScopedVector<WebSocketFrame>* frames() { return &frames_; }
[email protected]999bcaa2013-07-17 13:42:54142
143 private:
144 // The frames_ that will be sent in the next call to WriteFrames().
[email protected]2f5d9f62013-09-26 12:14:28145 ScopedVector<WebSocketFrame> frames_;
[email protected]999bcaa2013-07-17 13:42:54146
[email protected]2f5d9f62013-09-26 12:14:28147 // The total size of the payload data in |frames_|. This will be used to
148 // measure the throughput of the link.
[email protected]999bcaa2013-07-17 13:42:54149 // TODO(ricea): Measure the throughput of the link.
pkasting4bff6be2014-10-15 17:54:34150 uint64 total_bytes_;
[email protected]999bcaa2013-07-17 13:42:54151};
152
[email protected]2f5d9f62013-09-26 12:14:28153void WebSocketChannel::SendBuffer::AddFrame(scoped_ptr<WebSocketFrame> frame) {
154 total_bytes_ += frame->header.payload_length;
hari.singh1b87973c2015-06-01 13:34:07155 frames_.push_back(frame.Pass());
[email protected]999bcaa2013-07-17 13:42:54156}
157
158// Implementation of WebSocketStream::ConnectDelegate that simply forwards the
159// calls on to the WebSocketChannel that created it.
160class WebSocketChannel::ConnectDelegate
161 : public WebSocketStream::ConnectDelegate {
162 public:
163 explicit ConnectDelegate(WebSocketChannel* creator) : creator_(creator) {}
164
dchengb03027d2014-10-21 12:00:20165 void OnSuccess(scoped_ptr<WebSocketStream> stream) override {
[email protected]999bcaa2013-07-17 13:42:54166 creator_->OnConnectSuccess(stream.Pass());
[email protected]f485985e2013-10-24 13:47:44167 // |this| may have been deleted.
[email protected]999bcaa2013-07-17 13:42:54168 }
169
dchengb03027d2014-10-21 12:00:20170 void OnFailure(const std::string& message) override {
[email protected]96868202014-01-09 10:38:04171 creator_->OnConnectFailure(message);
[email protected]f485985e2013-10-24 13:47:44172 // |this| has been deleted.
[email protected]999bcaa2013-07-17 13:42:54173 }
174
dchengb03027d2014-10-21 12:00:20175 void OnStartOpeningHandshake(
mostynbba063d6032014-10-09 11:01:13176 scoped_ptr<WebSocketHandshakeRequestInfo> request) override {
[email protected]cd48ed12014-01-22 14:34:22177 creator_->OnStartOpeningHandshake(request.Pass());
178 }
179
dchengb03027d2014-10-21 12:00:20180 void OnFinishOpeningHandshake(
mostynbba063d6032014-10-09 11:01:13181 scoped_ptr<WebSocketHandshakeResponseInfo> response) override {
[email protected]cd48ed12014-01-22 14:34:22182 creator_->OnFinishOpeningHandshake(response.Pass());
183 }
184
dchengb03027d2014-10-21 12:00:20185 void OnSSLCertificateError(
[email protected]a62449522014-06-05 11:11:15186 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>
187 ssl_error_callbacks,
188 const SSLInfo& ssl_info,
mostynbba063d6032014-10-09 11:01:13189 bool fatal) override {
[email protected]a62449522014-06-05 11:11:15190 creator_->OnSSLCertificateError(
191 ssl_error_callbacks.Pass(), ssl_info, fatal);
192 }
193
[email protected]999bcaa2013-07-17 13:42:54194 private:
[email protected]caab2cc2013-08-27 10:24:37195 // A pointer to the WebSocketChannel that created this object. There is no
196 // danger of this pointer being stale, because deleting the WebSocketChannel
197 // cancels the connect process, deleting this object and preventing its
198 // callbacks from being called.
[email protected]999bcaa2013-07-17 13:42:54199 WebSocketChannel* const creator_;
200
201 DISALLOW_COPY_AND_ASSIGN(ConnectDelegate);
202};
203
[email protected]cd48ed12014-01-22 14:34:22204class WebSocketChannel::HandshakeNotificationSender
205 : public base::SupportsWeakPtr<HandshakeNotificationSender> {
206 public:
207 explicit HandshakeNotificationSender(WebSocketChannel* channel);
208 ~HandshakeNotificationSender();
209
210 static void Send(base::WeakPtr<HandshakeNotificationSender> sender);
211
212 ChannelState SendImmediately(WebSocketEventInterface* event_interface);
213
214 const WebSocketHandshakeRequestInfo* handshake_request_info() const {
215 return handshake_request_info_.get();
216 }
217
218 void set_handshake_request_info(
219 scoped_ptr<WebSocketHandshakeRequestInfo> request_info) {
220 handshake_request_info_ = request_info.Pass();
221 }
222
223 const WebSocketHandshakeResponseInfo* handshake_response_info() const {
224 return handshake_response_info_.get();
225 }
226
227 void set_handshake_response_info(
228 scoped_ptr<WebSocketHandshakeResponseInfo> response_info) {
229 handshake_response_info_ = response_info.Pass();
230 }
231
232 private:
233 WebSocketChannel* owner_;
234 scoped_ptr<WebSocketHandshakeRequestInfo> handshake_request_info_;
235 scoped_ptr<WebSocketHandshakeResponseInfo> handshake_response_info_;
236};
237
238WebSocketChannel::HandshakeNotificationSender::HandshakeNotificationSender(
[email protected]4256dbb2014-03-24 15:39:36239 WebSocketChannel* channel)
240 : owner_(channel) {}
[email protected]cd48ed12014-01-22 14:34:22241
242WebSocketChannel::HandshakeNotificationSender::~HandshakeNotificationSender() {}
243
244void WebSocketChannel::HandshakeNotificationSender::Send(
245 base::WeakPtr<HandshakeNotificationSender> sender) {
246 // Do nothing if |sender| is already destructed.
247 if (sender) {
248 WebSocketChannel* channel = sender->owner_;
pkasting47ceb872014-10-09 18:53:22249 sender->SendImmediately(channel->event_interface_.get());
[email protected]cd48ed12014-01-22 14:34:22250 }
251}
252
253ChannelState WebSocketChannel::HandshakeNotificationSender::SendImmediately(
254 WebSocketEventInterface* event_interface) {
255
256 if (handshake_request_info_.get()) {
257 if (CHANNEL_DELETED == event_interface->OnStartOpeningHandshake(
[email protected]4256dbb2014-03-24 15:39:36258 handshake_request_info_.Pass()))
[email protected]cd48ed12014-01-22 14:34:22259 return CHANNEL_DELETED;
260 }
261
262 if (handshake_response_info_.get()) {
263 if (CHANNEL_DELETED == event_interface->OnFinishOpeningHandshake(
[email protected]4256dbb2014-03-24 15:39:36264 handshake_response_info_.Pass()))
[email protected]cd48ed12014-01-22 14:34:22265 return CHANNEL_DELETED;
266
267 // TODO(yhirano): We can release |this| to save memory because
268 // there will be no more opening handshake notification.
269 }
270
271 return CHANNEL_ALIVE;
272}
273
[email protected]4256dbb2014-03-24 15:39:36274WebSocketChannel::PendingReceivedFrame::PendingReceivedFrame(
275 bool final,
276 WebSocketFrameHeader::OpCode opcode,
277 const scoped_refptr<IOBuffer>& data,
pkasting4bff6be2014-10-15 17:54:34278 uint64 offset,
279 uint64 size)
[email protected]4256dbb2014-03-24 15:39:36280 : final_(final),
281 opcode_(opcode),
282 data_(data),
283 offset_(offset),
284 size_(size) {}
285
286WebSocketChannel::PendingReceivedFrame::~PendingReceivedFrame() {}
287
288void WebSocketChannel::PendingReceivedFrame::ResetOpcode() {
289 DCHECK(WebSocketFrameHeader::IsKnownDataOpCode(opcode_));
290 opcode_ = WebSocketFrameHeader::kOpCodeContinuation;
291}
292
pkasting4bff6be2014-10-15 17:54:34293void WebSocketChannel::PendingReceivedFrame::DidConsume(uint64 bytes) {
[email protected]4256dbb2014-03-24 15:39:36294 DCHECK_LE(offset_, size_);
295 DCHECK_LE(bytes, size_ - offset_);
296 offset_ += bytes;
297}
298
[email protected]999bcaa2013-07-17 13:42:54299WebSocketChannel::WebSocketChannel(
[email protected]dab33eb2013-10-08 02:27:51300 scoped_ptr<WebSocketEventInterface> event_interface,
301 URLRequestContext* url_request_context)
302 : event_interface_(event_interface.Pass()),
303 url_request_context_(url_request_context),
[email protected]999bcaa2013-07-17 13:42:54304 send_quota_low_water_mark_(kDefaultSendQuotaLowWaterMark),
305 send_quota_high_water_mark_(kDefaultSendQuotaHighWaterMark),
306 current_send_quota_(0),
[email protected]4256dbb2014-03-24 15:39:36307 current_receive_quota_(0),
tyoshinod4d1d302014-11-07 04:31:16308 closing_handshake_timeout_(base::TimeDelta::FromSeconds(
309 kClosingHandshakeTimeoutSeconds)),
310 underlying_connection_close_timeout_(base::TimeDelta::FromSeconds(
311 kUnderlyingConnectionCloseTimeoutSeconds)),
tyoshinoceae3b242014-10-31 06:43:19312 has_received_close_frame_(false),
[email protected]8b3d14e2014-02-13 14:24:28313 received_close_code_(0),
[email protected]cd48ed12014-01-22 14:34:22314 state_(FRESHLY_CONSTRUCTED),
[email protected]48cc6922014-02-10 14:20:48315 notification_sender_(new HandshakeNotificationSender(this)),
316 sending_text_message_(false),
[email protected]4e4bbaae7e2014-02-19 08:28:53317 receiving_text_message_(false),
[email protected]326b8fb2014-02-21 21:14:00318 expecting_to_handle_continuation_(false),
319 initial_frame_forwarded_(false) {}
[email protected]999bcaa2013-07-17 13:42:54320
321WebSocketChannel::~WebSocketChannel() {
[email protected]2f5d9f62013-09-26 12:14:28322 // The stream may hold a pointer to read_frames_, and so it needs to be
[email protected]999bcaa2013-07-17 13:42:54323 // destroyed first.
324 stream_.reset();
[email protected]3a266762013-10-23 08:15:10325 // The timer may have a callback pointing back to us, so stop it just in case
326 // someone decides to run the event loop from their destructor.
tyoshinod4d1d302014-11-07 04:31:16327 close_timer_.Stop();
[email protected]999bcaa2013-07-17 13:42:54328}
329
330void WebSocketChannel::SendAddChannelRequest(
[email protected]dab33eb2013-10-08 02:27:51331 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:54332 const std::vector<std::string>& requested_subprotocols,
mkwst4997ce82015-07-25 12:00:05333 const url::Origin& origin) {
[email protected]999bcaa2013-07-17 13:42:54334 // Delegate to the tested version.
[email protected]969dde72013-11-13 15:59:14335 SendAddChannelRequestWithSuppliedCreator(
[email protected]dab33eb2013-10-08 02:27:51336 socket_url,
[email protected]999bcaa2013-07-17 13:42:54337 requested_subprotocols,
338 origin,
[email protected]999bcaa2013-07-17 13:42:54339 base::Bind(&WebSocketStream::CreateAndConnectStream));
340}
341
[email protected]09ef67362014-04-24 08:48:58342void WebSocketChannel::SetState(State new_state) {
343 DCHECK_NE(state_, new_state);
344
345 if (new_state == CONNECTED)
346 established_on_ = base::TimeTicks::Now();
347 if (state_ == CONNECTED && !established_on_.is_null()) {
348 UMA_HISTOGRAM_LONG_TIMES(
349 "Net.WebSocket.Duration", base::TimeTicks::Now() - established_on_);
350 }
351
352 state_ = new_state;
353}
354
[email protected]c0d29c22013-07-26 20:40:41355bool WebSocketChannel::InClosingState() const {
[email protected]caab2cc2013-08-27 10:24:37356 // The state RECV_CLOSED is not supported here, because it is only used in one
357 // code path and should not leak into the code in general.
[email protected]c0d29c22013-07-26 20:40:41358 DCHECK_NE(RECV_CLOSED, state_)
359 << "InClosingState called with state_ == RECV_CLOSED";
360 return state_ == SEND_CLOSED || state_ == CLOSE_WAIT || state_ == CLOSED;
361}
362
[email protected]999bcaa2013-07-17 13:42:54363void WebSocketChannel::SendFrame(bool fin,
364 WebSocketFrameHeader::OpCode op_code,
365 const std::vector<char>& data) {
366 if (data.size() > INT_MAX) {
367 NOTREACHED() << "Frame size sanity check failed";
368 return;
369 }
370 if (stream_ == NULL) {
371 LOG(DFATAL) << "Got SendFrame without a connection established; "
372 << "misbehaving renderer? fin=" << fin << " op_code=" << op_code
373 << " data.size()=" << data.size();
374 return;
375 }
[email protected]c0d29c22013-07-26 20:40:41376 if (InClosingState()) {
[email protected]b8393cc2014-04-14 06:22:25377 DVLOG(1) << "SendFrame called in state " << state_
378 << ". This may be a bug, or a harmless race.";
[email protected]999bcaa2013-07-17 13:42:54379 return;
380 }
381 if (state_ != CONNECTED) {
382 NOTREACHED() << "SendFrame() called in state " << state_;
383 return;
384 }
[email protected]cb154062014-01-17 03:32:40385 if (data.size() > base::checked_cast<size_t>(current_send_quota_)) {
[email protected]ea56b982014-01-27 03:21:03386 // TODO(ricea): Kill renderer.
pkasting47ceb872014-10-09 18:53:22387 ignore_result(
[email protected]ea56b982014-01-27 03:21:03388 FailChannel("Send quota exceeded", kWebSocketErrorGoingAway, ""));
[email protected]53deacb2013-11-22 14:02:43389 // |this| has been deleted.
[email protected]999bcaa2013-07-17 13:42:54390 return;
391 }
392 if (!WebSocketFrameHeader::IsKnownDataOpCode(op_code)) {
393 LOG(DFATAL) << "Got SendFrame with bogus op_code " << op_code
394 << "; misbehaving renderer? fin=" << fin
395 << " data.size()=" << data.size();
396 return;
397 }
[email protected]48cc6922014-02-10 14:20:48398 if (op_code == WebSocketFrameHeader::kOpCodeText ||
399 (op_code == WebSocketFrameHeader::kOpCodeContinuation &&
400 sending_text_message_)) {
401 StreamingUtf8Validator::State state =
402 outgoing_utf8_validator_.AddBytes(vector_as_array(&data), data.size());
403 if (state == StreamingUtf8Validator::INVALID ||
404 (state == StreamingUtf8Validator::VALID_MIDPOINT && fin)) {
405 // TODO(ricea): Kill renderer.
pkasting47ceb872014-10-09 18:53:22406 ignore_result(
[email protected]48cc6922014-02-10 14:20:48407 FailChannel("Browser sent a text frame containing invalid UTF-8",
408 kWebSocketErrorGoingAway,
409 ""));
410 // |this| has been deleted.
411 return;
412 }
413 sending_text_message_ = !fin;
414 DCHECK(!fin || state == StreamingUtf8Validator::VALID_ENDPOINT);
415 }
[email protected]999bcaa2013-07-17 13:42:54416 current_send_quota_ -= data.size();
417 // TODO(ricea): If current_send_quota_ has dropped below
[email protected]caab2cc2013-08-27 10:24:37418 // send_quota_low_water_mark_, it might be good to increase the "low
419 // water mark" and "high water mark", but only if the link to the WebSocket
420 // server is not saturated.
[email protected]2f5d9f62013-09-26 12:14:28421 scoped_refptr<IOBuffer> buffer(new IOBuffer(data.size()));
[email protected]999bcaa2013-07-17 13:42:54422 std::copy(data.begin(), data.end(), buffer->data());
pkasting47ceb872014-10-09 18:53:22423 ignore_result(SendFrameFromIOBuffer(fin, op_code, buffer, data.size()));
[email protected]f485985e2013-10-24 13:47:44424 // |this| may have been deleted.
[email protected]999bcaa2013-07-17 13:42:54425}
426
427void WebSocketChannel::SendFlowControl(int64 quota) {
[email protected]abda70d2013-12-12 07:53:54428 DCHECK(state_ == CONNECTING || state_ == CONNECTED || state_ == SEND_CLOSED ||
429 state_ == CLOSE_WAIT);
[email protected]4256dbb2014-03-24 15:39:36430 // TODO(ricea): Kill the renderer if it tries to send us a negative quota
431 // value or > INT_MAX.
432 DCHECK_GE(quota, 0);
433 DCHECK_LE(quota, INT_MAX);
434 if (!pending_received_frames_.empty()) {
pkasting4bff6be2014-10-15 17:54:34435 DCHECK_EQ(0u, current_receive_quota_);
[email protected]4256dbb2014-03-24 15:39:36436 }
437 while (!pending_received_frames_.empty() && quota > 0) {
438 PendingReceivedFrame& front = pending_received_frames_.front();
pkasting4bff6be2014-10-15 17:54:34439 const uint64 data_size = front.size() - front.offset();
440 const uint64 bytes_to_send =
441 std::min(base::checked_cast<uint64>(quota), data_size);
[email protected]4256dbb2014-03-24 15:39:36442 const bool final = front.final() && data_size == bytes_to_send;
dchengb206dc412014-08-26 19:46:23443 const char* data =
444 front.data().get() ? front.data()->data() + front.offset() : NULL;
[email protected]82cc04b22014-04-28 12:10:46445 DCHECK(!bytes_to_send || data) << "Non empty data should not be null.";
[email protected]4256dbb2014-03-24 15:39:36446 const std::vector<char> data_vector(data, data + bytes_to_send);
447 DVLOG(3) << "Sending frame previously split due to quota to the "
448 << "renderer: quota=" << quota << " data_size=" << data_size
449 << " bytes_to_send=" << bytes_to_send;
450 if (event_interface_->OnDataFrame(final, front.opcode(), data_vector) ==
451 CHANNEL_DELETED)
452 return;
453 if (bytes_to_send < data_size) {
454 front.DidConsume(bytes_to_send);
455 front.ResetOpcode();
456 return;
457 }
pkasting4bff6be2014-10-15 17:54:34458 quota -= bytes_to_send;
[email protected]4256dbb2014-03-24 15:39:36459
460 pending_received_frames_.pop();
461 }
462 // If current_receive_quota_ == 0 then there is no pending ReadFrames()
463 // operation.
464 const bool start_read =
465 current_receive_quota_ == 0 && quota > 0 &&
466 (state_ == CONNECTED || state_ == SEND_CLOSED || state_ == CLOSE_WAIT);
pkasting4bff6be2014-10-15 17:54:34467 current_receive_quota_ += quota;
[email protected]4256dbb2014-03-24 15:39:36468 if (start_read)
pkasting47ceb872014-10-09 18:53:22469 ignore_result(ReadFrames());
[email protected]4256dbb2014-03-24 15:39:36470 // |this| may have been deleted.
[email protected]999bcaa2013-07-17 13:42:54471}
472
473void WebSocketChannel::StartClosingHandshake(uint16 code,
474 const std::string& reason) {
[email protected]c0d29c22013-07-26 20:40:41475 if (InClosingState()) {
[email protected]e778f322014-07-28 10:00:53476 // When the associated renderer process is killed while the channel is in
477 // CLOSING state we reach here.
[email protected]b8393cc2014-04-14 06:22:25478 DVLOG(1) << "StartClosingHandshake called in state " << state_
479 << ". This may be a bug, or a harmless race.";
[email protected]999bcaa2013-07-17 13:42:54480 return;
481 }
[email protected]6dfd8b32014-02-05 11:24:49482 if (state_ == CONNECTING) {
483 // Abort the in-progress handshake and drop the connection immediately.
484 stream_request_.reset();
[email protected]09ef67362014-04-24 08:48:58485 SetState(CLOSED);
pkasting47ceb872014-10-09 18:53:22486 DoDropChannel(false, kWebSocketErrorAbnormalClosure, "");
[email protected]6dfd8b32014-02-05 11:24:49487 return;
488 }
[email protected]999bcaa2013-07-17 13:42:54489 if (state_ != CONNECTED) {
490 NOTREACHED() << "StartClosingHandshake() called in state " << state_;
491 return;
492 }
tyoshinod4d1d302014-11-07 04:31:16493
494 DCHECK(!close_timer_.IsRunning());
495 // This use of base::Unretained() is safe because we stop the timer in the
496 // destructor.
497 close_timer_.Start(
498 FROM_HERE,
499 closing_handshake_timeout_,
500 base::Bind(&WebSocketChannel::CloseTimeout, base::Unretained(this)));
501
[email protected]3de65092013-10-24 09:39:44502 // Javascript actually only permits 1000 and 3000-4999, but the implementation
503 // itself may produce different codes. The length of |reason| is also checked
504 // by Javascript.
505 if (!IsStrictlyValidCloseStatusCode(code) ||
506 reason.size() > kMaximumCloseReasonLength) {
507 // "InternalServerError" is actually used for errors from any endpoint, per
508 // errata 3227 to RFC6455. If the renderer is sending us an invalid code or
509 // reason it must be malfunctioning in some way, and based on that we
510 // interpret this as an internal error.
[email protected]0f5f1bb2014-04-22 08:34:35511 if (SendClose(kWebSocketErrorInternalServerError, "") != CHANNEL_DELETED) {
512 DCHECK_EQ(CONNECTED, state_);
[email protected]09ef67362014-04-24 08:48:58513 SetState(SEND_CLOSED);
[email protected]0f5f1bb2014-04-22 08:34:35514 }
[email protected]3de65092013-10-24 09:39:44515 return;
516 }
[email protected]3d5637692014-03-19 16:48:22517 if (SendClose(
518 code,
519 StreamingUtf8Validator::Validate(reason) ? reason : std::string()) ==
520 CHANNEL_DELETED)
521 return;
[email protected]0f5f1bb2014-04-22 08:34:35522 DCHECK_EQ(CONNECTED, state_);
[email protected]09ef67362014-04-24 08:48:58523 SetState(SEND_CLOSED);
[email protected]999bcaa2013-07-17 13:42:54524}
525
526void WebSocketChannel::SendAddChannelRequestForTesting(
[email protected]dab33eb2013-10-08 02:27:51527 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:54528 const std::vector<std::string>& requested_subprotocols,
mkwst4997ce82015-07-25 12:00:05529 const url::Origin& origin,
[email protected]969dde72013-11-13 15:59:14530 const WebSocketStreamCreator& creator) {
531 SendAddChannelRequestWithSuppliedCreator(
532 socket_url, requested_subprotocols, origin, creator);
[email protected]3a266762013-10-23 08:15:10533}
534
535void WebSocketChannel::SetClosingHandshakeTimeoutForTesting(
536 base::TimeDelta delay) {
tyoshinod4d1d302014-11-07 04:31:16537 closing_handshake_timeout_ = delay;
538}
539
540void WebSocketChannel::SetUnderlyingConnectionCloseTimeoutForTesting(
541 base::TimeDelta delay) {
542 underlying_connection_close_timeout_ = delay;
[email protected]999bcaa2013-07-17 13:42:54543}
544
[email protected]969dde72013-11-13 15:59:14545void WebSocketChannel::SendAddChannelRequestWithSuppliedCreator(
[email protected]dab33eb2013-10-08 02:27:51546 const GURL& socket_url,
[email protected]999bcaa2013-07-17 13:42:54547 const std::vector<std::string>& requested_subprotocols,
mkwst4997ce82015-07-25 12:00:05548 const url::Origin& origin,
[email protected]969dde72013-11-13 15:59:14549 const WebSocketStreamCreator& creator) {
[email protected]999bcaa2013-07-17 13:42:54550 DCHECK_EQ(FRESHLY_CONSTRUCTED, state_);
[email protected]53deacb2013-11-22 14:02:43551 if (!socket_url.SchemeIsWSOrWSS()) {
552 // TODO(ricea): Kill the renderer (this error should have been caught by
553 // Javascript).
tyoshinoc06da562015-03-06 06:02:42554 ignore_result(event_interface_->OnFailChannel("Invalid scheme"));
[email protected]53deacb2013-11-22 14:02:43555 // |this| is deleted here.
556 return;
557 }
[email protected]dab33eb2013-10-08 02:27:51558 socket_url_ = socket_url;
[email protected]999bcaa2013-07-17 13:42:54559 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate(
560 new ConnectDelegate(this));
[email protected]969dde72013-11-13 15:59:14561 stream_request_ = creator.Run(socket_url_,
[email protected]999bcaa2013-07-17 13:42:54562 requested_subprotocols,
563 origin,
[email protected]dab33eb2013-10-08 02:27:51564 url_request_context_,
[email protected]999bcaa2013-07-17 13:42:54565 BoundNetLog(),
566 connect_delegate.Pass());
[email protected]09ef67362014-04-24 08:48:58567 SetState(CONNECTING);
[email protected]999bcaa2013-07-17 13:42:54568}
569
570void WebSocketChannel::OnConnectSuccess(scoped_ptr<WebSocketStream> stream) {
571 DCHECK(stream);
572 DCHECK_EQ(CONNECTING, state_);
[email protected]09ef67362014-04-24 08:48:58573
[email protected]999bcaa2013-07-17 13:42:54574 stream_ = stream.Pass();
[email protected]09ef67362014-04-24 08:48:58575
576 SetState(CONNECTED);
577
tyoshinoc06da562015-03-06 06:02:42578 if (event_interface_->OnAddChannelResponse(stream_->GetSubProtocol(),
579 stream_->GetExtensions()) ==
[email protected]6c5d9f62014-01-27 15:05:21580 CHANNEL_DELETED)
[email protected]f485985e2013-10-24 13:47:44581 return;
[email protected]999bcaa2013-07-17 13:42:54582
583 // TODO(ricea): Get flow control information from the WebSocketStream once we
584 // have a multiplexing WebSocketStream.
585 current_send_quota_ = send_quota_high_water_mark_;
[email protected]f485985e2013-10-24 13:47:44586 if (event_interface_->OnFlowControl(send_quota_high_water_mark_) ==
587 CHANNEL_DELETED)
588 return;
[email protected]999bcaa2013-07-17 13:42:54589
[email protected]caab2cc2013-08-27 10:24:37590 // |stream_request_| is not used once the connection has succeeded.
[email protected]999bcaa2013-07-17 13:42:54591 stream_request_.reset();
[email protected]4256dbb2014-03-24 15:39:36592
pkasting47ceb872014-10-09 18:53:22593 ignore_result(ReadFrames());
[email protected]f485985e2013-10-24 13:47:44594 // |this| may have been deleted.
[email protected]999bcaa2013-07-17 13:42:54595}
596
[email protected]96868202014-01-09 10:38:04597void WebSocketChannel::OnConnectFailure(const std::string& message) {
[email protected]999bcaa2013-07-17 13:42:54598 DCHECK_EQ(CONNECTING, state_);
[email protected]09ef67362014-04-24 08:48:58599
[email protected]8aba0172014-07-03 12:09:53600 // Copy the message before we delete its owner.
601 std::string message_copy = message;
602
[email protected]09ef67362014-04-24 08:48:58603 SetState(CLOSED);
[email protected]999bcaa2013-07-17 13:42:54604 stream_request_.reset();
[email protected]cd48ed12014-01-22 14:34:22605
606 if (CHANNEL_DELETED ==
607 notification_sender_->SendImmediately(event_interface_.get())) {
608 // |this| has been deleted.
609 return;
610 }
tyoshinoae74d7a2014-11-06 05:24:07611 ChannelState result = event_interface_->OnFailChannel(message_copy);
612 DCHECK_EQ(CHANNEL_DELETED, result);
[email protected]f485985e2013-10-24 13:47:44613 // |this| has been deleted.
[email protected]999bcaa2013-07-17 13:42:54614}
615
[email protected]a62449522014-06-05 11:11:15616void WebSocketChannel::OnSSLCertificateError(
617 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks> ssl_error_callbacks,
618 const SSLInfo& ssl_info,
619 bool fatal) {
pkasting47ceb872014-10-09 18:53:22620 ignore_result(event_interface_->OnSSLCertificateError(
[email protected]a62449522014-06-05 11:11:15621 ssl_error_callbacks.Pass(), socket_url_, ssl_info, fatal));
622}
623
[email protected]cd48ed12014-01-22 14:34:22624void WebSocketChannel::OnStartOpeningHandshake(
625 scoped_ptr<WebSocketHandshakeRequestInfo> request) {
626 DCHECK(!notification_sender_->handshake_request_info());
627
628 // Because it is hard to handle an IPC error synchronously is difficult,
629 // we asynchronously notify the information.
630 notification_sender_->set_handshake_request_info(request.Pass());
631 ScheduleOpeningHandshakeNotification();
632}
633
634void WebSocketChannel::OnFinishOpeningHandshake(
635 scoped_ptr<WebSocketHandshakeResponseInfo> response) {
636 DCHECK(!notification_sender_->handshake_response_info());
637
638 // Because it is hard to handle an IPC error synchronously is difficult,
639 // we asynchronously notify the information.
640 notification_sender_->set_handshake_response_info(response.Pass());
641 ScheduleOpeningHandshakeNotification();
642}
643
644void WebSocketChannel::ScheduleOpeningHandshakeNotification() {
skyostil4891b25b2015-06-11 11:43:45645 base::ThreadTaskRunnerHandle::Get()->PostTask(
646 FROM_HERE, base::Bind(HandshakeNotificationSender::Send,
647 notification_sender_->AsWeakPtr()));
[email protected]cd48ed12014-01-22 14:34:22648}
649
[email protected]f485985e2013-10-24 13:47:44650ChannelState WebSocketChannel::WriteFrames() {
[email protected]999bcaa2013-07-17 13:42:54651 int result = OK;
652 do {
[email protected]caab2cc2013-08-27 10:24:37653 // This use of base::Unretained is safe because this object owns the
654 // WebSocketStream and destroying it cancels all callbacks.
[email protected]999bcaa2013-07-17 13:42:54655 result = stream_->WriteFrames(
[email protected]c0d29c22013-07-26 20:40:41656 data_being_sent_->frames(),
[email protected]f485985e2013-10-24 13:47:44657 base::Bind(base::IgnoreResult(&WebSocketChannel::OnWriteDone),
658 base::Unretained(this),
659 false));
[email protected]999bcaa2013-07-17 13:42:54660 if (result != ERR_IO_PENDING) {
[email protected]f485985e2013-10-24 13:47:44661 if (OnWriteDone(true, result) == CHANNEL_DELETED)
662 return CHANNEL_DELETED;
[email protected]3d5637692014-03-19 16:48:22663 // OnWriteDone() returns CHANNEL_DELETED on error. Here |state_| is
664 // guaranteed to be the same as before OnWriteDone() call.
[email protected]999bcaa2013-07-17 13:42:54665 }
666 } while (result == OK && data_being_sent_);
[email protected]f485985e2013-10-24 13:47:44667 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54668}
669
[email protected]f485985e2013-10-24 13:47:44670ChannelState WebSocketChannel::OnWriteDone(bool synchronous, int result) {
[email protected]999bcaa2013-07-17 13:42:54671 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
672 DCHECK_NE(CONNECTING, state_);
673 DCHECK_NE(ERR_IO_PENDING, result);
674 DCHECK(data_being_sent_);
675 switch (result) {
676 case OK:
677 if (data_to_send_next_) {
678 data_being_sent_ = data_to_send_next_.Pass();
[email protected]f485985e2013-10-24 13:47:44679 if (!synchronous)
680 return WriteFrames();
[email protected]999bcaa2013-07-17 13:42:54681 } else {
682 data_being_sent_.reset();
683 if (current_send_quota_ < send_quota_low_water_mark_) {
684 // TODO(ricea): Increase low_water_mark and high_water_mark if
685 // throughput is high, reduce them if throughput is low. Low water
686 // mark needs to be >= the bandwidth delay product *of the IPC
687 // channel*. Because factors like context-switch time, thread wake-up
688 // time, and bus speed come into play it is complex and probably needs
689 // to be determined empirically.
690 DCHECK_LE(send_quota_low_water_mark_, send_quota_high_water_mark_);
691 // TODO(ricea): Truncate quota by the quota specified by the remote
692 // server, if the protocol in use supports quota.
693 int fresh_quota = send_quota_high_water_mark_ - current_send_quota_;
694 current_send_quota_ += fresh_quota;
[email protected]f485985e2013-10-24 13:47:44695 return event_interface_->OnFlowControl(fresh_quota);
[email protected]999bcaa2013-07-17 13:42:54696 }
697 }
[email protected]f485985e2013-10-24 13:47:44698 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54699
700 // If a recoverable error condition existed, it would go here.
701
702 default:
703 DCHECK_LT(result, 0)
704 << "WriteFrames() should only return OK or ERR_ codes";
[email protected]09ef67362014-04-24 08:48:58705
[email protected]999bcaa2013-07-17 13:42:54706 stream_->Close();
[email protected]09ef67362014-04-24 08:48:58707 SetState(CLOSED);
[email protected]86ec55502014-02-10 13:16:16708 return DoDropChannel(false, kWebSocketErrorAbnormalClosure, "");
[email protected]999bcaa2013-07-17 13:42:54709 }
710}
711
[email protected]f485985e2013-10-24 13:47:44712ChannelState WebSocketChannel::ReadFrames() {
[email protected]999bcaa2013-07-17 13:42:54713 int result = OK;
[email protected]4256dbb2014-03-24 15:39:36714 while (result == OK && current_receive_quota_ > 0) {
[email protected]caab2cc2013-08-27 10:24:37715 // This use of base::Unretained is safe because this object owns the
716 // WebSocketStream, and any pending reads will be cancelled when it is
717 // destroyed.
[email protected]999bcaa2013-07-17 13:42:54718 result = stream_->ReadFrames(
[email protected]2f5d9f62013-09-26 12:14:28719 &read_frames_,
[email protected]f485985e2013-10-24 13:47:44720 base::Bind(base::IgnoreResult(&WebSocketChannel::OnReadDone),
721 base::Unretained(this),
722 false));
[email protected]999bcaa2013-07-17 13:42:54723 if (result != ERR_IO_PENDING) {
[email protected]f485985e2013-10-24 13:47:44724 if (OnReadDone(true, result) == CHANNEL_DELETED)
725 return CHANNEL_DELETED;
[email protected]999bcaa2013-07-17 13:42:54726 }
[email protected]f485985e2013-10-24 13:47:44727 DCHECK_NE(CLOSED, state_);
[email protected]4256dbb2014-03-24 15:39:36728 }
[email protected]f485985e2013-10-24 13:47:44729 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54730}
731
[email protected]f485985e2013-10-24 13:47:44732ChannelState WebSocketChannel::OnReadDone(bool synchronous, int result) {
[email protected]999bcaa2013-07-17 13:42:54733 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
734 DCHECK_NE(CONNECTING, state_);
735 DCHECK_NE(ERR_IO_PENDING, result);
736 switch (result) {
737 case OK:
738 // ReadFrames() must use ERR_CONNECTION_CLOSED for a closed connection
739 // with no data read, not an empty response.
[email protected]2f5d9f62013-09-26 12:14:28740 DCHECK(!read_frames_.empty())
[email protected]999bcaa2013-07-17 13:42:54741 << "ReadFrames() returned OK, but nothing was read.";
[email protected]2f5d9f62013-09-26 12:14:28742 for (size_t i = 0; i < read_frames_.size(); ++i) {
743 scoped_ptr<WebSocketFrame> frame(read_frames_[i]);
744 read_frames_[i] = NULL;
[email protected]8b3d14e2014-02-13 14:24:28745 if (HandleFrame(frame.Pass()) == CHANNEL_DELETED)
[email protected]f485985e2013-10-24 13:47:44746 return CHANNEL_DELETED;
[email protected]999bcaa2013-07-17 13:42:54747 }
[email protected]2f5d9f62013-09-26 12:14:28748 read_frames_.clear();
[email protected]caab2cc2013-08-27 10:24:37749 // There should always be a call to ReadFrames pending.
[email protected]2f5d9f62013-09-26 12:14:28750 // TODO(ricea): Unless we are out of quota.
[email protected]f485985e2013-10-24 13:47:44751 DCHECK_NE(CLOSED, state_);
752 if (!synchronous)
753 return ReadFrames();
754 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54755
[email protected]2f5d9f62013-09-26 12:14:28756 case ERR_WS_PROTOCOL_ERROR:
[email protected]ea56b982014-01-27 03:21:03757 // This could be kWebSocketErrorProtocolError (specifically, non-minimal
758 // encoding of payload length) or kWebSocketErrorMessageTooBig, or an
759 // extension-specific error.
760 return FailChannel("Invalid frame header",
[email protected]f485985e2013-10-24 13:47:44761 kWebSocketErrorProtocolError,
762 "WebSocket Protocol Error");
[email protected]2f5d9f62013-09-26 12:14:28763
[email protected]c0d29c22013-07-26 20:40:41764 default:
[email protected]999bcaa2013-07-17 13:42:54765 DCHECK_LT(result, 0)
766 << "ReadFrames() should only return OK or ERR_ codes";
[email protected]09ef67362014-04-24 08:48:58767
[email protected]999bcaa2013-07-17 13:42:54768 stream_->Close();
[email protected]09ef67362014-04-24 08:48:58769 SetState(CLOSED);
770
[email protected]f485985e2013-10-24 13:47:44771 uint16 code = kWebSocketErrorAbnormalClosure;
[email protected]5742ae62014-02-06 11:03:18772 std::string reason = "";
[email protected]86ec55502014-02-10 13:16:16773 bool was_clean = false;
tyoshinoceae3b242014-10-31 06:43:19774 if (has_received_close_frame_) {
[email protected]8b3d14e2014-02-13 14:24:28775 code = received_close_code_;
776 reason = received_close_reason_;
[email protected]86ec55502014-02-10 13:16:16777 was_clean = (result == ERR_CONNECTION_CLOSED);
[email protected]999bcaa2013-07-17 13:42:54778 }
[email protected]09ef67362014-04-24 08:48:58779
[email protected]86ec55502014-02-10 13:16:16780 return DoDropChannel(was_clean, code, reason);
[email protected]999bcaa2013-07-17 13:42:54781 }
782}
783
[email protected]4256dbb2014-03-24 15:39:36784ChannelState WebSocketChannel::HandleFrame(scoped_ptr<WebSocketFrame> frame) {
[email protected]2f5d9f62013-09-26 12:14:28785 if (frame->header.masked) {
786 // RFC6455 Section 5.1 "A client MUST close a connection if it detects a
787 // masked frame."
[email protected]ea56b982014-01-27 03:21:03788 return FailChannel(
789 "A server must not mask any frames that it sends to the "
790 "client.",
791 kWebSocketErrorProtocolError,
792 "Masked frame from server");
[email protected]999bcaa2013-07-17 13:42:54793 }
[email protected]2f5d9f62013-09-26 12:14:28794 const WebSocketFrameHeader::OpCode opcode = frame->header.opcode;
[email protected]bae48422014-03-05 15:07:25795 DCHECK(!WebSocketFrameHeader::IsKnownControlOpCode(opcode) ||
796 frame->header.final);
[email protected]658d7672014-02-26 13:11:35797 if (frame->header.reserved1 || frame->header.reserved2 ||
798 frame->header.reserved3) {
[email protected]c46c2612014-02-28 17:08:02799 return FailChannel(base::StringPrintf(
800 "One or more reserved bits are on: reserved1 = %d, "
801 "reserved2 = %d, reserved3 = %d",
802 static_cast<int>(frame->header.reserved1),
803 static_cast<int>(frame->header.reserved2),
804 static_cast<int>(frame->header.reserved3)),
[email protected]658d7672014-02-26 13:11:35805 kWebSocketErrorProtocolError,
806 "Invalid reserved bit");
807 }
[email protected]999bcaa2013-07-17 13:42:54808
[email protected]999bcaa2013-07-17 13:42:54809 // Respond to the frame appropriately to its type.
[email protected]8b3d14e2014-02-13 14:24:28810 return HandleFrameByState(
[email protected]2f5d9f62013-09-26 12:14:28811 opcode, frame->header.final, frame->data, frame->header.payload_length);
[email protected]999bcaa2013-07-17 13:42:54812}
813
[email protected]8b3d14e2014-02-13 14:24:28814ChannelState WebSocketChannel::HandleFrameByState(
[email protected]f485985e2013-10-24 13:47:44815 const WebSocketFrameHeader::OpCode opcode,
816 bool final,
817 const scoped_refptr<IOBuffer>& data_buffer,
pkasting4bff6be2014-10-15 17:54:34818 uint64 size) {
[email protected]999bcaa2013-07-17 13:42:54819 DCHECK_NE(RECV_CLOSED, state_)
820 << "HandleFrame() does not support being called re-entrantly from within "
821 "SendClose()";
[email protected]f485985e2013-10-24 13:47:44822 DCHECK_NE(CLOSED, state_);
823 if (state_ == CLOSE_WAIT) {
[email protected]999bcaa2013-07-17 13:42:54824 std::string frame_name;
[email protected]8b3d14e2014-02-13 14:24:28825 GetFrameTypeForOpcode(opcode, &frame_name);
[email protected]999bcaa2013-07-17 13:42:54826
[email protected]ea56b982014-01-27 03:21:03827 // FailChannel() won't send another Close frame.
828 return FailChannel(
829 frame_name + " received after close", kWebSocketErrorProtocolError, "");
[email protected]999bcaa2013-07-17 13:42:54830 }
831 switch (opcode) {
[email protected]4256dbb2014-03-24 15:39:36832 case WebSocketFrameHeader::kOpCodeText: // fall-thru
[email protected]4e4bbaae7e2014-02-19 08:28:53833 case WebSocketFrameHeader::kOpCodeBinary:
[email protected]999bcaa2013-07-17 13:42:54834 case WebSocketFrameHeader::kOpCodeContinuation:
[email protected]4e4bbaae7e2014-02-19 08:28:53835 return HandleDataFrame(opcode, final, data_buffer, size);
[email protected]999bcaa2013-07-17 13:42:54836
837 case WebSocketFrameHeader::kOpCodePing:
[email protected]b8393cc2014-04-14 06:22:25838 DVLOG(1) << "Got Ping of size " << size;
[email protected]f485985e2013-10-24 13:47:44839 if (state_ == CONNECTED)
[email protected]a691b6c32014-03-24 16:09:08840 return SendFrameFromIOBuffer(
[email protected]2f5d9f62013-09-26 12:14:28841 true, WebSocketFrameHeader::kOpCodePong, data_buffer, size);
[email protected]b8393cc2014-04-14 06:22:25842 DVLOG(3) << "Ignored ping in state " << state_;
[email protected]f485985e2013-10-24 13:47:44843 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54844
845 case WebSocketFrameHeader::kOpCodePong:
[email protected]b8393cc2014-04-14 06:22:25846 DVLOG(1) << "Got Pong of size " << size;
[email protected]caab2cc2013-08-27 10:24:37847 // There is no need to do anything with pong messages.
[email protected]f485985e2013-10-24 13:47:44848 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54849
850 case WebSocketFrameHeader::kOpCodeClose: {
[email protected]4256dbb2014-03-24 15:39:36851 // TODO(ricea): If there is a message which is queued for transmission to
852 // the renderer, then the renderer should not receive an
853 // OnClosingHandshake or OnDropChannel IPC until the queued message has
854 // been completedly transmitted.
[email protected]999bcaa2013-07-17 13:42:54855 uint16 code = kWebSocketNormalClosure;
856 std::string reason;
[email protected]ea56b982014-01-27 03:21:03857 std::string message;
858 if (!ParseClose(data_buffer, size, &code, &reason, &message)) {
859 return FailChannel(message, code, reason);
860 }
[email protected]999bcaa2013-07-17 13:42:54861 // TODO(ricea): Find a way to safely log the message from the close
862 // message (escape control codes and so on).
[email protected]b8393cc2014-04-14 06:22:25863 DVLOG(1) << "Got Close with code " << code;
[email protected]999bcaa2013-07-17 13:42:54864 switch (state_) {
865 case CONNECTED:
[email protected]09ef67362014-04-24 08:48:58866 SetState(RECV_CLOSED);
tyoshinod4d1d302014-11-07 04:31:16867
[email protected]3d5637692014-03-19 16:48:22868 if (SendClose(code, reason) == CHANNEL_DELETED)
[email protected]f485985e2013-10-24 13:47:44869 return CHANNEL_DELETED;
[email protected]0f5f1bb2014-04-22 08:34:35870 DCHECK_EQ(RECV_CLOSED, state_);
tyoshinod4d1d302014-11-07 04:31:16871
[email protected]09ef67362014-04-24 08:48:58872 SetState(CLOSE_WAIT);
tyoshinod4d1d302014-11-07 04:31:16873 DCHECK(!close_timer_.IsRunning());
874 // This use of base::Unretained() is safe because we stop the timer
875 // in the destructor.
876 close_timer_.Start(
877 FROM_HERE,
878 underlying_connection_close_timeout_,
879 base::Bind(
880 &WebSocketChannel::CloseTimeout, base::Unretained(this)));
[email protected]3d5637692014-03-19 16:48:22881
[email protected]f485985e2013-10-24 13:47:44882 if (event_interface_->OnClosingHandshake() == CHANNEL_DELETED)
883 return CHANNEL_DELETED;
tyoshinoceae3b242014-10-31 06:43:19884 has_received_close_frame_ = true;
[email protected]8b3d14e2014-02-13 14:24:28885 received_close_code_ = code;
886 received_close_reason_ = reason;
[email protected]999bcaa2013-07-17 13:42:54887 break;
888
889 case SEND_CLOSED:
[email protected]09ef67362014-04-24 08:48:58890 SetState(CLOSE_WAIT);
tyoshinod4d1d302014-11-07 04:31:16891 DCHECK(close_timer_.IsRunning());
892 close_timer_.Stop();
893 // This use of base::Unretained() is safe because we stop the timer
894 // in the destructor.
895 close_timer_.Start(
896 FROM_HERE,
897 underlying_connection_close_timeout_,
898 base::Bind(
899 &WebSocketChannel::CloseTimeout, base::Unretained(this)));
900
[email protected]999bcaa2013-07-17 13:42:54901 // From RFC6455 section 7.1.5: "Each endpoint
902 // will see the status code sent by the other end as _The WebSocket
903 // Connection Close Code_."
tyoshinoceae3b242014-10-31 06:43:19904 has_received_close_frame_ = true;
[email protected]8b3d14e2014-02-13 14:24:28905 received_close_code_ = code;
906 received_close_reason_ = reason;
[email protected]999bcaa2013-07-17 13:42:54907 break;
908
909 default:
910 LOG(DFATAL) << "Got Close in unexpected state " << state_;
911 break;
912 }
[email protected]f485985e2013-10-24 13:47:44913 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:54914 }
915
916 default:
[email protected]f485985e2013-10-24 13:47:44917 return FailChannel(
[email protected]ea56b982014-01-27 03:21:03918 base::StringPrintf("Unrecognized frame opcode: %d", opcode),
919 kWebSocketErrorProtocolError,
920 "Unknown opcode");
[email protected]999bcaa2013-07-17 13:42:54921 }
922}
923
[email protected]4e4bbaae7e2014-02-19 08:28:53924ChannelState WebSocketChannel::HandleDataFrame(
[email protected]326b8fb2014-02-21 21:14:00925 WebSocketFrameHeader::OpCode opcode,
[email protected]4e4bbaae7e2014-02-19 08:28:53926 bool final,
927 const scoped_refptr<IOBuffer>& data_buffer,
pkasting4bff6be2014-10-15 17:54:34928 uint64 size) {
[email protected]4e4bbaae7e2014-02-19 08:28:53929 if (state_ != CONNECTED) {
930 DVLOG(3) << "Ignored data packet received in state " << state_;
931 return CHANNEL_ALIVE;
932 }
933 DCHECK(opcode == WebSocketFrameHeader::kOpCodeContinuation ||
934 opcode == WebSocketFrameHeader::kOpCodeText ||
935 opcode == WebSocketFrameHeader::kOpCodeBinary);
936 const bool got_continuation =
937 (opcode == WebSocketFrameHeader::kOpCodeContinuation);
938 if (got_continuation != expecting_to_handle_continuation_) {
939 const std::string console_log = got_continuation
940 ? "Received unexpected continuation frame."
941 : "Received start of new message but previous message is unfinished.";
942 const std::string reason = got_continuation
943 ? "Unexpected continuation"
944 : "Previous data frame unfinished";
945 return FailChannel(console_log, kWebSocketErrorProtocolError, reason);
946 }
947 expecting_to_handle_continuation_ = !final;
[email protected]326b8fb2014-02-21 21:14:00948 WebSocketFrameHeader::OpCode opcode_to_send = opcode;
949 if (!initial_frame_forwarded_ &&
950 opcode == WebSocketFrameHeader::kOpCodeContinuation) {
951 opcode_to_send = receiving_text_message_
952 ? WebSocketFrameHeader::kOpCodeText
953 : WebSocketFrameHeader::kOpCodeBinary;
954 }
[email protected]4e4bbaae7e2014-02-19 08:28:53955 if (opcode == WebSocketFrameHeader::kOpCodeText ||
956 (opcode == WebSocketFrameHeader::kOpCodeContinuation &&
957 receiving_text_message_)) {
958 // This call is not redundant when size == 0 because it tells us what
959 // the current state is.
960 StreamingUtf8Validator::State state = incoming_utf8_validator_.AddBytes(
pkasting4bff6be2014-10-15 17:54:34961 size ? data_buffer->data() : NULL, static_cast<size_t>(size));
[email protected]4e4bbaae7e2014-02-19 08:28:53962 if (state == StreamingUtf8Validator::INVALID ||
963 (state == StreamingUtf8Validator::VALID_MIDPOINT && final)) {
964 return FailChannel("Could not decode a text frame as UTF-8.",
965 kWebSocketErrorProtocolError,
966 "Invalid UTF-8 in text frame");
967 }
968 receiving_text_message_ = !final;
969 DCHECK(!final || state == StreamingUtf8Validator::VALID_ENDPOINT);
970 }
[email protected]326b8fb2014-02-21 21:14:00971 if (size == 0U && !final)
972 return CHANNEL_ALIVE;
973
974 initial_frame_forwarded_ = !final;
pkasting4bff6be2014-10-15 17:54:34975 if (size > current_receive_quota_ || !pending_received_frames_.empty()) {
[email protected]4256dbb2014-03-24 15:39:36976 const bool no_quota = (current_receive_quota_ == 0);
977 DCHECK(no_quota || pending_received_frames_.empty());
978 DVLOG(3) << "Queueing frame to renderer due to quota. quota="
979 << current_receive_quota_ << " size=" << size;
980 WebSocketFrameHeader::OpCode opcode_to_queue =
981 no_quota ? opcode_to_send : WebSocketFrameHeader::kOpCodeContinuation;
982 pending_received_frames_.push(PendingReceivedFrame(
983 final, opcode_to_queue, data_buffer, current_receive_quota_, size));
984 if (no_quota)
985 return CHANNEL_ALIVE;
986 size = current_receive_quota_;
987 final = false;
988 }
989
[email protected]4e4bbaae7e2014-02-19 08:28:53990 // TODO(ricea): Can this copy be eliminated?
991 const char* const data_begin = size ? data_buffer->data() : NULL;
992 const char* const data_end = data_begin + size;
993 const std::vector<char> data(data_begin, data_end);
[email protected]4256dbb2014-03-24 15:39:36994 current_receive_quota_ -= size;
[email protected]4e4bbaae7e2014-02-19 08:28:53995
996 // Sends the received frame to the renderer process.
[email protected]326b8fb2014-02-21 21:14:00997 return event_interface_->OnDataFrame(final, opcode_to_send, data);
[email protected]4e4bbaae7e2014-02-19 08:28:53998}
999
[email protected]a691b6c32014-03-24 16:09:081000ChannelState WebSocketChannel::SendFrameFromIOBuffer(
[email protected]f485985e2013-10-24 13:47:441001 bool fin,
1002 WebSocketFrameHeader::OpCode op_code,
1003 const scoped_refptr<IOBuffer>& buffer,
pkasting4bff6be2014-10-15 17:54:341004 uint64 size) {
[email protected]999bcaa2013-07-17 13:42:541005 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED);
1006 DCHECK(stream_);
[email protected]3d5637692014-03-19 16:48:221007
[email protected]2f5d9f62013-09-26 12:14:281008 scoped_ptr<WebSocketFrame> frame(new WebSocketFrame(op_code));
1009 WebSocketFrameHeader& header = frame->header;
1010 header.final = fin;
1011 header.masked = true;
1012 header.payload_length = size;
1013 frame->data = buffer;
[email protected]3d5637692014-03-19 16:48:221014
[email protected]999bcaa2013-07-17 13:42:541015 if (data_being_sent_) {
[email protected]caab2cc2013-08-27 10:24:371016 // Either the link to the WebSocket server is saturated, or several messages
1017 // are being sent in a batch.
1018 // TODO(ricea): Keep some statistics to work out the situation and adjust
1019 // quota appropriately.
[email protected]999bcaa2013-07-17 13:42:541020 if (!data_to_send_next_)
1021 data_to_send_next_.reset(new SendBuffer);
[email protected]2f5d9f62013-09-26 12:14:281022 data_to_send_next_->AddFrame(frame.Pass());
[email protected]f485985e2013-10-24 13:47:441023 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:541024 }
[email protected]3d5637692014-03-19 16:48:221025
[email protected]f485985e2013-10-24 13:47:441026 data_being_sent_.reset(new SendBuffer);
1027 data_being_sent_->AddFrame(frame.Pass());
1028 return WriteFrames();
[email protected]999bcaa2013-07-17 13:42:541029}
1030
[email protected]ea56b982014-01-27 03:21:031031ChannelState WebSocketChannel::FailChannel(const std::string& message,
[email protected]f485985e2013-10-24 13:47:441032 uint16 code,
1033 const std::string& reason) {
[email protected]999bcaa2013-07-17 13:42:541034 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
1035 DCHECK_NE(CONNECTING, state_);
[email protected]f485985e2013-10-24 13:47:441036 DCHECK_NE(CLOSED, state_);
[email protected]09ef67362014-04-24 08:48:581037
[email protected]999bcaa2013-07-17 13:42:541038 // TODO(ricea): Logging.
[email protected]999bcaa2013-07-17 13:42:541039 if (state_ == CONNECTED) {
[email protected]3d5637692014-03-19 16:48:221040 if (SendClose(code, reason) == CHANNEL_DELETED)
[email protected]f485985e2013-10-24 13:47:441041 return CHANNEL_DELETED;
[email protected]999bcaa2013-07-17 13:42:541042 }
[email protected]09ef67362014-04-24 08:48:581043
[email protected]caab2cc2013-08-27 10:24:371044 // Careful study of RFC6455 section 7.1.7 and 7.1.1 indicates the browser
1045 // should close the connection itself without waiting for the closing
1046 // handshake.
[email protected]999bcaa2013-07-17 13:42:541047 stream_->Close();
[email protected]09ef67362014-04-24 08:48:581048 SetState(CLOSED);
tyoshinoae74d7a2014-11-06 05:24:071049 ChannelState result = event_interface_->OnFailChannel(message);
1050 DCHECK_EQ(CHANNEL_DELETED, result);
1051 return result;
[email protected]999bcaa2013-07-17 13:42:541052}
1053
[email protected]f485985e2013-10-24 13:47:441054ChannelState WebSocketChannel::SendClose(uint16 code,
1055 const std::string& reason) {
[email protected]999bcaa2013-07-17 13:42:541056 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED);
[email protected]3de65092013-10-24 09:39:441057 DCHECK_LE(reason.size(), kMaximumCloseReasonLength);
[email protected]2f5d9f62013-09-26 12:14:281058 scoped_refptr<IOBuffer> body;
pkasting4bff6be2014-10-15 17:54:341059 uint64 size = 0;
[email protected]c0d29c22013-07-26 20:40:411060 if (code == kWebSocketErrorNoStatusReceived) {
1061 // Special case: translate kWebSocketErrorNoStatusReceived into a Close
1062 // frame with no payload.
[email protected]aa984e5f2014-02-26 07:33:091063 DCHECK(reason.empty());
[email protected]2f5d9f62013-09-26 12:14:281064 body = new IOBuffer(0);
[email protected]c0d29c22013-07-26 20:40:411065 } else {
1066 const size_t payload_length = kWebSocketCloseCodeLength + reason.length();
[email protected]2f5d9f62013-09-26 12:14:281067 body = new IOBuffer(payload_length);
1068 size = payload_length;
[email protected]d9806a972014-02-26 18:14:571069 base::WriteBigEndian(body->data(), code);
mostynb91e0da982015-01-20 19:17:271070 static_assert(sizeof(code) == kWebSocketCloseCodeLength,
1071 "they should both be two");
[email protected]c0d29c22013-07-26 20:40:411072 std::copy(
1073 reason.begin(), reason.end(), body->data() + kWebSocketCloseCodeLength);
1074 }
[email protected]a691b6c32014-03-24 16:09:081075 if (SendFrameFromIOBuffer(
1076 true, WebSocketFrameHeader::kOpCodeClose, body, size) ==
[email protected]f485985e2013-10-24 13:47:441077 CHANNEL_DELETED)
1078 return CHANNEL_DELETED;
[email protected]f485985e2013-10-24 13:47:441079 return CHANNEL_ALIVE;
[email protected]999bcaa2013-07-17 13:42:541080}
1081
[email protected]ea56b982014-01-27 03:21:031082bool WebSocketChannel::ParseClose(const scoped_refptr<IOBuffer>& buffer,
pkasting4bff6be2014-10-15 17:54:341083 uint64 size,
[email protected]999bcaa2013-07-17 13:42:541084 uint16* code,
[email protected]ea56b982014-01-27 03:21:031085 std::string* reason,
1086 std::string* message) {
[email protected]999bcaa2013-07-17 13:42:541087 reason->clear();
1088 if (size < kWebSocketCloseCodeLength) {
[email protected]c4432932014-03-19 05:55:131089 if (size == 0U) {
1090 *code = kWebSocketErrorNoStatusReceived;
1091 return true;
[email protected]999bcaa2013-07-17 13:42:541092 }
[email protected]c4432932014-03-19 05:55:131093
1094 DVLOG(1) << "Close frame with payload size " << size << " received "
1095 << "(the first byte is " << std::hex
1096 << static_cast<int>(buffer->data()[0]) << ")";
1097 *code = kWebSocketErrorProtocolError;
1098 *message =
1099 "Received a broken close frame containing an invalid size body.";
1100 return false;
[email protected]999bcaa2013-07-17 13:42:541101 }
[email protected]c4432932014-03-19 05:55:131102
[email protected]00f4daf2013-11-12 13:56:411103 const char* data = buffer->data();
[email protected]999bcaa2013-07-17 13:42:541104 uint16 unchecked_code = 0;
[email protected]d9806a972014-02-26 18:14:571105 base::ReadBigEndian(data, &unchecked_code);
mostynb91e0da982015-01-20 19:17:271106 static_assert(sizeof(unchecked_code) == kWebSocketCloseCodeLength,
1107 "they should both be two bytes");
[email protected]c4432932014-03-19 05:55:131108
[email protected]ea56b982014-01-27 03:21:031109 switch (unchecked_code) {
1110 case kWebSocketErrorNoStatusReceived:
1111 case kWebSocketErrorAbnormalClosure:
1112 case kWebSocketErrorTlsHandshake:
1113 *code = kWebSocketErrorProtocolError;
1114 *message =
1115 "Received a broken close frame containing a reserved status code.";
[email protected]c4432932014-03-19 05:55:131116 return false;
[email protected]ea56b982014-01-27 03:21:031117
1118 default:
1119 *code = unchecked_code;
1120 break;
[email protected]999bcaa2013-07-17 13:42:541121 }
[email protected]c4432932014-03-19 05:55:131122
1123 std::string text(data + kWebSocketCloseCodeLength, data + size);
1124 if (StreamingUtf8Validator::Validate(text)) {
1125 reason->swap(text);
1126 return true;
[email protected]999bcaa2013-07-17 13:42:541127 }
[email protected]c4432932014-03-19 05:55:131128
1129 *code = kWebSocketErrorProtocolError;
1130 *reason = "Invalid UTF-8 in Close frame";
1131 *message = "Received a broken close frame containing invalid UTF-8.";
1132 return false;
[email protected]999bcaa2013-07-17 13:42:541133}
1134
[email protected]86ec55502014-02-10 13:16:161135ChannelState WebSocketChannel::DoDropChannel(bool was_clean,
1136 uint16 code,
[email protected]cd48ed12014-01-22 14:34:221137 const std::string& reason) {
1138 if (CHANNEL_DELETED ==
1139 notification_sender_->SendImmediately(event_interface_.get()))
1140 return CHANNEL_DELETED;
[email protected]3d5637692014-03-19 16:48:221141 ChannelState result =
1142 event_interface_->OnDropChannel(was_clean, code, reason);
1143 DCHECK_EQ(CHANNEL_DELETED, result);
1144 return result;
[email protected]cd48ed12014-01-22 14:34:221145}
1146
[email protected]3a266762013-10-23 08:15:101147void WebSocketChannel::CloseTimeout() {
1148 stream_->Close();
[email protected]09ef67362014-04-24 08:48:581149 SetState(CLOSED);
pkasting47ceb872014-10-09 18:53:221150 DoDropChannel(false, kWebSocketErrorAbnormalClosure, "");
[email protected]f485985e2013-10-24 13:47:441151 // |this| has been deleted.
[email protected]3a266762013-10-23 08:15:101152}
1153
[email protected]999bcaa2013-07-17 13:42:541154} // namespace net