OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2013 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "net/websockets/websocket_channel.h" | |
6 | |
7 #include <algorithm> | |
8 | |
9 #include "base/basictypes.h" // for size_t | |
10 #include "base/bind.h" | |
11 #include "base/string_util.h" | |
12 #include "net/base/big_endian.h" | |
13 #include "net/base/io_buffer.h" | |
14 #include "net/http/http_request_info.h" | |
15 #include "net/http/http_stream_factory.h" | |
16 #include "net/ssl/ssl_config_service.h" | |
17 #include "net/websockets/websocket_errors.h" | |
18 #include "net/websockets/websocket_event_interface.h" | |
19 #include "net/websockets/websocket_frame.h" | |
20 #include "net/websockets/websocket_mux.h" | |
21 #include "net/websockets/websocket_stream.h" | |
22 | |
23 namespace net { | |
24 | |
25 namespace { | |
26 | |
27 const int kDefaultSendQuotaLowWaterMark = 1 << 16; | |
28 const int kDefaultSendQuotaHighWaterMark = 1 << 17; | |
29 const size_t kWebSocketCloseCodeLength = 2; | |
30 | |
31 // IOBuffer is too hardcore to offer a const accessor. Make our own. | |
32 const char* GetConstData(const IOBuffer* iobuffer) { | |
33 return const_cast<IOBuffer*>(iobuffer)->data(); | |
34 } | |
35 | |
36 // Concatenate the data from two IOBufferWithSize objects into a single one. | |
37 IOBufferWithSize* ConcatenateIOBuffers(const IOBufferWithSize* part1, | |
38 const IOBufferWithSize* part2) { | |
39 int newsize = part1->size() + part2->size(); | |
40 IOBufferWithSize* newbuffer = new IOBufferWithSize(newsize); | |
41 std::copy(GetConstData(part1), | |
42 GetConstData(part1) + part1->size(), | |
43 newbuffer->data()); | |
44 std::copy(GetConstData(part2), | |
45 GetConstData(part2) + part2->size(), | |
46 newbuffer->data() + part1->size()); | |
47 return newbuffer; | |
48 } | |
49 | |
50 } // namespace | |
51 | |
52 struct WebSocketChannel::SendBuffer { | |
53 SendBuffer() : total_bytes(0) {} | |
54 ScopedVector<WebSocketFrameChunk> frames; | |
55 size_t total_bytes; | |
56 }; | |
57 | |
58 // Implementation of WebSocketStream::ConnectDelegate that simply forwards the | |
59 // calls on to the WebSocketChannel that created it. | |
60 class WebSocketChannel::ConnectDelegate | |
61 : public WebSocketStream::ConnectDelegate { | |
62 public: | |
63 ConnectDelegate(WebSocketChannel* creator) : creator_(creator) {} | |
64 | |
65 virtual void OnSuccess(scoped_ptr<WebSocketStream> stream) OVERRIDE { | |
66 creator_->OnConnectSuccess(stream.Pass()); | |
67 } | |
68 | |
69 virtual void OnFailure(unsigned short websocket_error) OVERRIDE { | |
70 creator_->OnConnectFailure(websocket_error); | |
71 } | |
72 | |
73 private: | |
74 // A pointer to the WebSocketChannel that created us. We do not need to worry | |
75 // about this pointer being stale, because deleting WebSocketChannel cancels | |
76 // the connect process, deleting this object and preventing its callbacks from | |
77 // being called. | |
78 WebSocketChannel* const creator_; | |
79 | |
80 DISALLOW_COPY_AND_ASSIGN(ConnectDelegate); | |
81 }; | |
82 | |
83 WebSocketChannel::WebSocketChannel( | |
84 const GURL& socket_url, | |
85 scoped_ptr<WebSocketEventInterface> event_interface) | |
86 : socket_url_(socket_url), | |
87 event_interface_(event_interface.Pass()), | |
88 send_quota_low_water_mark_(kDefaultSendQuotaLowWaterMark), | |
89 send_quota_high_water_mark_(kDefaultSendQuotaHighWaterMark), | |
90 current_send_quota_(0), | |
91 state_(FRESHLY_CONSTRUCTED), | |
92 weak_factory_(this) {} | |
93 | |
94 WebSocketChannel::~WebSocketChannel() { | |
95 // The stream may hold a pointer to read_frame_chunks_, and so it needs to be | |
96 // destroyed first. | |
97 stream_.reset(); | |
98 } | |
99 | |
100 void WebSocketChannel::SendAddChannelRequest( | |
101 const std::vector<std::string>& requested_subprotocols, | |
102 const GURL& origin, | |
103 URLRequestContext* url_request_context) { | |
104 // Delegate to the tested version. | |
105 SendAddChannelRequestWithFactory( | |
106 requested_subprotocols, | |
107 origin, | |
108 url_request_context, | |
109 base::Bind(&WebSocketStream::CreateAndConnectStream)); | |
110 } | |
111 | |
112 void WebSocketChannel::SendAddChannelRequestWithFactory( | |
113 const std::vector<std::string>& requested_subprotocols, | |
114 const GURL& origin, | |
115 URLRequestContext* url_request_context, | |
116 base::Callback<scoped_ptr<WebSocketStreamRequest>( | |
117 const GURL&, | |
118 const std::vector<std::string>&, | |
119 const GURL&, | |
120 URLRequestContext*, | |
121 const BoundNetLog&, | |
122 scoped_ptr<WebSocketStream::ConnectDelegate>)> factory) { | |
123 DCHECK_EQ(FRESHLY_CONSTRUCTED, state_); | |
124 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate( | |
125 new WebSocketChannel::ConnectDelegate(this)); | |
126 stream_request_ = factory.Run(socket_url_, | |
127 requested_subprotocols, | |
128 origin, | |
129 url_request_context, | |
130 BoundNetLog(), | |
131 connect_delegate.Pass()); | |
132 state_ = CONNECTING; | |
133 } | |
134 | |
135 void WebSocketChannel::OnConnectSuccess(scoped_ptr<WebSocketStream> stream) { | |
136 DCHECK(stream); | |
137 DCHECK_EQ(CONNECTING, state_); | |
138 stream_ = stream.Pass(); | |
139 event_interface_->OnAddChannelResponse(false, stream_->GetSubProtocol()); | |
140 // TODO(ricea): Get flow control information from the WebSocketStream once we | |
141 // have a multiplexing WebSocketStream. | |
142 event_interface_->OnFlowControl(send_quota_high_water_mark_); | |
143 current_send_quota_ = send_quota_high_water_mark_; | |
144 state_ = CONNECTED; | |
145 // We don't need this any more. | |
146 stream_request_.reset(); | |
147 ReadFrames(); | |
148 } | |
149 | |
150 void WebSocketChannel::OnConnectFailure(unsigned short web_socket_error) { | |
151 DCHECK_EQ(CONNECTING, state_); | |
152 event_interface_->OnAddChannelResponse(true, ""); | |
153 stream_request_.reset(); | |
154 state_ = CLOSED; | |
155 } | |
156 | |
157 void WebSocketChannel::SendFrame(bool fin, | |
158 WebSocketFrameHeader::OpCode op_code, | |
159 const std::vector<char>& data) { | |
160 if (data.size() > INT_MAX) { | |
161 NOTREACHED() << "Frame size sanity check failed"; | |
162 return; | |
163 } | |
164 if (stream_ == NULL) { | |
165 LOG(DFATAL) << "Got SendFrame without a connection established; " | |
166 << "misbehaving renderer? fin=" << fin << " op_code=" << op_code | |
167 << " data.size()=" << data.size(); | |
168 return; | |
169 } | |
170 if (state_ == SEND_CLOSED || state_ == RECV_CLOSED || state_ == CLOSED) { | |
171 VLOG(1) << "SendFrame called in state " << state_ | |
172 << ". This may be a bug, or a harmless race."; | |
173 return; | |
174 } | |
175 DCHECK_EQ(CONNECTED, state_); | |
176 CHECK_GE(current_send_quota_, 0); // Security-critical invariant | |
177 if (data.size() > static_cast<size_t>(current_send_quota_)) { | |
178 FailChannel(SEND_INTERNAL_ERROR, | |
179 kWebSocketMuxErrorSendQuotaViolation, | |
180 "Send quota exceeded"); | |
181 return; | |
182 } | |
183 if (!WebSocketFrameHeader::IsKnownDataOpCode(op_code)) { | |
184 LOG(DFATAL) << "Got SendFrame with bogus op_code " << op_code | |
185 << "; misbehaving renderer? fin=" << fin | |
186 << " data.size()=" << data.size(); | |
187 return; | |
188 } | |
189 current_send_quota_ -= data.size(); | |
190 // TODO(ricea): If current_send_quota_ has dropped below | |
191 // send_quota_low_water_mark_, we may want to consider increasing the "low | |
192 // water mark" and "high water mark", but only if we think we are not | |
193 // saturating the link to the WebSocket server. | |
194 // TODO(ricea): For kOpCodeText, do UTF-8 validation? | |
195 Send(fin, op_code, data); | |
196 } | |
197 | |
198 void WebSocketChannel::Send(bool fin, | |
199 WebSocketFrameHeader::OpCode op_code, | |
200 const std::vector<char>& data) { | |
201 scoped_refptr<IOBufferWithSize> buffer(new IOBufferWithSize(data.size())); | |
202 std::copy(data.begin(), data.end(), buffer->data()); | |
203 SendIOBufferWithSize(fin, op_code, buffer); | |
204 } | |
205 | |
206 void WebSocketChannel::SendIOBufferWithSize( | |
207 bool fin, | |
208 WebSocketFrameHeader::OpCode op_code, | |
209 const scoped_refptr<IOBufferWithSize>& buffer) { | |
210 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED); | |
211 DCHECK(stream_); | |
212 scoped_ptr<WebSocketFrameHeader> header(new WebSocketFrameHeader(op_code)); | |
213 header->final = fin; | |
214 header->masked = true; | |
215 header->payload_length = buffer->size(); | |
216 scoped_ptr<WebSocketFrameChunk> chunk(new WebSocketFrameChunk()); | |
217 chunk->header = header.Pass(); | |
218 chunk->final_chunk = true; | |
219 chunk->data = buffer; | |
220 if (currently_sending_) { | |
221 // Either the link to the WebSocket server is saturated, or we are simply | |
222 // processing a batch of messages. | |
223 // TODO(ricea): We need to keep some statistics to work out which situation | |
224 // we are in and adjust quota appropriately. | |
225 if (!send_next_) { | |
226 send_next_.reset(new SendBuffer); | |
227 } | |
228 send_next_->frames.push_back(chunk.release()); | |
229 send_next_->total_bytes += buffer->size(); | |
230 } else { | |
231 currently_sending_.reset(new SendBuffer); | |
232 currently_sending_->frames.push_back(chunk.release()); | |
233 currently_sending_->total_bytes += buffer->size(); | |
234 WriteFrames(); | |
235 } | |
236 } | |
237 | |
238 void WebSocketChannel::WriteFrames() { | |
239 // This is safe because we own the WebSocketStream and destroying it cancels | |
240 // all callbacks. | |
241 int result = stream_->WriteFrames( | |
242 &(currently_sending_->frames), | |
243 base::Bind(&WebSocketChannel::OnWriteDone, base::Unretained(this))); | |
244 if (result != ERR_IO_PENDING) { | |
245 OnWriteDone(result); | |
246 } | |
247 } | |
248 | |
249 void WebSocketChannel::OnWriteDone(int result) { | |
250 DCHECK(state_ != FRESHLY_CONSTRUCTED && state_ != CONNECTING); | |
251 DCHECK_NE(ERR_IO_PENDING, result); | |
252 DCHECK(currently_sending_); | |
253 switch (result) { | |
254 case OK: | |
255 if (send_next_) { | |
256 currently_sending_ = send_next_.Pass(); | |
257 WriteFrames(); | |
258 } else { | |
259 currently_sending_.reset(); | |
260 if (current_send_quota_ < send_quota_low_water_mark_) { | |
261 // TODO(ricea): Increase low_water_mark and high_water_mark if | |
262 // throughput is high, reduce them if throughput is low. Low water | |
263 // mark needs to be >= the bandwidth delay product *of the IPC | |
264 // channel*. Because factors like context-switch time, thread wake-up | |
265 // time, and bus speed come into play it is complex and probably needs | |
266 // to be determined empirically. | |
267 DCHECK_LE(send_quota_low_water_mark_, send_quota_high_water_mark_); | |
268 // TODO(ricea): Truncate quota by the quota specified by the remote | |
269 // server, if the protocol in use supports quota. | |
270 int fresh_quota = send_quota_high_water_mark_ - current_send_quota_; | |
271 event_interface_->OnFlowControl(fresh_quota); | |
272 current_send_quota_ += fresh_quota; | |
273 } | |
274 } | |
275 break; | |
276 | |
277 // If a recoverable error condition existed, it would go here. | |
278 | |
279 default: | |
280 DCHECK_LT(result, 0) | |
281 << "WriteFrames() should only return OK or ERR_ codes"; | |
282 stream_->Close(); | |
283 state_ = CLOSED; | |
284 event_interface_->OnDropChannel(kWebSocketErrorAbnormalClosure, | |
285 "Abnormal Closure"); | |
286 break; | |
287 } | |
288 } | |
289 | |
290 void WebSocketChannel::ReadFrames() { | |
291 // This use if base::Unretained is safe because we own the WebSocketStream, | |
292 // and any pending reads will be cancelled when it is destroyed. | |
293 int result = stream_->ReadFrames( | |
294 &read_frame_chunks_, | |
295 base::Bind(&WebSocketChannel::OnReadDone, base::Unretained(this))); | |
296 if (result != ERR_IO_PENDING) { | |
297 OnReadDone(result); | |
298 } | |
299 } | |
300 | |
301 void WebSocketChannel::OnReadDone(int result) { | |
302 DCHECK(state_ != FRESHLY_CONSTRUCTED && state_ != CONNECTING); | |
303 DCHECK_NE(ERR_IO_PENDING, result); | |
304 switch (result) { | |
305 case OK: | |
306 // ReadFrames() must use ERR_CONNECTION_CLOSED for a closed connection | |
307 // with no data read, not an empty response. | |
308 DCHECK(!read_frame_chunks_.empty()) | |
309 << "ReadFrames() returned OK, but nothing was read."; | |
310 for (size_t i = 0; i < read_frame_chunks_.size(); ++i) { | |
311 scoped_ptr<WebSocketFrameChunk> chunk(read_frame_chunks_[i]); | |
312 read_frame_chunks_[i] = NULL; | |
313 ProcessFrameChunk(chunk.Pass()); | |
314 } | |
315 read_frame_chunks_.clear(); | |
316 // We need to always keep a call to ReadFrames pending. | |
317 ReadFrames(); | |
318 return; | |
319 | |
320 case ERR_CONNECTION_CLOSED: { | |
321 State old_state = state_; | |
322 state_ = CLOSED; | |
323 if (old_state != RECV_CLOSED && old_state != CLOSED) { | |
324 // We need to inform the render process of the unexpected closure. | |
325 event_interface_->OnDropChannel(kWebSocketErrorAbnormalClosure, | |
326 "Abnormal Closure"); | |
327 } | |
328 return; | |
329 } | |
330 | |
331 default: { | |
332 DCHECK_LT(result, 0) | |
333 << "ReadFrames() should only return OK or ERR_ codes"; | |
334 stream_->Close(); | |
335 State old_state = state_; | |
336 state_ = CLOSED; | |
337 if (old_state != RECV_CLOSED && old_state != CLOSED) { | |
338 event_interface_->OnDropChannel(kWebSocketErrorAbnormalClosure, | |
339 "Abnormal Closure"); | |
340 } | |
341 return; | |
342 } | |
343 } | |
344 } | |
345 | |
346 // TODO(ricea): This method is too long. Break it up. | |
347 void WebSocketChannel::ProcessFrameChunk( | |
348 scoped_ptr<WebSocketFrameChunk> chunk) { | |
349 // frame_header stores the header for this frame, either saved from a previous | |
350 // chunk or from this chunk if it includes a header. | |
351 scoped_ptr<WebSocketFrameHeader> frame_header; | |
352 // Borrow the value of current_frame_header_. At the end of the function we | |
353 // will put it back if it is still valid, or replace it with the header from | |
354 // the new chunk. | |
355 frame_header.swap(current_frame_header_); | |
356 bool first_chunk = false; | |
357 if (chunk->header) { | |
358 first_chunk = true; | |
359 frame_header.swap(chunk->header); | |
360 if (frame_header->masked) { | |
361 // RFC6455 Section 5.1 "A client MUST close a connection if it detects a | |
362 // masked frame." | |
363 FailChannel(SEND_REAL_ERROR, | |
364 kWebSocketErrorProtocolError, | |
365 "Masked frame from server"); | |
366 return; | |
367 } | |
368 } | |
369 if (!frame_header) { | |
370 DCHECK(state_ != CONNECTED) << "Unexpected header-less frame received " | |
371 << "(final_chunk = " << chunk->final_chunk | |
372 << ", data size = " << chunk->data->size() | |
373 << ")"; | |
374 return; | |
375 } | |
376 scoped_refptr<IOBufferWithSize> data_buffer; | |
377 data_buffer.swap(chunk->data); | |
378 if (WebSocketFrameHeader::IsKnownControlOpCode(frame_header->opcode)) { | |
379 if (chunk->final_chunk) { | |
380 if (incomplete_control_frame_body_) { | |
381 VLOG(2) << "Rejoining a split control frame, opcode " | |
382 << frame_header->opcode; | |
383 scoped_refptr<IOBufferWithSize> old_data_buffer; | |
384 old_data_buffer.swap(incomplete_control_frame_body_); | |
385 scoped_refptr<IOBufferWithSize> new_data_buffer; | |
386 new_data_buffer.swap(data_buffer); | |
387 data_buffer = | |
388 ConcatenateIOBuffers(old_data_buffer.get(), new_data_buffer.get()); | |
389 } | |
390 } else { | |
391 // TODO(ricea): Enforce a maximum size of 125 bytes on the control frames | |
392 // we accept. | |
393 VLOG(2) << "Encountered a split control frame, opcode " | |
394 << frame_header->opcode; | |
395 if (incomplete_control_frame_body_) { | |
396 // The really horrid case. We need to create a new IOBufferWithSize | |
397 // combining the new one and the old one. This should virtually never | |
398 // happen. | |
399 // TODO(ricea): This algorithm is O(N^2). Use a fixed 127-byte byffer | |
400 // instead. | |
401 VLOG(3) << "Hit the really horrid case"; | |
402 scoped_refptr<IOBufferWithSize> old_body; | |
403 old_body.swap(incomplete_control_frame_body_); | |
404 incomplete_control_frame_body_ = | |
405 ConcatenateIOBuffers(old_body.get(), data_buffer.get()); | |
406 } else { | |
407 // The merely horrid case. Store the IOBufferWithSize to use when the | |
408 // rest of the control frame arrives. | |
409 incomplete_control_frame_body_.swap(data_buffer); | |
410 } | |
411 current_frame_header_.swap(frame_header); | |
412 return; | |
413 } | |
414 } | |
415 | |
416 WebSocketFrameHeader::OpCode opcode = frame_header->opcode; | |
417 switch (frame_header->opcode) { | |
418 case WebSocketFrameHeader::kOpCodeText: // fall-thru | |
419 case WebSocketFrameHeader::kOpCodeBinary: | |
420 if (!first_chunk) { | |
421 opcode = WebSocketFrameHeader::kOpCodeContinuation; | |
422 } | |
423 // fall-thru | |
424 case WebSocketFrameHeader::kOpCodeContinuation: | |
425 if (state_ == RECV_CLOSED) { | |
426 FailChannel(SEND_REAL_ERROR, | |
427 kWebSocketErrorProtocolError, | |
428 "Data packet received after close"); | |
429 return; | |
430 } else if (state_ == CONNECTED) { | |
431 const bool final = chunk->final_chunk && frame_header->final; | |
432 // TODO(ricea): Can this copy be eliminated? | |
433 const char* const data_begin = data_buffer->data(); | |
434 const char* const data_end = data_begin + data_buffer->size(); | |
435 const std::vector<char> data(data_begin, data_end); | |
436 // TODO(ricea): Handle the (improbable) case when ReadFrames returns far | |
437 // more data at once than we want to send in a single IPC (in which case | |
438 // we need to buffer the data and return to the event loop with a | |
439 // callback to send the rest in 32K chunks). | |
440 | |
441 // Send the received frame to the renderer process. | |
442 event_interface_->OnDataFrame(final, opcode, data); | |
443 } else { | |
444 VLOG(3) << "Ignored data packet received in state " << state_; | |
445 } | |
446 break; | |
447 | |
448 case WebSocketFrameHeader::kOpCodePing: | |
449 VLOG(1) << "Got Ping of size " << data_buffer->size(); | |
450 if (state_ == RECV_CLOSED) { | |
451 FailChannel(SEND_REAL_ERROR, | |
452 kWebSocketErrorProtocolError, | |
453 "Ping received after Close"); | |
454 return; | |
455 } else if (state_ == CONNECTED) { | |
456 SendIOBufferWithSize( | |
457 true, WebSocketFrameHeader::kOpCodePong, data_buffer); | |
458 } else { | |
459 VLOG(3) << "Ignored ping in state " << state_; | |
460 } | |
461 break; | |
462 | |
463 case WebSocketFrameHeader::kOpCodePong: | |
464 VLOG(1) << "Got Pong of size " << data_buffer->size(); | |
465 if (state_ == RECV_CLOSED) { | |
466 FailChannel(SEND_REAL_ERROR, | |
467 kWebSocketErrorProtocolError, | |
468 "Pong received after Close"); | |
469 return; | |
470 } | |
471 // We do not need to do anything with pong messages. | |
472 break; | |
473 | |
474 case WebSocketFrameHeader::kOpCodeClose: { | |
475 unsigned short reason = kWebSocketNormalClosure; | |
yhirano
2013/06/28 10:52:33
nit: We decided that we would use code and reason
Adam Rice
2013/06/28 14:06:41
You are right. I had completely forgotten. Sorry.
| |
476 std::string reason_text; | |
477 ParseClose(*data_buffer, &reason, &reason_text); | |
478 // TODO(ricea): Find a way to safely log the message from the close | |
479 // message (escape control codes and so on). | |
480 VLOG(1) << "Got Close with reason " << reason; | |
481 switch (state_) { | |
482 case CONNECTED: | |
483 state_ = RECV_CLOSED; | |
484 SendClose(reason, reason_text); | |
485 event_interface_->OnDropChannel(reason, reason_text); | |
486 break; | |
487 | |
488 case RECV_CLOSED: | |
489 FailChannel(SEND_REAL_ERROR, | |
490 kWebSocketErrorProtocolError, | |
491 "Close received after Close"); | |
492 break; | |
493 | |
494 case SEND_CLOSED: | |
495 state_ = CLOSED; | |
496 event_interface_->OnDropChannel(reason, reason_text); | |
497 break; | |
498 | |
499 default: | |
500 LOG(DFATAL) << "Got Close in unexpected state " << state_; | |
501 break; | |
502 } | |
503 break; | |
504 } | |
505 | |
506 default: | |
507 FailChannel(SEND_REAL_ERROR, | |
508 kWebSocketErrorProtocolError, | |
509 "Unknown opcode"); | |
510 break; | |
511 } | |
512 if (!chunk->final_chunk) { | |
513 // Preserve the frame header for the next call. | |
514 current_frame_header_.swap(frame_header); | |
515 } | |
516 } | |
517 | |
518 void WebSocketChannel::SendFlowControl(int64 quota) { | |
519 DCHECK_EQ(CONNECTED, state_); | |
520 // TODO(ricea): Add interface to WebSocketStream and implement. | |
521 // stream_->SendFlowControl(quota); | |
522 } | |
523 | |
524 void WebSocketChannel::SendDropChannel(unsigned short reason, | |
525 const std::string& reason_text) { | |
526 if (state_ == SEND_CLOSED || state_ == CLOSED) { | |
yhirano
2013/06/28 10:52:33
Ditto
Adam Rice
2013/06/28 14:06:41
Done.
| |
527 VLOG(1) << "SendDropChannel called in state " << state_ | |
528 << ". This may be a bug, or a harmless race."; | |
529 return; | |
530 } | |
531 DCHECK_EQ(CONNECTED, state_); | |
532 // TODO(ricea): Validate reason? Check that reason_text is valid UTF-8? | |
533 // TODO(ricea): There should probably be a timeout for the closing handshake. | |
534 SendClose(reason, reason_text); | |
535 } | |
536 | |
537 void WebSocketChannel::FailChannel(ExposeError expose, | |
538 unsigned short code, | |
539 const std::string& reason) { | |
540 // TODO(ricea): Logging. | |
541 State old_state = state_; | |
542 if (state_ == CONNECTED) { | |
543 unsigned short send_code = kWebSocketErrorGoingAway; | |
544 std::string send_reason = "Internal Error"; | |
545 if (expose == SEND_REAL_ERROR) { | |
546 send_code = code; | |
547 send_reason = reason; | |
548 } | |
549 SendClose(send_code, send_reason); | |
550 } | |
551 if (old_state != RECV_CLOSED && old_state != CLOSED) { | |
552 event_interface_->OnDropChannel(code, reason); | |
553 } | |
554 } | |
555 | |
556 void WebSocketChannel::SendClose(unsigned short code, | |
557 const std::string& reason) { | |
558 DCHECK(state_ == CONNECTED || state_ == RECV_CLOSED); | |
559 uint64 payload_length = kWebSocketCloseCodeLength + reason.length(); | |
560 std::vector<char> data(payload_length); | |
561 DCHECK(payload_length > 0); | |
562 WriteBigEndian(&data[0], code); | |
563 COMPILE_ASSERT(sizeof(code) == kWebSocketCloseCodeLength, | |
564 they_should_both_be_two); | |
565 std::copy(reason.begin(), | |
566 reason.end(), | |
567 data.begin() + kWebSocketCloseCodeLength); | |
568 Send(true, WebSocketFrameHeader::kOpCodeClose, data); | |
569 state_ = state_ == CONNECTED ? SEND_CLOSED : CLOSED; | |
570 } | |
571 | |
572 void WebSocketChannel::ParseClose(const IOBufferWithSize& buffer, | |
573 unsigned short* reason, | |
574 std::string* reason_text) { | |
575 const char* data = const_cast<IOBufferWithSize&>(buffer).data(); | |
yhirano
2013/06/28 10:52:33
Ditto
Adam Rice
2013/06/28 14:06:41
Done.
| |
576 CHECK_GE(buffer.size(), 0); // Possibly security-critical invariant. | |
577 size_t size = static_cast<size_t>(buffer.size()); | |
578 reason_text->clear(); | |
579 if (size < kWebSocketCloseCodeLength) { | |
580 *reason = kWebSocketErrorNoStatusReceived; | |
581 if (size != 0) { | |
582 VLOG(1) << "Close frame with payload size " << size << " received " | |
583 << "(the first byte is " << std::hex << static_cast<int>(data[0]) | |
584 << ")"; | |
585 return; | |
586 } | |
587 return; | |
588 } | |
589 unsigned short unchecked_reason = 0; | |
590 ReadBigEndian(data, &unchecked_reason); | |
591 COMPILE_ASSERT(sizeof(unchecked_reason) == kWebSocketCloseCodeLength, | |
592 they_should_both_be_two_bytes); | |
593 if (unchecked_reason >= | |
594 static_cast<unsigned short>(kWebSocketNormalClosure) && | |
595 unchecked_reason <= | |
596 static_cast<unsigned short>(kWebSocketErrorPrivateReservedMax)) { | |
597 *reason = unchecked_reason; | |
598 } else { | |
599 VLOG(1) << "Close frame contained reason code outside of the valid range: " | |
600 << unchecked_reason; | |
601 *reason = kWebSocketErrorProtocolError; | |
602 } | |
603 std::string text(data + kWebSocketCloseCodeLength, data + size); | |
604 // TODO(ricea): Is this check strict enough? In particular, check the | |
605 // "Security Considerations" from RFC3629. | |
606 if (IsStringUTF8(text)) { | |
607 using std::swap; | |
608 swap(*reason_text, text); | |
609 } | |
610 } | |
611 | |
612 } // namespace net | |
OLD | NEW |