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

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

Issue 23604044: Replace WebSocketFrameChunk with WebSocketFrame (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Fixes to debug printing. Created 7 years, 3 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_basic_stream.h" 5 #include "net/websockets/websocket_basic_stream.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <limits> 8 #include <limits>
9 #include <string> 9 #include <string>
10 #include <vector> 10 #include <vector>
11 11
12 #include "base/basictypes.h" 12 #include "base/basictypes.h"
13 #include "base/bind.h" 13 #include "base/bind.h"
14 #include "base/logging.h" 14 #include "base/logging.h"
15 #include "base/safe_numerics.h"
15 #include "net/base/io_buffer.h" 16 #include "net/base/io_buffer.h"
16 #include "net/base/net_errors.h" 17 #include "net/base/net_errors.h"
17 #include "net/socket/client_socket_handle.h" 18 #include "net/socket/client_socket_handle.h"
18 #include "net/websockets/websocket_errors.h" 19 #include "net/websockets/websocket_errors.h"
19 #include "net/websockets/websocket_frame.h" 20 #include "net/websockets/websocket_frame.h"
20 #include "net/websockets/websocket_frame_parser.h" 21 #include "net/websockets/websocket_frame_parser.h"
21 22
22 namespace net { 23 namespace net {
23 24
24 namespace { 25 namespace {
25 26
27 // This uses type uint64 to match the definition of
28 // WebSocketFrameHeader::payload_length in websocket_frame.h.
29 const uint64 kMaxControlFramePayload = 125;
30
26 // The number of bytes to attempt to read at a time. 31 // The number of bytes to attempt to read at a time.
27 // TODO(ricea): See if there is a better number or algorithm to fulfill our 32 // TODO(ricea): See if there is a better number or algorithm to fulfill our
28 // requirements: 33 // requirements:
29 // 1. We would like to use minimal memory on low-bandwidth or idle connections 34 // 1. We would like to use minimal memory on low-bandwidth or idle connections
30 // 2. We would like to read as close to line speed as possible on 35 // 2. We would like to read as close to line speed as possible on
31 // high-bandwidth connections 36 // high-bandwidth connections
32 // 3. We can't afford to cause jank on the IO thread by copying large buffers 37 // 3. We can't afford to cause jank on the IO thread by copying large buffers
33 // around 38 // around
34 // 4. We would like to hit any sweet-spots that might exist in terms of network 39 // 4. We would like to hit any sweet-spots that might exist in terms of network
35 // packet sizes / encryption block sizes / IPC alignment issues, etc. 40 // packet sizes / encryption block sizes / IPC alignment issues, etc.
36 const int kReadBufferSize = 32 * 1024; 41 const int kReadBufferSize = 32 * 1024;
37 42
38 } // namespace 43 } // namespace
39 44
40 WebSocketBasicStream::WebSocketBasicStream( 45 WebSocketBasicStream::WebSocketBasicStream(
41 scoped_ptr<ClientSocketHandle> connection) 46 scoped_ptr<ClientSocketHandle> connection)
42 : read_buffer_(new IOBufferWithSize(kReadBufferSize)), 47 : read_buffer_(new IOBufferWithSize(kReadBufferSize)),
43 connection_(connection.Pass()), 48 connection_(connection.Pass()),
44 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) { 49 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
45 DCHECK(connection_->is_initialized()); 50 DCHECK(connection_->is_initialized());
46 } 51 }
47 52
48 WebSocketBasicStream::~WebSocketBasicStream() { Close(); } 53 WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
49 54
50 int WebSocketBasicStream::ReadFrames( 55 int WebSocketBasicStream::ReadFrames(ScopedVector<WebSocketFrame>* frames,
51 ScopedVector<WebSocketFrameChunk>* frame_chunks, 56 const CompletionCallback& callback) {
52 const CompletionCallback& callback) { 57 DCHECK(frames->empty());
53 DCHECK(frame_chunks->empty());
54 // If there is data left over after parsing the HTTP headers, attempt to parse 58 // If there is data left over after parsing the HTTP headers, attempt to parse
55 // it as WebSocket frames. 59 // it as WebSocket frames.
56 if (http_read_buffer_) { 60 if (http_read_buffer_) {
57 DCHECK_GE(http_read_buffer_->offset(), 0); 61 DCHECK_GE(http_read_buffer_->offset(), 0);
58 // We cannot simply copy the data into read_buffer_, as it might be too 62 // We cannot simply copy the data into read_buffer_, as it might be too
59 // large. 63 // large.
60 scoped_refptr<GrowableIOBuffer> buffered_data; 64 scoped_refptr<GrowableIOBuffer> buffered_data;
61 buffered_data.swap(http_read_buffer_); 65 buffered_data.swap(http_read_buffer_);
62 DCHECK(http_read_buffer_.get() == NULL); 66 DCHECK(http_read_buffer_.get() == NULL);
67 ScopedVector<WebSocketFrameChunk> frame_chunks;
63 if (!parser_.Decode(buffered_data->StartOfBuffer(), 68 if (!parser_.Decode(buffered_data->StartOfBuffer(),
64 buffered_data->offset(), 69 buffered_data->offset(),
65 frame_chunks)) 70 &frame_chunks))
66 return WebSocketErrorToNetError(parser_.websocket_error()); 71 return WebSocketErrorToNetError(parser_.websocket_error());
67 if (!frame_chunks->empty()) 72 if (!frame_chunks.empty())
68 return OK; 73 return ConvertChunksToFrames(&frame_chunks, frames);
69 } 74 }
70 75
71 // Run until socket stops giving us data or we get some chunks. 76 // Run until socket stops giving us data or we get some frames.
72 while (true) { 77 while (true) {
73 // base::Unretained(this) here is safe because net::Socket guarantees not to 78 // base::Unretained(this) here is safe because net::Socket guarantees not to
74 // call any callbacks after Disconnect(), which we call from the 79 // call any callbacks after Disconnect(), which we call from the
75 // destructor. The caller of ReadFrames() is required to keep |frame_chunks| 80 // destructor. The caller of ReadFrames() is required to keep |frames|
76 // valid. 81 // valid.
77 int result = connection_->socket() 82 int result = connection_->socket()->Read(
78 ->Read(read_buffer_.get(), 83 read_buffer_.get(),
79 read_buffer_->size(), 84 read_buffer_->size(),
80 base::Bind(&WebSocketBasicStream::OnReadComplete, 85 base::Bind(&WebSocketBasicStream::OnReadComplete,
81 base::Unretained(this), 86 base::Unretained(this),
82 base::Unretained(frame_chunks), 87 base::Unretained(frames),
83 callback)); 88 callback));
84 if (result == ERR_IO_PENDING) 89 if (result == ERR_IO_PENDING)
85 return result; 90 return result;
86 result = HandleReadResult(result, frame_chunks); 91 result = HandleReadResult(result, frames);
87 if (result != ERR_IO_PENDING) 92 if (result != ERR_IO_PENDING)
88 return result; 93 return result;
89 } 94 }
90 } 95 }
91 96
92 int WebSocketBasicStream::WriteFrames( 97 int WebSocketBasicStream::WriteFrames(ScopedVector<WebSocketFrame>* frames,
93 ScopedVector<WebSocketFrameChunk>* frame_chunks, 98 const CompletionCallback& callback) {
94 const CompletionCallback& callback) {
95 // This function always concatenates all frames into a single buffer. 99 // This function always concatenates all frames into a single buffer.
96 // TODO(ricea): Investigate whether it would be better in some cases to 100 // TODO(ricea): Investigate whether it would be better in some cases to
97 // perform multiple writes with smaller buffers. 101 // perform multiple writes with smaller buffers.
98 // 102 //
99 // First calculate the size of the buffer we need to allocate. 103 // First calculate the size of the buffer we need to allocate.
100 typedef ScopedVector<WebSocketFrameChunk>::const_iterator Iterator; 104 typedef ScopedVector<WebSocketFrame>::const_iterator Iterator;
101 const int kMaximumTotalSize = std::numeric_limits<int>::max(); 105 const int kMaximumTotalSize = std::numeric_limits<int>::max();
102 int total_size = 0; 106 int total_size = 0;
103 for (Iterator it = frame_chunks->begin(); it != frame_chunks->end(); ++it) { 107 for (Iterator it = frames->begin(); it != frames->end(); ++it) {
104 WebSocketFrameChunk* chunk = *it; 108 WebSocketFrame* frame = *it;
105 DCHECK(chunk->header)
106 << "Only complete frames are supported by WebSocketBasicStream";
107 DCHECK(chunk->final_chunk)
108 << "Only complete frames are supported by WebSocketBasicStream";
109 // Force the masked bit on. 109 // Force the masked bit on.
110 chunk->header->masked = true; 110 frame->header.masked = true;
111 // We enforce flow control so the renderer should never be able to force us 111 // We enforce flow control so the renderer should never be able to force us
112 // to cache anywhere near 2GB of frames. 112 // to cache anywhere near 2GB of frames.
113 int chunk_size = 113 int frame_size = frame->header.payload_length +
114 chunk->data->size() + GetWebSocketFrameHeaderSize(*(chunk->header)); 114 GetWebSocketFrameHeaderSize(frame->header);
115 CHECK_GE(kMaximumTotalSize - total_size, chunk_size) 115 CHECK_GE(kMaximumTotalSize - total_size, frame_size)
116 << "Aborting to prevent overflow"; 116 << "Aborting to prevent overflow";
117 total_size += chunk_size; 117 total_size += frame_size;
118 } 118 }
119 scoped_refptr<IOBufferWithSize> combined_buffer( 119 scoped_refptr<IOBufferWithSize> combined_buffer(
120 new IOBufferWithSize(total_size)); 120 new IOBufferWithSize(total_size));
121 char* dest = combined_buffer->data(); 121 char* dest = combined_buffer->data();
122 int remaining_size = total_size; 122 int remaining_size = total_size;
123 for (Iterator it = frame_chunks->begin(); it != frame_chunks->end(); ++it) { 123 for (Iterator it = frames->begin(); it != frames->end(); ++it) {
124 WebSocketFrameChunk* chunk = *it; 124 WebSocketFrame* frame = *it;
125 WebSocketMaskingKey mask = generate_websocket_masking_key_(); 125 WebSocketMaskingKey mask = generate_websocket_masking_key_();
126 int result = WriteWebSocketFrameHeader( 126 int result =
127 *(chunk->header), &mask, dest, remaining_size); 127 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
128 DCHECK(result != ERR_INVALID_ARGUMENT) 128 DCHECK(result != ERR_INVALID_ARGUMENT)
129 << "WriteWebSocketFrameHeader() says that " << remaining_size 129 << "WriteWebSocketFrameHeader() says that " << remaining_size
130 << " is not enough to write the header in. This should not happen."; 130 << " is not enough to write the header in. This should not happen.";
131 CHECK_GE(result, 0) << "Potentially security-critical check failed"; 131 CHECK_GE(result, 0) << "Potentially security-critical check failed";
132 dest += result; 132 dest += result;
133 remaining_size -= result; 133 remaining_size -= result;
134 134
135 const char* const frame_data = chunk->data->data(); 135 const char* const frame_data = frame->data->data();
136 const int frame_size = chunk->data->size(); 136 const int frame_size = frame->header.payload_length;
137 CHECK_GE(remaining_size, frame_size); 137 CHECK_GE(remaining_size, frame_size);
138 std::copy(frame_data, frame_data + frame_size, dest); 138 std::copy(frame_data, frame_data + frame_size, dest);
139 MaskWebSocketFramePayload(mask, 0, dest, frame_size); 139 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
140 dest += frame_size; 140 dest += frame_size;
141 remaining_size -= frame_size; 141 remaining_size -= frame_size;
142 } 142 }
143 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; " 143 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
144 << remaining_size << " bytes left over."; 144 << remaining_size << " bytes left over.";
145 scoped_refptr<DrainableIOBuffer> drainable_buffer( 145 scoped_refptr<DrainableIOBuffer> drainable_buffer(
146 new DrainableIOBuffer(combined_buffer, total_size)); 146 new DrainableIOBuffer(combined_buffer, total_size));
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
189 stream->generate_websocket_masking_key_ = key_generator_function; 189 stream->generate_websocket_masking_key_ = key_generator_function;
190 return stream.Pass(); 190 return stream.Pass();
191 } 191 }
192 192
193 int WebSocketBasicStream::WriteEverything( 193 int WebSocketBasicStream::WriteEverything(
194 const scoped_refptr<DrainableIOBuffer>& buffer, 194 const scoped_refptr<DrainableIOBuffer>& buffer,
195 const CompletionCallback& callback) { 195 const CompletionCallback& callback) {
196 while (buffer->BytesRemaining() > 0) { 196 while (buffer->BytesRemaining() > 0) {
197 // The use of base::Unretained() here is safe because on destruction we 197 // The use of base::Unretained() here is safe because on destruction we
198 // disconnect the socket, preventing any further callbacks. 198 // disconnect the socket, preventing any further callbacks.
199 int result = connection_->socket() 199 int result = connection_->socket()->Write(
200 ->Write(buffer.get(), 200 buffer.get(),
201 buffer->BytesRemaining(), 201 buffer->BytesRemaining(),
202 base::Bind(&WebSocketBasicStream::OnWriteComplete, 202 base::Bind(&WebSocketBasicStream::OnWriteComplete,
203 base::Unretained(this), 203 base::Unretained(this),
204 buffer, 204 buffer,
205 callback)); 205 callback));
206 if (result > 0) { 206 if (result > 0) {
207 buffer->DidConsume(result); 207 buffer->DidConsume(result);
208 } else { 208 } else {
209 return result; 209 return result;
210 } 210 }
211 } 211 }
212 return OK; 212 return OK;
213 } 213 }
214 214
215 void WebSocketBasicStream::OnWriteComplete( 215 void WebSocketBasicStream::OnWriteComplete(
216 const scoped_refptr<DrainableIOBuffer>& buffer, 216 const scoped_refptr<DrainableIOBuffer>& buffer,
217 const CompletionCallback& callback, 217 const CompletionCallback& callback,
218 int result) { 218 int result) {
219 if (result < 0) { 219 if (result < 0) {
220 DCHECK(result != ERR_IO_PENDING); 220 DCHECK(result != ERR_IO_PENDING);
221 callback.Run(result); 221 callback.Run(result);
222 return; 222 return;
223 } 223 }
224 224
225 DCHECK(result != 0); 225 DCHECK(result != 0);
226 buffer->DidConsume(result); 226 buffer->DidConsume(result);
227 result = WriteEverything(buffer, callback); 227 result = WriteEverything(buffer, callback);
228 if (result != ERR_IO_PENDING) 228 if (result != ERR_IO_PENDING)
229 callback.Run(result); 229 callback.Run(result);
230 } 230 }
231 231
232 int WebSocketBasicStream::HandleReadResult( 232 int WebSocketBasicStream::HandleReadResult(
233 int result, 233 int result,
234 ScopedVector<WebSocketFrameChunk>* frame_chunks) { 234 ScopedVector<WebSocketFrame>* frames) {
235 DCHECK_NE(ERR_IO_PENDING, result); 235 DCHECK_NE(ERR_IO_PENDING, result);
236 DCHECK(frame_chunks->empty()); 236 DCHECK(frames->empty());
237 if (result < 0) 237 if (result < 0)
238 return result; 238 return result;
239 if (result == 0) 239 if (result == 0)
240 return ERR_CONNECTION_CLOSED; 240 return ERR_CONNECTION_CLOSED;
241 if (!parser_.Decode(read_buffer_->data(), result, frame_chunks)) 241 ScopedVector<WebSocketFrameChunk> frame_chunks;
242 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
242 return WebSocketErrorToNetError(parser_.websocket_error()); 243 return WebSocketErrorToNetError(parser_.websocket_error());
243 if (!frame_chunks->empty()) 244 if (frame_chunks.empty())
244 return OK; 245 return ERR_IO_PENDING;
245 return ERR_IO_PENDING; 246 return ConvertChunksToFrames(&frame_chunks, frames);
246 } 247 }
247 248
248 void WebSocketBasicStream::OnReadComplete( 249 int WebSocketBasicStream::ConvertChunksToFrames(
249 ScopedVector<WebSocketFrameChunk>* frame_chunks, 250 ScopedVector<WebSocketFrameChunk>* frame_chunks,
250 const CompletionCallback& callback, 251 ScopedVector<WebSocketFrame>* frames) {
251 int result) { 252 for (size_t i = 0; i < frame_chunks->size(); ++i) {
252 result = HandleReadResult(result, frame_chunks); 253 scoped_ptr<WebSocketFrame> frame;
254 int result = ConvertChunkToFrame(
255 scoped_ptr<WebSocketFrameChunk>((*frame_chunks)[i]), &frame);
256 (*frame_chunks)[i] = NULL;
257 if (result != OK)
258 return result;
259 if (frame)
260 frames->push_back(frame.release());
261 }
262 // All the elements of |frame_chunks| are now NULL, so there is no point in
263 // calling delete on them all.
264 frame_chunks->weak_clear();
265 if (frames->empty())
266 return ERR_IO_PENDING;
267 return OK;
268 }
269
270 int WebSocketBasicStream::ConvertChunkToFrame(
271 scoped_ptr<WebSocketFrameChunk> chunk,
272 scoped_ptr<WebSocketFrame>* frame) {
273 DCHECK(frame->get() == NULL);
274 bool is_first_chunk = false;
275 if (chunk->header) {
276 DCHECK(current_frame_header_ == NULL)
277 << "Received the header for a new frame without notification that "
278 << "the previous frame was complete (bug in WebSocketFrameParser?)";
279 is_first_chunk = true;
280 current_frame_header_.swap(chunk->header);
281 }
282 int chunk_size = chunk->data ? chunk->data->size() : 0;
283 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
284 << "(final_chunk = " << chunk->final_chunk
285 << ", data size = " << chunk_size
286 << ") (bug in WebSocketFrameParser?)";
287 scoped_refptr<IOBufferWithSize> data_buffer;
288 data_buffer.swap(chunk->data);
289 const bool is_final_chunk = chunk->final_chunk;
290 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
291 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
292 bool protocol_error = false;
293 if (!current_frame_header_->final) {
294 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
295 << " received with FIN bit unset.";
296 protocol_error = true;
297 }
298 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
299 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
300 << ", payload_length=" << current_frame_header_->payload_length
301 << " exceeds maximum payload length for a control message.";
302 protocol_error = true;
303 }
304 if (protocol_error) {
305 current_frame_header_.reset();
306 return ERR_WS_PROTOCOL_ERROR;
307 }
308 if (!is_final_chunk) {
309 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
310 if (incomplete_control_frame_body_) {
311 DVLOG(3) << "Appending to an existing split control frame.";
312 AddToIncompleteControlFrameBody(data_buffer);
313 } else {
314 DVLOG(3) << "Creating new storage for an incomplete control frame.";
315 incomplete_control_frame_body_ = new GrowableIOBuffer();
316 // This method checks for oversize control frames above, so as long as
317 // the frame parser is working correctly, this won't overflow. If a bug
318 // does cause it to overflow, it will CHECK() in
319 // AddToIncompleteControlFrameBody() without writing outside the buffer.
320 incomplete_control_frame_body_->SetCapacity(kMaxControlFramePayload);
321 AddToIncompleteControlFrameBody(data_buffer);
322 }
323 return OK;
324 }
325 if (incomplete_control_frame_body_) {
326 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
327 AddToIncompleteControlFrameBody(data_buffer);
328 const int body_size = incomplete_control_frame_body_->offset();
329 data_buffer = new IOBufferWithSize(body_size);
330 memcpy(data_buffer->data(),
331 incomplete_control_frame_body_->StartOfBuffer(),
332 body_size);
333 chunk_size = body_size;
334 incomplete_control_frame_body_ = NULL; // Frame now complete.
335 is_first_chunk = true; // Avoid having our opcode re-written.
336 }
337 }
338
339 // Apply basic sanity checks to the |payload_length| field from the frame
340 // header. A check for exact equality can only be used when the whole frame
341 // arrives in one chunk.
342 DCHECK_GE(current_frame_header_->payload_length,
343 base::checked_numeric_cast<uint64>(chunk_size));
344 DCHECK(!is_first_chunk || !is_final_chunk ||
345 current_frame_header_->payload_length ==
346 base::checked_numeric_cast<uint64>(chunk_size));
347
348 // Convert the chunk to a complete frame.
349 const bool final = is_final_chunk && current_frame_header_->final;
yhirano 2013/09/13 10:03:17 [opt] I think is_final_chunk_in_message is a bette
Adam Rice 2013/09/13 14:09:53 Done.
350 // Empty frames are a waste of CPU unless they have the "final" bit set.
351 if (final || chunk_size > 0) {
352 scoped_ptr<WebSocketFrame> result_frame(new WebSocketFrame(opcode));
353 result_frame->header.CopyFrom(*current_frame_header_);
354 result_frame->header.final = final;
355 result_frame->header.payload_length = data_buffer->size();
356 if (!is_first_chunk && opcode != WebSocketFrameHeader::kOpCodeContinuation)
357 result_frame->header.opcode = WebSocketFrameHeader::kOpCodeContinuation;
358 result_frame->data = data_buffer;
359 frame->swap(result_frame);
360 }
361 // Make sure that a frame header is not applied to any chunks that do not
362 // belong to it.
363 if (is_final_chunk)
364 current_frame_header_.reset();
365 return OK;
366 }
367
368 void WebSocketBasicStream::AddToIncompleteControlFrameBody(
369 const scoped_refptr<IOBufferWithSize>& data_buffer) {
370 if (!data_buffer)
371 return;
372 const int new_offset =
373 incomplete_control_frame_body_->offset() + data_buffer->size();
374 CHECK_GE(incomplete_control_frame_body_->capacity(), new_offset)
375 << "Control frame body larger than frame header indicates; frame parser "
376 "bug?";
377 memcpy(incomplete_control_frame_body_->data(),
378 data_buffer->data(),
379 data_buffer->size());
380 incomplete_control_frame_body_->set_offset(new_offset);
381 }
382
383 void WebSocketBasicStream::OnReadComplete(ScopedVector<WebSocketFrame>* frames,
384 const CompletionCallback& callback,
385 int result) {
386 result = HandleReadResult(result, frames);
253 if (result == ERR_IO_PENDING) 387 if (result == ERR_IO_PENDING)
254 result = ReadFrames(frame_chunks, callback); 388 result = ReadFrames(frames, callback);
255 if (result != ERR_IO_PENDING) 389 if (result != ERR_IO_PENDING)
256 callback.Run(result); 390 callback.Run(result);
257 } 391 }
258 392
259 } // namespace net 393 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698