blob: c4599f559e9478c4e1847bec0089141650114a4a [file] [log] [blame]
[email protected]adb225d2013-08-30 13:14:431// 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_basic_stream.h"
6
tfarina8a2c66c22015-10-13 19:14:497#include <stdint.h>
[email protected]adb225d2013-08-30 13:14:438#include <algorithm>
9#include <limits>
10#include <string>
11#include <vector>
12
13#include "base/basictypes.h"
14#include "base/bind.h"
15#include "base/logging.h"
[email protected]cb154062014-01-17 03:32:4016#include "base/numerics/safe_conversions.h"
[email protected]adb225d2013-08-30 13:14:4317#include "net/base/io_buffer.h"
18#include "net/base/net_errors.h"
19#include "net/socket/client_socket_handle.h"
20#include "net/websockets/websocket_errors.h"
21#include "net/websockets/websocket_frame.h"
22#include "net/websockets/websocket_frame_parser.h"
23
24namespace net {
25
26namespace {
27
tfarina8a2c66c22015-10-13 19:14:4928// This uses type uint64_t to match the definition of
[email protected]2f5d9f62013-09-26 12:14:2829// WebSocketFrameHeader::payload_length in websocket_frame.h.
tfarina8a2c66c22015-10-13 19:14:4930const uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2831
[email protected]adb225d2013-08-30 13:14:4332// The number of bytes to attempt to read at a time.
33// TODO(ricea): See if there is a better number or algorithm to fulfill our
34// requirements:
35// 1. We would like to use minimal memory on low-bandwidth or idle connections
36// 2. We would like to read as close to line speed as possible on
37// high-bandwidth connections
38// 3. We can't afford to cause jank on the IO thread by copying large buffers
39// around
40// 4. We would like to hit any sweet-spots that might exist in terms of network
41// packet sizes / encryption block sizes / IPC alignment issues, etc.
42const int kReadBufferSize = 32 * 1024;
43
[email protected]9576544a2013-10-11 08:36:3344typedef ScopedVector<WebSocketFrame>::const_iterator WebSocketFrameIterator;
45
46// Returns the total serialized size of |frames|. This function assumes that
47// |frames| will be serialized with mask field. This function forces the
48// masked bit of the frames on.
49int CalculateSerializedSizeAndTurnOnMaskBit(
50 ScopedVector<WebSocketFrame>* frames) {
tfarina8a2c66c22015-10-13 19:14:4951 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3352
tfarina8a2c66c22015-10-13 19:14:4953 uint64_t total_size = 0;
[email protected]693ebf32013-10-23 13:47:0154 for (WebSocketFrameIterator it = frames->begin(); it != frames->end(); ++it) {
[email protected]9576544a2013-10-11 08:36:3355 WebSocketFrame* frame = *it;
56 // Force the masked bit on.
57 frame->header.masked = true;
58 // We enforce flow control so the renderer should never be able to force us
59 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4960 uint64_t frame_size = frame->header.payload_length +
61 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:3462 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:3363 << "Aborting to prevent overflow";
64 total_size += frame_size;
65 }
pkasting4bff6be2014-10-15 17:54:3466 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:3367}
68
[email protected]adb225d2013-08-30 13:14:4369} // namespace
70
71WebSocketBasicStream::WebSocketBasicStream(
[email protected]86602d3f2013-11-06 00:08:2272 scoped_ptr<ClientSocketHandle> connection,
73 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
74 const std::string& sub_protocol,
75 const std::string& extensions)
[email protected]adb225d2013-08-30 13:14:4376 : read_buffer_(new IOBufferWithSize(kReadBufferSize)),
77 connection_(connection.Pass()),
[email protected]86602d3f2013-11-06 00:08:2278 http_read_buffer_(http_read_buffer),
79 sub_protocol_(sub_protocol),
80 extensions_(extensions),
[email protected]adb225d2013-08-30 13:14:4381 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:3682 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:2383 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
[email protected]50133d7a2013-11-07 13:08:3684 http_read_buffer_ = NULL;
[email protected]adb225d2013-08-30 13:14:4385 DCHECK(connection_->is_initialized());
86}
87
88WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
89
[email protected]2f5d9f62013-09-26 12:14:2890int WebSocketBasicStream::ReadFrames(ScopedVector<WebSocketFrame>* frames,
91 const CompletionCallback& callback) {
92 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:4393 // If there is data left over after parsing the HTTP headers, attempt to parse
94 // it as WebSocket frames.
dchengb206dc412014-08-26 19:46:2395 if (http_read_buffer_.get()) {
[email protected]adb225d2013-08-30 13:14:4396 DCHECK_GE(http_read_buffer_->offset(), 0);
97 // We cannot simply copy the data into read_buffer_, as it might be too
98 // large.
99 scoped_refptr<GrowableIOBuffer> buffered_data;
100 buffered_data.swap(http_read_buffer_);
101 DCHECK(http_read_buffer_.get() == NULL);
[email protected]2f5d9f62013-09-26 12:14:28102 ScopedVector<WebSocketFrameChunk> frame_chunks;
[email protected]adb225d2013-08-30 13:14:43103 if (!parser_.Decode(buffered_data->StartOfBuffer(),
104 buffered_data->offset(),
[email protected]2f5d9f62013-09-26 12:14:28105 &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43106 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28107 if (!frame_chunks.empty()) {
108 int result = ConvertChunksToFrames(&frame_chunks, frames);
109 if (result != ERR_IO_PENDING)
110 return result;
111 }
[email protected]adb225d2013-08-30 13:14:43112 }
113
[email protected]2f5d9f62013-09-26 12:14:28114 // Run until socket stops giving us data or we get some frames.
[email protected]adb225d2013-08-30 13:14:43115 while (true) {
116 // base::Unretained(this) here is safe because net::Socket guarantees not to
117 // call any callbacks after Disconnect(), which we call from the
[email protected]2f5d9f62013-09-26 12:14:28118 // destructor. The caller of ReadFrames() is required to keep |frames|
[email protected]adb225d2013-08-30 13:14:43119 // valid.
[email protected]2f5d9f62013-09-26 12:14:28120 int result = connection_->socket()->Read(
121 read_buffer_.get(),
122 read_buffer_->size(),
123 base::Bind(&WebSocketBasicStream::OnReadComplete,
124 base::Unretained(this),
125 base::Unretained(frames),
126 callback));
[email protected]adb225d2013-08-30 13:14:43127 if (result == ERR_IO_PENDING)
128 return result;
[email protected]2f5d9f62013-09-26 12:14:28129 result = HandleReadResult(result, frames);
[email protected]adb225d2013-08-30 13:14:43130 if (result != ERR_IO_PENDING)
131 return result;
[email protected]2f5d9f62013-09-26 12:14:28132 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43133 }
134}
135
[email protected]2f5d9f62013-09-26 12:14:28136int WebSocketBasicStream::WriteFrames(ScopedVector<WebSocketFrame>* frames,
137 const CompletionCallback& callback) {
[email protected]adb225d2013-08-30 13:14:43138 // This function always concatenates all frames into a single buffer.
139 // TODO(ricea): Investigate whether it would be better in some cases to
140 // perform multiple writes with smaller buffers.
141 //
142 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33143 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
[email protected]adb225d2013-08-30 13:14:43144 scoped_refptr<IOBufferWithSize> combined_buffer(
145 new IOBufferWithSize(total_size));
[email protected]9576544a2013-10-11 08:36:33146
[email protected]adb225d2013-08-30 13:14:43147 char* dest = combined_buffer->data();
148 int remaining_size = total_size;
[email protected]693ebf32013-10-23 13:47:01149 for (WebSocketFrameIterator it = frames->begin(); it != frames->end(); ++it) {
[email protected]2f5d9f62013-09-26 12:14:28150 WebSocketFrame* frame = *it;
[email protected]adb225d2013-08-30 13:14:43151 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28152 int result =
153 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
154 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43155 << "WriteWebSocketFrameHeader() says that " << remaining_size
156 << " is not enough to write the header in. This should not happen.";
157 CHECK_GE(result, 0) << "Potentially security-critical check failed";
158 dest += result;
159 remaining_size -= result;
160
tfarina8a2c66c22015-10-13 19:14:49161 CHECK_LE(frame->header.payload_length,
162 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34163 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44164 if (frame_size > 0) {
[email protected]403ee6e2014-01-27 10:10:44165 const char* const frame_data = frame->data->data();
166 std::copy(frame_data, frame_data + frame_size, dest);
167 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
168 dest += frame_size;
169 remaining_size -= frame_size;
170 }
[email protected]adb225d2013-08-30 13:14:43171 }
172 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
173 << remaining_size << " bytes left over.";
174 scoped_refptr<DrainableIOBuffer> drainable_buffer(
dchengb206dc412014-08-26 19:46:23175 new DrainableIOBuffer(combined_buffer.get(), total_size));
[email protected]adb225d2013-08-30 13:14:43176 return WriteEverything(drainable_buffer, callback);
177}
178
179void WebSocketBasicStream::Close() { connection_->socket()->Disconnect(); }
180
181std::string WebSocketBasicStream::GetSubProtocol() const {
182 return sub_protocol_;
183}
184
185std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
186
[email protected]adb225d2013-08-30 13:14:43187/*static*/
188scoped_ptr<WebSocketBasicStream>
189WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
190 scoped_ptr<ClientSocketHandle> connection,
191 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
192 const std::string& sub_protocol,
193 const std::string& extensions,
194 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
[email protected]86602d3f2013-11-06 00:08:22195 scoped_ptr<WebSocketBasicStream> stream(new WebSocketBasicStream(
196 connection.Pass(), http_read_buffer, sub_protocol, extensions));
[email protected]adb225d2013-08-30 13:14:43197 stream->generate_websocket_masking_key_ = key_generator_function;
198 return stream.Pass();
199}
200
201int WebSocketBasicStream::WriteEverything(
202 const scoped_refptr<DrainableIOBuffer>& buffer,
203 const CompletionCallback& callback) {
204 while (buffer->BytesRemaining() > 0) {
205 // The use of base::Unretained() here is safe because on destruction we
206 // disconnect the socket, preventing any further callbacks.
[email protected]2f5d9f62013-09-26 12:14:28207 int result = connection_->socket()->Write(
208 buffer.get(),
209 buffer->BytesRemaining(),
210 base::Bind(&WebSocketBasicStream::OnWriteComplete,
211 base::Unretained(this),
212 buffer,
213 callback));
[email protected]adb225d2013-08-30 13:14:43214 if (result > 0) {
215 buffer->DidConsume(result);
216 } else {
217 return result;
218 }
219 }
220 return OK;
221}
222
223void WebSocketBasicStream::OnWriteComplete(
224 const scoped_refptr<DrainableIOBuffer>& buffer,
225 const CompletionCallback& callback,
226 int result) {
227 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28228 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]adb225d2013-08-30 13:14:43229 callback.Run(result);
230 return;
231 }
232
[email protected]2f5d9f62013-09-26 12:14:28233 DCHECK_NE(0, result);
[email protected]adb225d2013-08-30 13:14:43234 buffer->DidConsume(result);
235 result = WriteEverything(buffer, callback);
236 if (result != ERR_IO_PENDING)
237 callback.Run(result);
238}
239
240int WebSocketBasicStream::HandleReadResult(
241 int result,
[email protected]2f5d9f62013-09-26 12:14:28242 ScopedVector<WebSocketFrame>* frames) {
[email protected]adb225d2013-08-30 13:14:43243 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28244 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43245 if (result < 0)
246 return result;
247 if (result == 0)
248 return ERR_CONNECTION_CLOSED;
[email protected]2f5d9f62013-09-26 12:14:28249 ScopedVector<WebSocketFrameChunk> frame_chunks;
250 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43251 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28252 if (frame_chunks.empty())
253 return ERR_IO_PENDING;
254 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43255}
256
[email protected]2f5d9f62013-09-26 12:14:28257int WebSocketBasicStream::ConvertChunksToFrames(
[email protected]adb225d2013-08-30 13:14:43258 ScopedVector<WebSocketFrameChunk>* frame_chunks,
[email protected]2f5d9f62013-09-26 12:14:28259 ScopedVector<WebSocketFrame>* frames) {
260 for (size_t i = 0; i < frame_chunks->size(); ++i) {
261 scoped_ptr<WebSocketFrame> frame;
262 int result = ConvertChunkToFrame(
263 scoped_ptr<WebSocketFrameChunk>((*frame_chunks)[i]), &frame);
264 (*frame_chunks)[i] = NULL;
265 if (result != OK)
266 return result;
267 if (frame)
hari.singh1b87973c2015-06-01 13:34:07268 frames->push_back(frame.Pass());
[email protected]2f5d9f62013-09-26 12:14:28269 }
270 // All the elements of |frame_chunks| are now NULL, so there is no point in
271 // calling delete on them all.
272 frame_chunks->weak_clear();
273 if (frames->empty())
274 return ERR_IO_PENDING;
275 return OK;
276}
277
278int WebSocketBasicStream::ConvertChunkToFrame(
279 scoped_ptr<WebSocketFrameChunk> chunk,
280 scoped_ptr<WebSocketFrame>* frame) {
281 DCHECK(frame->get() == NULL);
282 bool is_first_chunk = false;
283 if (chunk->header) {
284 DCHECK(current_frame_header_ == NULL)
285 << "Received the header for a new frame without notification that "
286 << "the previous frame was complete (bug in WebSocketFrameParser?)";
287 is_first_chunk = true;
288 current_frame_header_.swap(chunk->header);
289 }
dchengb206dc412014-08-26 19:46:23290 const int chunk_size = chunk->data.get() ? chunk->data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28291 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
292 << "(final_chunk = " << chunk->final_chunk
293 << ", data size = " << chunk_size
294 << ") (bug in WebSocketFrameParser?)";
295 scoped_refptr<IOBufferWithSize> data_buffer;
296 data_buffer.swap(chunk->data);
297 const bool is_final_chunk = chunk->final_chunk;
298 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
299 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
300 bool protocol_error = false;
301 if (!current_frame_header_->final) {
302 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
303 << " received with FIN bit unset.";
304 protocol_error = true;
305 }
306 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
307 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
308 << ", payload_length=" << current_frame_header_->payload_length
309 << " exceeds maximum payload length for a control message.";
310 protocol_error = true;
311 }
312 if (protocol_error) {
313 current_frame_header_.reset();
314 return ERR_WS_PROTOCOL_ERROR;
315 }
316 if (!is_final_chunk) {
317 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
dchengb206dc412014-08-26 19:46:23318 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28319 DVLOG(3) << "Appending to an existing split control frame.";
320 AddToIncompleteControlFrameBody(data_buffer);
321 } else {
322 DVLOG(3) << "Creating new storage for an incomplete control frame.";
323 incomplete_control_frame_body_ = new GrowableIOBuffer();
324 // This method checks for oversize control frames above, so as long as
325 // the frame parser is working correctly, this won't overflow. If a bug
326 // does cause it to overflow, it will CHECK() in
327 // AddToIncompleteControlFrameBody() without writing outside the buffer.
328 incomplete_control_frame_body_->SetCapacity(kMaxControlFramePayload);
329 AddToIncompleteControlFrameBody(data_buffer);
330 }
331 return OK;
332 }
dchengb206dc412014-08-26 19:46:23333 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28334 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
335 AddToIncompleteControlFrameBody(data_buffer);
336 const int body_size = incomplete_control_frame_body_->offset();
337 DCHECK_EQ(body_size,
338 static_cast<int>(current_frame_header_->payload_length));
339 scoped_refptr<IOBufferWithSize> body = new IOBufferWithSize(body_size);
340 memcpy(body->data(),
341 incomplete_control_frame_body_->StartOfBuffer(),
342 body_size);
343 incomplete_control_frame_body_ = NULL; // Frame now complete.
344 DCHECK(is_final_chunk);
345 *frame = CreateFrame(is_final_chunk, body);
346 return OK;
347 }
348 }
349
350 // Apply basic sanity checks to the |payload_length| field from the frame
351 // header. A check for exact equality can only be used when the whole frame
352 // arrives in one chunk.
353 DCHECK_GE(current_frame_header_->payload_length,
tfarina8a2c66c22015-10-13 19:14:49354 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28355 DCHECK(!is_first_chunk || !is_final_chunk ||
356 current_frame_header_->payload_length ==
tfarina8a2c66c22015-10-13 19:14:49357 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28358
359 // Convert the chunk to a complete frame.
360 *frame = CreateFrame(is_final_chunk, data_buffer);
361 return OK;
362}
363
364scoped_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
365 bool is_final_chunk,
366 const scoped_refptr<IOBufferWithSize>& data) {
367 scoped_ptr<WebSocketFrame> result_frame;
368 const bool is_final_chunk_in_message =
369 is_final_chunk && current_frame_header_->final;
dchengb206dc412014-08-26 19:46:23370 const int data_size = data.get() ? data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28371 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55372 // Empty frames convey no useful information unless they are the first frame
373 // (containing the type and flags) or have the "final" bit set.
374 if (is_final_chunk_in_message || data_size > 0 ||
375 current_frame_header_->opcode !=
376 WebSocketFrameHeader::kOpCodeContinuation) {
[email protected]2f5d9f62013-09-26 12:14:28377 result_frame.reset(new WebSocketFrame(opcode));
378 result_frame->header.CopyFrom(*current_frame_header_);
379 result_frame->header.final = is_final_chunk_in_message;
380 result_frame->header.payload_length = data_size;
381 result_frame->data = data;
382 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47383 // the message. Also clear the reserved bits.
384 // TODO(ricea): If a future extension requires the reserved bits to be
385 // retained on continuation frames, make this behaviour conditional on a
386 // flag set at construction time.
387 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28388 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47389 current_frame_header_->reserved1 = false;
390 current_frame_header_->reserved2 = false;
391 current_frame_header_->reserved3 = false;
392 }
[email protected]2f5d9f62013-09-26 12:14:28393 }
394 // Make sure that a frame header is not applied to any chunks that do not
395 // belong to it.
396 if (is_final_chunk)
397 current_frame_header_.reset();
398 return result_frame.Pass();
399}
400
401void WebSocketBasicStream::AddToIncompleteControlFrameBody(
402 const scoped_refptr<IOBufferWithSize>& data_buffer) {
dchengb206dc412014-08-26 19:46:23403 if (!data_buffer.get())
[email protected]2f5d9f62013-09-26 12:14:28404 return;
405 const int new_offset =
406 incomplete_control_frame_body_->offset() + data_buffer->size();
407 CHECK_GE(incomplete_control_frame_body_->capacity(), new_offset)
408 << "Control frame body larger than frame header indicates; frame parser "
409 "bug?";
410 memcpy(incomplete_control_frame_body_->data(),
411 data_buffer->data(),
412 data_buffer->size());
413 incomplete_control_frame_body_->set_offset(new_offset);
414}
415
416void WebSocketBasicStream::OnReadComplete(ScopedVector<WebSocketFrame>* frames,
417 const CompletionCallback& callback,
418 int result) {
419 result = HandleReadResult(result, frames);
[email protected]adb225d2013-08-30 13:14:43420 if (result == ERR_IO_PENDING)
[email protected]2f5d9f62013-09-26 12:14:28421 result = ReadFrames(frames, callback);
[email protected]adb225d2013-08-30 13:14:43422 if (result != ERR_IO_PENDING)
423 callback.Run(result);
424}
425
426} // namespace net