Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(45)

Side by Side Diff: net/websockets/websocket_channel.cc

Issue 26544003: Make net::WebSocketChannel deletion safe and enable new IPCs (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Add missing "virtual" keyword Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2013 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/websockets/websocket_channel.h" 5 #include "net/websockets/websocket_channel.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 8
9 #include "base/basictypes.h" // for size_t 9 #include "base/basictypes.h" // for size_t
10 #include "base/bind.h" 10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
11 #include "base/safe_numerics.h" 12 #include "base/safe_numerics.h"
12 #include "base/strings/string_util.h" 13 #include "base/strings/string_util.h"
13 #include "net/base/big_endian.h" 14 #include "net/base/big_endian.h"
14 #include "net/base/io_buffer.h" 15 #include "net/base/io_buffer.h"
15 #include "net/base/net_log.h" 16 #include "net/base/net_log.h"
16 #include "net/websockets/websocket_errors.h" 17 #include "net/websockets/websocket_errors.h"
17 #include "net/websockets/websocket_event_interface.h" 18 #include "net/websockets/websocket_event_interface.h"
18 #include "net/websockets/websocket_frame.h" 19 #include "net/websockets/websocket_frame.h"
19 #include "net/websockets/websocket_mux.h" 20 #include "net/websockets/websocket_mux.h"
20 #include "net/websockets/websocket_stream.h" 21 #include "net/websockets/websocket_stream.h"
21 22
22 namespace net { 23 namespace net {
23 24
24 namespace { 25 namespace {
25 26
26 const int kDefaultSendQuotaLowWaterMark = 1 << 16; 27 const int kDefaultSendQuotaLowWaterMark = 1 << 16;
27 const int kDefaultSendQuotaHighWaterMark = 1 << 17; 28 const int kDefaultSendQuotaHighWaterMark = 1 << 17;
28 const size_t kWebSocketCloseCodeLength = 2; 29 const size_t kWebSocketCloseCodeLength = 2;
30 typedef WebSocketEventInterface::ChannelState ChannelState;
31 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
32 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
33
34 // This function avoids a bunch of boilerplate code.
35 void AllowUnused(ChannelState ALLOW_UNUSED unused) {}
29 36
30 } // namespace 37 } // namespace
31 38
32 // A class to encapsulate a set of frames and information about the size of 39 // A class to encapsulate a set of frames and information about the size of
33 // those frames. 40 // those frames.
34 class WebSocketChannel::SendBuffer { 41 class WebSocketChannel::SendBuffer {
35 public: 42 public:
36 SendBuffer() : total_bytes_(0) {} 43 SendBuffer() : total_bytes_(0) {}
37 44
38 // Add a WebSocketFrame to the buffer and increase total_bytes_. 45 // Add a WebSocketFrame to the buffer and increase total_bytes_.
(...skipping 19 matching lines...) Expand all
58 65
59 // Implementation of WebSocketStream::ConnectDelegate that simply forwards the 66 // Implementation of WebSocketStream::ConnectDelegate that simply forwards the
60 // calls on to the WebSocketChannel that created it. 67 // calls on to the WebSocketChannel that created it.
61 class WebSocketChannel::ConnectDelegate 68 class WebSocketChannel::ConnectDelegate
62 : public WebSocketStream::ConnectDelegate { 69 : public WebSocketStream::ConnectDelegate {
63 public: 70 public:
64 explicit ConnectDelegate(WebSocketChannel* creator) : creator_(creator) {} 71 explicit ConnectDelegate(WebSocketChannel* creator) : creator_(creator) {}
65 72
66 virtual void OnSuccess(scoped_ptr<WebSocketStream> stream) OVERRIDE { 73 virtual void OnSuccess(scoped_ptr<WebSocketStream> stream) OVERRIDE {
67 creator_->OnConnectSuccess(stream.Pass()); 74 creator_->OnConnectSuccess(stream.Pass());
75 // |this| may have been deleted.
68 } 76 }
69 77
70 virtual void OnFailure(uint16 websocket_error) OVERRIDE { 78 virtual void OnFailure(uint16 websocket_error) OVERRIDE {
71 creator_->OnConnectFailure(websocket_error); 79 creator_->OnConnectFailure(websocket_error);
80 // |this| has been deleted.
72 } 81 }
73 82
74 private: 83 private:
75 // A pointer to the WebSocketChannel that created this object. There is no 84 // A pointer to the WebSocketChannel that created this object. There is no
76 // danger of this pointer being stale, because deleting the WebSocketChannel 85 // danger of this pointer being stale, because deleting the WebSocketChannel
77 // cancels the connect process, deleting this object and preventing its 86 // cancels the connect process, deleting this object and preventing its
78 // callbacks from being called. 87 // callbacks from being called.
79 WebSocketChannel* const creator_; 88 WebSocketChannel* const creator_;
80 89
81 DISALLOW_COPY_AND_ASSIGN(ConnectDelegate); 90 DISALLOW_COPY_AND_ASSIGN(ConnectDelegate);
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
134 if (InClosingState()) { 143 if (InClosingState()) {
135 VLOG(1) << "SendFrame called in state " << state_ 144 VLOG(1) << "SendFrame called in state " << state_
136 << ". This may be a bug, or a harmless race."; 145 << ". This may be a bug, or a harmless race.";
137 return; 146 return;
138 } 147 }
139 if (state_ != CONNECTED) { 148 if (state_ != CONNECTED) {
140 NOTREACHED() << "SendFrame() called in state " << state_; 149 NOTREACHED() << "SendFrame() called in state " << state_;
141 return; 150 return;
142 } 151 }
143 if (data.size() > base::checked_numeric_cast<size_t>(current_send_quota_)) { 152 if (data.size() > base::checked_numeric_cast<size_t>(current_send_quota_)) {
144 FailChannel(SEND_GOING_AWAY, 153 AllowUnused(FailChannel(SEND_GOING_AWAY,
145 kWebSocketMuxErrorSendQuotaViolation, 154 kWebSocketMuxErrorSendQuotaViolation,
146 "Send quota exceeded"); 155 "Send quota exceeded"));
156 // |this| is deleted here.
147 return; 157 return;
148 } 158 }
149 if (!WebSocketFrameHeader::IsKnownDataOpCode(op_code)) { 159 if (!WebSocketFrameHeader::IsKnownDataOpCode(op_code)) {
150 LOG(DFATAL) << "Got SendFrame with bogus op_code " << op_code 160 LOG(DFATAL) << "Got SendFrame with bogus op_code " << op_code
151 << "; misbehaving renderer? fin=" << fin 161 << "; misbehaving renderer? fin=" << fin
152 << " data.size()=" << data.size(); 162 << " data.size()=" << data.size();
153 return; 163 return;
154 } 164 }
155 current_send_quota_ -= data.size(); 165 current_send_quota_ -= data.size();
156 // TODO(ricea): If current_send_quota_ has dropped below 166 // TODO(ricea): If current_send_quota_ has dropped below
157 // send_quota_low_water_mark_, it might be good to increase the "low 167 // send_quota_low_water_mark_, it might be good to increase the "low
158 // water mark" and "high water mark", but only if the link to the WebSocket 168 // water mark" and "high water mark", but only if the link to the WebSocket
159 // server is not saturated. 169 // server is not saturated.
160 // TODO(ricea): For kOpCodeText, do UTF-8 validation? 170 // TODO(ricea): For kOpCodeText, do UTF-8 validation?
161 scoped_refptr<IOBuffer> buffer(new IOBuffer(data.size())); 171 scoped_refptr<IOBuffer> buffer(new IOBuffer(data.size()));
162 std::copy(data.begin(), data.end(), buffer->data()); 172 std::copy(data.begin(), data.end(), buffer->data());
163 SendIOBuffer(fin, op_code, buffer, data.size()); 173 AllowUnused(SendIOBuffer(fin, op_code, buffer, data.size()));
174 // |this| may have been deleted.
164 } 175 }
165 176
166 void WebSocketChannel::SendFlowControl(int64 quota) { 177 void WebSocketChannel::SendFlowControl(int64 quota) {
167 DCHECK_EQ(CONNECTED, state_); 178 DCHECK_EQ(CONNECTED, state_);
168 // TODO(ricea): Add interface to WebSocketStream and implement. 179 // TODO(ricea): Add interface to WebSocketStream and implement.
169 // stream_->SendFlowControl(quota); 180 // stream_->SendFlowControl(quota);
170 } 181 }
171 182
172 void WebSocketChannel::StartClosingHandshake(uint16 code, 183 void WebSocketChannel::StartClosingHandshake(uint16 code,
173 const std::string& reason) { 184 const std::string& reason) {
174 if (InClosingState()) { 185 if (InClosingState()) {
175 VLOG(1) << "StartClosingHandshake called in state " << state_ 186 VLOG(1) << "StartClosingHandshake called in state " << state_
176 << ". This may be a bug, or a harmless race."; 187 << ". This may be a bug, or a harmless race.";
177 return; 188 return;
178 } 189 }
179 if (state_ != CONNECTED) { 190 if (state_ != CONNECTED) {
180 NOTREACHED() << "StartClosingHandshake() called in state " << state_; 191 NOTREACHED() << "StartClosingHandshake() called in state " << state_;
181 return; 192 return;
182 } 193 }
183 // TODO(ricea): Validate |code|? Check that |reason| is valid UTF-8? 194 // TODO(ricea): Validate |code|
184 // TODO(ricea): There should be a timeout for the closing handshake. 195 // TODO(ricea): There should be a timeout for the closing handshake.
185 SendClose(code, reason); // Sets state_ to SEND_CLOSED 196 AllowUnused(SendClose(
197 code, IsStringUTF8(reason) ? reason : std::string())); // Sets state_ to
198 // SEND_CLOSED
199 // If |unused| is CHANNEL_DELETED, then |this| has been deleted.
186 } 200 }
187 201
188 void WebSocketChannel::SendAddChannelRequestForTesting( 202 void WebSocketChannel::SendAddChannelRequestForTesting(
189 const GURL& socket_url, 203 const GURL& socket_url,
190 const std::vector<std::string>& requested_subprotocols, 204 const std::vector<std::string>& requested_subprotocols,
191 const GURL& origin, 205 const GURL& origin,
192 const WebSocketStreamFactory& factory) { 206 const WebSocketStreamFactory& factory) {
193 SendAddChannelRequestWithFactory(socket_url, 207 SendAddChannelRequestWithFactory(
194 requested_subprotocols, 208 socket_url, requested_subprotocols, origin, factory);
195 origin,
196 factory);
197 } 209 }
198 210
199 void WebSocketChannel::SendAddChannelRequestWithFactory( 211 void WebSocketChannel::SendAddChannelRequestWithFactory(
200 const GURL& socket_url, 212 const GURL& socket_url,
201 const std::vector<std::string>& requested_subprotocols, 213 const std::vector<std::string>& requested_subprotocols,
202 const GURL& origin, 214 const GURL& origin,
203 const WebSocketStreamFactory& factory) { 215 const WebSocketStreamFactory& factory) {
204 DCHECK_EQ(FRESHLY_CONSTRUCTED, state_); 216 DCHECK_EQ(FRESHLY_CONSTRUCTED, state_);
205 socket_url_ = socket_url; 217 socket_url_ = socket_url;
206 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate( 218 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate(
207 new ConnectDelegate(this)); 219 new ConnectDelegate(this));
208 stream_request_ = factory.Run(socket_url_, 220 stream_request_ = factory.Run(socket_url_,
209 requested_subprotocols, 221 requested_subprotocols,
210 origin, 222 origin,
211 url_request_context_, 223 url_request_context_,
212 BoundNetLog(), 224 BoundNetLog(),
213 connect_delegate.Pass()); 225 connect_delegate.Pass());
214 state_ = CONNECTING; 226 state_ = CONNECTING;
215 } 227 }
216 228
217 void WebSocketChannel::OnConnectSuccess(scoped_ptr<WebSocketStream> stream) { 229 void WebSocketChannel::OnConnectSuccess(scoped_ptr<WebSocketStream> stream) {
218 DCHECK(stream); 230 DCHECK(stream);
219 DCHECK_EQ(CONNECTING, state_); 231 DCHECK_EQ(CONNECTING, state_);
220 stream_ = stream.Pass(); 232 stream_ = stream.Pass();
221 state_ = CONNECTED; 233 state_ = CONNECTED;
222 event_interface_->OnAddChannelResponse(false, stream_->GetSubProtocol()); 234 if (event_interface_->OnAddChannelResponse(
235 false, stream_->GetSubProtocol()) == CHANNEL_DELETED)
236 return;
223 237
224 // TODO(ricea): Get flow control information from the WebSocketStream once we 238 // TODO(ricea): Get flow control information from the WebSocketStream once we
225 // have a multiplexing WebSocketStream. 239 // have a multiplexing WebSocketStream.
226 current_send_quota_ = send_quota_high_water_mark_; 240 current_send_quota_ = send_quota_high_water_mark_;
227 event_interface_->OnFlowControl(send_quota_high_water_mark_); 241 if (event_interface_->OnFlowControl(send_quota_high_water_mark_) ==
242 CHANNEL_DELETED)
243 return;
228 244
229 // |stream_request_| is not used once the connection has succeeded. 245 // |stream_request_| is not used once the connection has succeeded.
230 stream_request_.reset(); 246 stream_request_.reset();
231 ReadFrames(); 247 AllowUnused(ReadFrames());
248 // |this| may have been deleted.
232 } 249 }
233 250
234 void WebSocketChannel::OnConnectFailure(uint16 websocket_error) { 251 void WebSocketChannel::OnConnectFailure(uint16 websocket_error) {
235 DCHECK_EQ(CONNECTING, state_); 252 DCHECK_EQ(CONNECTING, state_);
236 state_ = CLOSED; 253 state_ = CLOSED;
237 stream_request_.reset(); 254 stream_request_.reset();
238 event_interface_->OnAddChannelResponse(true, ""); 255 AllowUnused(event_interface_->OnAddChannelResponse(true, ""));
256 // |this| has been deleted.
239 } 257 }
240 258
241 void WebSocketChannel::WriteFrames() { 259 ChannelState WebSocketChannel::WriteFrames() {
242 int result = OK; 260 int result = OK;
243 do { 261 do {
244 // This use of base::Unretained is safe because this object owns the 262 // This use of base::Unretained is safe because this object owns the
245 // WebSocketStream and destroying it cancels all callbacks. 263 // WebSocketStream and destroying it cancels all callbacks.
246 result = stream_->WriteFrames( 264 result = stream_->WriteFrames(
247 data_being_sent_->frames(), 265 data_being_sent_->frames(),
248 base::Bind( 266 base::Bind(base::IgnoreResult(&WebSocketChannel::OnWriteDone),
249 &WebSocketChannel::OnWriteDone, base::Unretained(this), false)); 267 base::Unretained(this),
268 false));
250 if (result != ERR_IO_PENDING) { 269 if (result != ERR_IO_PENDING) {
251 OnWriteDone(true, result); 270 if (OnWriteDone(true, result) == CHANNEL_DELETED)
271 return CHANNEL_DELETED;
252 } 272 }
253 } while (result == OK && data_being_sent_); 273 } while (result == OK && data_being_sent_);
274 return CHANNEL_ALIVE;
254 } 275 }
255 276
256 void WebSocketChannel::OnWriteDone(bool synchronous, int result) { 277 ChannelState WebSocketChannel::OnWriteDone(bool synchronous, int result) {
257 DCHECK_NE(FRESHLY_CONSTRUCTED, state_); 278 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
258 DCHECK_NE(CONNECTING, state_); 279 DCHECK_NE(CONNECTING, state_);
259 DCHECK_NE(ERR_IO_PENDING, result); 280 DCHECK_NE(ERR_IO_PENDING, result);
260 DCHECK(data_being_sent_); 281 DCHECK(data_being_sent_);
261 switch (result) { 282 switch (result) {
262 case OK: 283 case OK:
263 if (data_to_send_next_) { 284 if (data_to_send_next_) {
264 data_being_sent_ = data_to_send_next_.Pass(); 285 data_being_sent_ = data_to_send_next_.Pass();
265 if (!synchronous) { 286 if (!synchronous)
266 WriteFrames(); 287 return WriteFrames();
267 }
268 } else { 288 } else {
269 data_being_sent_.reset(); 289 data_being_sent_.reset();
270 if (current_send_quota_ < send_quota_low_water_mark_) { 290 if (current_send_quota_ < send_quota_low_water_mark_) {
271 // TODO(ricea): Increase low_water_mark and high_water_mark if 291 // TODO(ricea): Increase low_water_mark and high_water_mark if
272 // throughput is high, reduce them if throughput is low. Low water 292 // throughput is high, reduce them if throughput is low. Low water
273 // mark needs to be >= the bandwidth delay product *of the IPC 293 // mark needs to be >= the bandwidth delay product *of the IPC
274 // channel*. Because factors like context-switch time, thread wake-up 294 // channel*. Because factors like context-switch time, thread wake-up
275 // time, and bus speed come into play it is complex and probably needs 295 // time, and bus speed come into play it is complex and probably needs
276 // to be determined empirically. 296 // to be determined empirically.
277 DCHECK_LE(send_quota_low_water_mark_, send_quota_high_water_mark_); 297 DCHECK_LE(send_quota_low_water_mark_, send_quota_high_water_mark_);
278 // TODO(ricea): Truncate quota by the quota specified by the remote 298 // TODO(ricea): Truncate quota by the quota specified by the remote
279 // server, if the protocol in use supports quota. 299 // server, if the protocol in use supports quota.
280 int fresh_quota = send_quota_high_water_mark_ - current_send_quota_; 300 int fresh_quota = send_quota_high_water_mark_ - current_send_quota_;
281 current_send_quota_ += fresh_quota; 301 current_send_quota_ += fresh_quota;
282 event_interface_->OnFlowControl(fresh_quota); 302 return event_interface_->OnFlowControl(fresh_quota);
283 } 303 }
284 } 304 }
285 return; 305 return CHANNEL_ALIVE;
286 306
287 // If a recoverable error condition existed, it would go here. 307 // If a recoverable error condition existed, it would go here.
288 308
289 default: 309 default:
290 DCHECK_LT(result, 0) 310 DCHECK_LT(result, 0)
291 << "WriteFrames() should only return OK or ERR_ codes"; 311 << "WriteFrames() should only return OK or ERR_ codes";
292 stream_->Close(); 312 stream_->Close();
293 if (state_ != CLOSED) { 313 DCHECK_NE(CLOSED, state_);
294 state_ = CLOSED; 314 state_ = CLOSED;
295 event_interface_->OnDropChannel(kWebSocketErrorAbnormalClosure, 315 return event_interface_->OnDropChannel(kWebSocketErrorAbnormalClosure,
296 "Abnormal Closure"); 316 "Abnormal Closure");
297 }
298 return;
299 } 317 }
300 } 318 }
301 319
302 void WebSocketChannel::ReadFrames() { 320 ChannelState WebSocketChannel::ReadFrames() {
303 int result = OK; 321 int result = OK;
304 do { 322 do {
305 // This use of base::Unretained is safe because this object owns the 323 // This use of base::Unretained is safe because this object owns the
306 // WebSocketStream, and any pending reads will be cancelled when it is 324 // WebSocketStream, and any pending reads will be cancelled when it is
307 // destroyed. 325 // destroyed.
308 result = stream_->ReadFrames( 326 result = stream_->ReadFrames(
309 &read_frames_, 327 &read_frames_,
310 base::Bind( 328 base::Bind(base::IgnoreResult(&WebSocketChannel::OnReadDone),
311 &WebSocketChannel::OnReadDone, base::Unretained(this), false)); 329 base::Unretained(this),
330 false));
312 if (result != ERR_IO_PENDING) { 331 if (result != ERR_IO_PENDING) {
313 OnReadDone(true, result); 332 if (OnReadDone(true, result) == CHANNEL_DELETED)
333 return CHANNEL_DELETED;
314 } 334 }
315 } while (result == OK && state_ != CLOSED); 335 DCHECK_NE(CLOSED, state_);
336 } while (result == OK);
337 return CHANNEL_ALIVE;
316 } 338 }
317 339
318 void WebSocketChannel::OnReadDone(bool synchronous, int result) { 340 ChannelState WebSocketChannel::OnReadDone(bool synchronous, int result) {
319 DCHECK_NE(FRESHLY_CONSTRUCTED, state_); 341 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
320 DCHECK_NE(CONNECTING, state_); 342 DCHECK_NE(CONNECTING, state_);
321 DCHECK_NE(ERR_IO_PENDING, result); 343 DCHECK_NE(ERR_IO_PENDING, result);
322 switch (result) { 344 switch (result) {
323 case OK: 345 case OK:
324 // ReadFrames() must use ERR_CONNECTION_CLOSED for a closed connection 346 // ReadFrames() must use ERR_CONNECTION_CLOSED for a closed connection
325 // with no data read, not an empty response. 347 // with no data read, not an empty response.
326 DCHECK(!read_frames_.empty()) 348 DCHECK(!read_frames_.empty())
327 << "ReadFrames() returned OK, but nothing was read."; 349 << "ReadFrames() returned OK, but nothing was read.";
328 for (size_t i = 0; i < read_frames_.size(); ++i) { 350 for (size_t i = 0; i < read_frames_.size(); ++i) {
329 scoped_ptr<WebSocketFrame> frame(read_frames_[i]); 351 scoped_ptr<WebSocketFrame> frame(read_frames_[i]);
330 read_frames_[i] = NULL; 352 read_frames_[i] = NULL;
331 ProcessFrame(frame.Pass()); 353 if (ProcessFrame(frame.Pass()) == CHANNEL_DELETED)
354 return CHANNEL_DELETED;
332 } 355 }
333 read_frames_.clear(); 356 read_frames_.clear();
334 // There should always be a call to ReadFrames pending. 357 // There should always be a call to ReadFrames pending.
335 // TODO(ricea): Unless we are out of quota. 358 // TODO(ricea): Unless we are out of quota.
336 if (!synchronous && state_ != CLOSED) { 359 DCHECK_NE(CLOSED, state_);
337 ReadFrames(); 360 if (!synchronous)
338 } 361 return ReadFrames();
339 return; 362 return CHANNEL_ALIVE;
340 363
341 case ERR_WS_PROTOCOL_ERROR: 364 case ERR_WS_PROTOCOL_ERROR:
342 FailChannel(SEND_REAL_ERROR, 365 return FailChannel(SEND_REAL_ERROR,
343 kWebSocketErrorProtocolError, 366 kWebSocketErrorProtocolError,
344 "WebSocket Protocol Error"); 367 "WebSocket Protocol Error");
345 return;
346 368
347 default: 369 default:
348 DCHECK_LT(result, 0) 370 DCHECK_LT(result, 0)
349 << "ReadFrames() should only return OK or ERR_ codes"; 371 << "ReadFrames() should only return OK or ERR_ codes";
350 stream_->Close(); 372 stream_->Close();
351 if (state_ != CLOSED) { 373 DCHECK_NE(CLOSED, state_);
352 state_ = CLOSED; 374 state_ = CLOSED;
353 uint16 code = kWebSocketErrorAbnormalClosure; 375 uint16 code = kWebSocketErrorAbnormalClosure;
354 std::string reason = "Abnormal Closure"; 376 std::string reason = "Abnormal Closure";
355 if (closing_code_ != 0) { 377 if (closing_code_ != 0) {
356 code = closing_code_; 378 code = closing_code_;
357 reason = closing_reason_; 379 reason = closing_reason_;
358 }
359 event_interface_->OnDropChannel(code, reason);
360 } 380 }
361 return; 381 return event_interface_->OnDropChannel(code, reason);
362 } 382 }
363 } 383 }
364 384
365 void WebSocketChannel::ProcessFrame(scoped_ptr<WebSocketFrame> frame) { 385 ChannelState WebSocketChannel::ProcessFrame(scoped_ptr<WebSocketFrame> frame) {
366 if (frame->header.masked) { 386 if (frame->header.masked) {
367 // RFC6455 Section 5.1 "A client MUST close a connection if it detects a 387 // RFC6455 Section 5.1 "A client MUST close a connection if it detects a
368 // masked frame." 388 // masked frame."
369 FailChannel(SEND_REAL_ERROR, 389 return FailChannel(SEND_REAL_ERROR,
370 kWebSocketErrorProtocolError, 390 kWebSocketErrorProtocolError,
371 "Masked frame from server"); 391 "Masked frame from server");
372 return;
373 } 392 }
374 const WebSocketFrameHeader::OpCode opcode = frame->header.opcode; 393 const WebSocketFrameHeader::OpCode opcode = frame->header.opcode;
375 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode) && 394 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode) &&
376 !frame->header.final) { 395 !frame->header.final) {
377 FailChannel(SEND_REAL_ERROR, 396 return FailChannel(SEND_REAL_ERROR,
378 kWebSocketErrorProtocolError, 397 kWebSocketErrorProtocolError,
379 "Control message with FIN bit unset received"); 398 "Control message with FIN bit unset received");
380 return;
381 } 399 }
382 400
383 // Respond to the frame appropriately to its type. 401 // Respond to the frame appropriately to its type.
384 HandleFrame( 402 return HandleFrame(
385 opcode, frame->header.final, frame->data, frame->header.payload_length); 403 opcode, frame->header.final, frame->data, frame->header.payload_length);
386 } 404 }
387 405
388 void WebSocketChannel::HandleFrame(const WebSocketFrameHeader::OpCode opcode, 406 ChannelState WebSocketChannel::HandleFrame(
389 bool final, 407 const WebSocketFrameHeader::OpCode opcode,
390 const scoped_refptr<IOBuffer>& data_buffer, 408 bool final,
391 size_t size) { 409 const scoped_refptr<IOBuffer>& data_buffer,
410 size_t size) {
392 DCHECK_NE(RECV_CLOSED, state_) 411 DCHECK_NE(RECV_CLOSED, state_)
393 << "HandleFrame() does not support being called re-entrantly from within " 412 << "HandleFrame() does not support being called re-entrantly from within "
394 "SendClose()"; 413 "SendClose()";
395 if (state_ == CLOSED || state_ == CLOSE_WAIT) { 414 DCHECK_NE(CLOSED, state_);
396 DVLOG_IF(1, state_ == CLOSED) << "A frame was received while in the CLOSED " 415 if (state_ == CLOSE_WAIT) {
397 "state. This is possible after a channel "
398 "failed, but should be very rare.";
399 std::string frame_name; 416 std::string frame_name;
400 switch (opcode) { 417 switch (opcode) {
401 case WebSocketFrameHeader::kOpCodeText: // fall-thru 418 case WebSocketFrameHeader::kOpCodeText: // fall-thru
402 case WebSocketFrameHeader::kOpCodeBinary: // fall-thru 419 case WebSocketFrameHeader::kOpCodeBinary: // fall-thru
403 case WebSocketFrameHeader::kOpCodeContinuation: 420 case WebSocketFrameHeader::kOpCodeContinuation:
404 frame_name = "Data frame"; 421 frame_name = "Data frame";
405 break; 422 break;
406 423
407 case WebSocketFrameHeader::kOpCodePing: 424 case WebSocketFrameHeader::kOpCodePing:
408 frame_name = "Ping"; 425 frame_name = "Ping";
409 break; 426 break;
410 427
411 case WebSocketFrameHeader::kOpCodePong: 428 case WebSocketFrameHeader::kOpCodePong:
412 frame_name = "Pong"; 429 frame_name = "Pong";
413 break; 430 break;
414 431
415 case WebSocketFrameHeader::kOpCodeClose: 432 case WebSocketFrameHeader::kOpCodeClose:
416 frame_name = "Close"; 433 frame_name = "Close";
417 break; 434 break;
418 435
419 default: 436 default:
420 frame_name = "Unknown frame type"; 437 frame_name = "Unknown frame type";
421 break; 438 break;
422 } 439 }
423 // SEND_REAL_ERROR makes no difference here, as FailChannel() won't send 440 // SEND_REAL_ERROR makes no difference here, as FailChannel() won't send
424 // another Close frame. 441 // another Close frame.
425 FailChannel(SEND_REAL_ERROR, 442 return FailChannel(SEND_REAL_ERROR,
426 kWebSocketErrorProtocolError, 443 kWebSocketErrorProtocolError,
427 frame_name + " received after close"); 444 frame_name + " received after close");
428 return;
429 } 445 }
430 switch (opcode) { 446 switch (opcode) {
431 case WebSocketFrameHeader::kOpCodeText: // fall-thru 447 case WebSocketFrameHeader::kOpCodeText: // fall-thru
432 case WebSocketFrameHeader::kOpCodeBinary: // fall-thru 448 case WebSocketFrameHeader::kOpCodeBinary: // fall-thru
433 case WebSocketFrameHeader::kOpCodeContinuation: 449 case WebSocketFrameHeader::kOpCodeContinuation:
434 if (state_ == CONNECTED) { 450 if (state_ == CONNECTED) {
435 // TODO(ricea): Need to fail the connection if UTF-8 is invalid 451 // TODO(ricea): Need to fail the connection if UTF-8 is invalid
436 // post-reassembly. Requires a streaming UTF-8 validator. 452 // post-reassembly. Requires a streaming UTF-8 validator.
437 // TODO(ricea): Can this copy be eliminated? 453 // TODO(ricea): Can this copy be eliminated?
438 const char* const data_begin = data_buffer->data(); 454 const char* const data_begin = data_buffer->data();
439 const char* const data_end = data_begin + size; 455 const char* const data_end = data_begin + size;
440 const std::vector<char> data(data_begin, data_end); 456 const std::vector<char> data(data_begin, data_end);
441 // TODO(ricea): Handle the case when ReadFrames returns far 457 // TODO(ricea): Handle the case when ReadFrames returns far
442 // more data at once than should be sent in a single IPC. This needs to 458 // more data at once than should be sent in a single IPC. This needs to
443 // be handled carefully, as an overloaded IO thread is one possible 459 // be handled carefully, as an overloaded IO thread is one possible
444 // cause of receiving very large chunks. 460 // cause of receiving very large chunks.
445 461
446 // Sends the received frame to the renderer process. 462 // Sends the received frame to the renderer process.
447 event_interface_->OnDataFrame(final, opcode, data); 463 return event_interface_->OnDataFrame(final, opcode, data);
448 } else {
449 VLOG(3) << "Ignored data packet received in state " << state_;
450 } 464 }
451 return; 465 VLOG(3) << "Ignored data packet received in state " << state_;
466 return CHANNEL_ALIVE;
452 467
453 case WebSocketFrameHeader::kOpCodePing: 468 case WebSocketFrameHeader::kOpCodePing:
454 VLOG(1) << "Got Ping of size " << size; 469 VLOG(1) << "Got Ping of size " << size;
455 if (state_ == CONNECTED) { 470 if (state_ == CONNECTED)
456 SendIOBuffer( 471 return SendIOBuffer(
457 true, WebSocketFrameHeader::kOpCodePong, data_buffer, size); 472 true, WebSocketFrameHeader::kOpCodePong, data_buffer, size);
458 } else { 473 VLOG(3) << "Ignored ping in state " << state_;
459 VLOG(3) << "Ignored ping in state " << state_; 474 return CHANNEL_ALIVE;
460 }
461 return;
462 475
463 case WebSocketFrameHeader::kOpCodePong: 476 case WebSocketFrameHeader::kOpCodePong:
464 VLOG(1) << "Got Pong of size " << size; 477 VLOG(1) << "Got Pong of size " << size;
465 // There is no need to do anything with pong messages. 478 // There is no need to do anything with pong messages.
466 return; 479 return CHANNEL_ALIVE;
467 480
468 case WebSocketFrameHeader::kOpCodeClose: { 481 case WebSocketFrameHeader::kOpCodeClose: {
469 uint16 code = kWebSocketNormalClosure; 482 uint16 code = kWebSocketNormalClosure;
470 std::string reason; 483 std::string reason;
471 ParseClose(data_buffer, size, &code, &reason); 484 ParseClose(data_buffer, size, &code, &reason);
472 // TODO(ricea): Find a way to safely log the message from the close 485 // TODO(ricea): Find a way to safely log the message from the close
473 // message (escape control codes and so on). 486 // message (escape control codes and so on).
474 VLOG(1) << "Got Close with code " << code; 487 VLOG(1) << "Got Close with code " << code;
475 switch (state_) { 488 switch (state_) {
476 case CONNECTED: 489 case CONNECTED:
477 state_ = RECV_CLOSED; 490 state_ = RECV_CLOSED;
478 SendClose(code, reason); // Sets state_ to CLOSE_WAIT 491 if (SendClose(code, reason) == // Sets state_ to CLOSE_WAIT
479 event_interface_->OnClosingHandshake(); 492 CHANNEL_DELETED)
493 return CHANNEL_DELETED;
494 if (event_interface_->OnClosingHandshake() == CHANNEL_DELETED)
495 return CHANNEL_DELETED;
480 closing_code_ = code; 496 closing_code_ = code;
481 closing_reason_ = reason; 497 closing_reason_ = reason;
482 break; 498 break;
483 499
484 case SEND_CLOSED: 500 case SEND_CLOSED:
485 state_ = CLOSE_WAIT; 501 state_ = CLOSE_WAIT;
486 // From RFC6455 section 7.1.5: "Each endpoint 502 // From RFC6455 section 7.1.5: "Each endpoint
487 // will see the status code sent by the other end as _The WebSocket 503 // will see the status code sent by the other end as _The WebSocket
488 // Connection Close Code_." 504 // Connection Close Code_."
489 closing_code_ = code; 505 closing_code_ = code;
490 closing_reason_ = reason; 506 closing_reason_ = reason;
491 break; 507 break;
492 508
493 default: 509 default:
494 LOG(DFATAL) << "Got Close in unexpected state " << state_; 510 LOG(DFATAL) << "Got Close in unexpected state " << state_;
495 break; 511 break;
496 } 512 }
497 return; 513 return CHANNEL_ALIVE;
498 } 514 }
499 515
500 default: 516 default:
501 FailChannel( 517 return FailChannel(
502 SEND_REAL_ERROR, kWebSocketErrorProtocolError, "Unknown opcode"); 518 SEND_REAL_ERROR, kWebSocketErrorProtocolError, "Unknown opcode");
503 return;
504 } 519 }
505 } 520 }
506 521
507 void WebSocketChannel::SendIOBuffer(bool fin, 522 ChannelState WebSocketChannel::SendIOBuffer(
508 WebSocketFrameHeader::OpCode op_code, 523 bool fin,
509 const scoped_refptr<IOBuffer>& buffer, 524 WebSocketFrameHeader::OpCode op_code,
510 size_t size) { 525 const scoped_refptr<IOBuffer>& buffer,
526 size_t size) {
511 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED); 527 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED);
512 DCHECK(stream_); 528 DCHECK(stream_);
513 scoped_ptr<WebSocketFrame> frame(new WebSocketFrame(op_code)); 529 scoped_ptr<WebSocketFrame> frame(new WebSocketFrame(op_code));
514 WebSocketFrameHeader& header = frame->header; 530 WebSocketFrameHeader& header = frame->header;
515 header.final = fin; 531 header.final = fin;
516 header.masked = true; 532 header.masked = true;
517 header.payload_length = size; 533 header.payload_length = size;
518 frame->data = buffer; 534 frame->data = buffer;
519 if (data_being_sent_) { 535 if (data_being_sent_) {
520 // Either the link to the WebSocket server is saturated, or several messages 536 // Either the link to the WebSocket server is saturated, or several messages
521 // are being sent in a batch. 537 // are being sent in a batch.
522 // TODO(ricea): Keep some statistics to work out the situation and adjust 538 // TODO(ricea): Keep some statistics to work out the situation and adjust
523 // quota appropriately. 539 // quota appropriately.
524 if (!data_to_send_next_) 540 if (!data_to_send_next_)
525 data_to_send_next_.reset(new SendBuffer); 541 data_to_send_next_.reset(new SendBuffer);
526 data_to_send_next_->AddFrame(frame.Pass()); 542 data_to_send_next_->AddFrame(frame.Pass());
527 } else { 543 return CHANNEL_ALIVE;
528 data_being_sent_.reset(new SendBuffer);
529 data_being_sent_->AddFrame(frame.Pass());
530 WriteFrames();
531 } 544 }
545 data_being_sent_.reset(new SendBuffer);
546 data_being_sent_->AddFrame(frame.Pass());
547 return WriteFrames();
532 } 548 }
533 549
534 void WebSocketChannel::FailChannel(ExposeError expose, 550 ChannelState WebSocketChannel::FailChannel(ExposeError expose,
535 uint16 code, 551 uint16 code,
536 const std::string& reason) { 552 const std::string& reason) {
537 DCHECK_NE(FRESHLY_CONSTRUCTED, state_); 553 DCHECK_NE(FRESHLY_CONSTRUCTED, state_);
538 DCHECK_NE(CONNECTING, state_); 554 DCHECK_NE(CONNECTING, state_);
555 DCHECK_NE(CLOSED, state_);
539 // TODO(ricea): Logging. 556 // TODO(ricea): Logging.
540 State old_state = state_;
541 if (state_ == CONNECTED) { 557 if (state_ == CONNECTED) {
542 uint16 send_code = kWebSocketErrorGoingAway; 558 uint16 send_code = kWebSocketErrorGoingAway;
543 std::string send_reason = "Internal Error"; 559 std::string send_reason = "Internal Error";
544 if (expose == SEND_REAL_ERROR) { 560 if (expose == SEND_REAL_ERROR) {
545 send_code = code; 561 send_code = code;
546 send_reason = reason; 562 send_reason = reason;
547 } 563 }
548 SendClose(send_code, send_reason); // Sets state_ to SEND_CLOSED 564 if (SendClose(send_code, send_reason) == // Sets state_ to SEND_CLOSED
565 CHANNEL_DELETED)
566 return CHANNEL_DELETED;
549 } 567 }
550 // Careful study of RFC6455 section 7.1.7 and 7.1.1 indicates the browser 568 // Careful study of RFC6455 section 7.1.7 and 7.1.1 indicates the browser
551 // should close the connection itself without waiting for the closing 569 // should close the connection itself without waiting for the closing
552 // handshake. 570 // handshake.
553 stream_->Close(); 571 stream_->Close();
554 state_ = CLOSED; 572 state_ = CLOSED;
555 573
556 if (old_state != CLOSED) { 574 return event_interface_->OnDropChannel(code, reason);
557 event_interface_->OnDropChannel(code, reason);
558 }
559 } 575 }
560 576
561 void WebSocketChannel::SendClose(uint16 code, const std::string& reason) { 577 ChannelState WebSocketChannel::SendClose(uint16 code,
578 const std::string& reason) {
562 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED); 579 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED);
563 // TODO(ricea): Ensure reason.length() <= 123 580 // TODO(ricea): Ensure reason.length() <= 123
564 scoped_refptr<IOBuffer> body; 581 scoped_refptr<IOBuffer> body;
565 size_t size = 0; 582 size_t size = 0;
566 if (code == kWebSocketErrorNoStatusReceived) { 583 if (code == kWebSocketErrorNoStatusReceived) {
567 // Special case: translate kWebSocketErrorNoStatusReceived into a Close 584 // Special case: translate kWebSocketErrorNoStatusReceived into a Close
568 // frame with no payload. 585 // frame with no payload.
569 body = new IOBuffer(0); 586 body = new IOBuffer(0);
570 } else { 587 } else {
571 const size_t payload_length = kWebSocketCloseCodeLength + reason.length(); 588 const size_t payload_length = kWebSocketCloseCodeLength + reason.length();
572 body = new IOBuffer(payload_length); 589 body = new IOBuffer(payload_length);
573 size = payload_length; 590 size = payload_length;
574 WriteBigEndian(body->data(), code); 591 WriteBigEndian(body->data(), code);
575 COMPILE_ASSERT(sizeof(code) == kWebSocketCloseCodeLength, 592 COMPILE_ASSERT(sizeof(code) == kWebSocketCloseCodeLength,
576 they_should_both_be_two); 593 they_should_both_be_two);
577 std::copy( 594 std::copy(
578 reason.begin(), reason.end(), body->data() + kWebSocketCloseCodeLength); 595 reason.begin(), reason.end(), body->data() + kWebSocketCloseCodeLength);
579 } 596 }
580 SendIOBuffer(true, WebSocketFrameHeader::kOpCodeClose, body, size); 597 if (SendIOBuffer(true, WebSocketFrameHeader::kOpCodeClose, body, size) ==
598 CHANNEL_DELETED)
599 return CHANNEL_DELETED;
600 // SendIOBuffer() checks |state_|, so it is best not to change it until after
601 // SendIOBuffer() returns.
581 state_ = (state_ == CONNECTED) ? SEND_CLOSED : CLOSE_WAIT; 602 state_ = (state_ == CONNECTED) ? SEND_CLOSED : CLOSE_WAIT;
603 return CHANNEL_ALIVE;
582 } 604 }
583 605
584 void WebSocketChannel::ParseClose(const scoped_refptr<IOBuffer>& buffer, 606 void WebSocketChannel::ParseClose(const scoped_refptr<IOBuffer>& buffer,
585 size_t size, 607 size_t size,
586 uint16* code, 608 uint16* code,
587 std::string* reason) { 609 std::string* reason) {
588 const char* data = buffer->data(); 610 const char* data = buffer->data();
589 reason->clear(); 611 reason->clear();
590 if (size < kWebSocketCloseCodeLength) { 612 if (size < kWebSocketCloseCodeLength) {
591 *code = kWebSocketErrorNoStatusReceived; 613 *code = kWebSocketErrorNoStatusReceived;
(...skipping 12 matching lines...) Expand all
604 if (unchecked_code >= static_cast<uint16>(kWebSocketNormalClosure) && 626 if (unchecked_code >= static_cast<uint16>(kWebSocketNormalClosure) &&
605 unchecked_code <= 627 unchecked_code <=
606 static_cast<uint16>(kWebSocketErrorPrivateReservedMax)) { 628 static_cast<uint16>(kWebSocketErrorPrivateReservedMax)) {
607 *code = unchecked_code; 629 *code = unchecked_code;
608 } else { 630 } else {
609 VLOG(1) << "Close frame contained code outside of the valid range: " 631 VLOG(1) << "Close frame contained code outside of the valid range: "
610 << unchecked_code; 632 << unchecked_code;
611 *code = kWebSocketErrorAbnormalClosure; 633 *code = kWebSocketErrorAbnormalClosure;
612 } 634 }
613 std::string text(data + kWebSocketCloseCodeLength, data + size); 635 std::string text(data + kWebSocketCloseCodeLength, data + size);
614 // TODO(ricea): Is this check strict enough? In particular, check the 636 // IsStringUTF8() blocks surrogate pairs and non-characters, so it is strictly
615 // "Security Considerations" from RFC3629. 637 // stronger than required by RFC3629.
616 if (IsStringUTF8(text)) { 638 if (IsStringUTF8(text)) {
617 reason->swap(text); 639 reason->swap(text);
618 } 640 }
619 } 641 }
620 642
621 } // namespace net 643 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698