blob: 3862ec39ab77518ddd68ce46a95c9a46887d61b9 [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
tfarinaea94afc232015-10-20 04:23:367#include <stddef.h>
tfarina8a2c66c22015-10-13 19:14:498#include <stdint.h>
[email protected]adb225d2013-08-30 13:14:439#include <algorithm>
10#include <limits>
yhirano592ff7f2015-12-07 08:45:1911#include <utility>
[email protected]adb225d2013-08-30 13:14:4312
[email protected]adb225d2013-08-30 13:14:4313#include "base/bind.h"
Yoichi Osato14073bd2019-06-04 11:06:3714#include "base/command_line.h"
[email protected]adb225d2013-08-30 13:14:4315#include "base/logging.h"
rajendrant75fe34f2017-03-28 05:53:0016#include "base/metrics/histogram_macros.h"
[email protected]cb154062014-01-17 03:32:4017#include "base/numerics/safe_conversions.h"
Yoichi Osato14073bd2019-06-04 11:06:3718#include "base/strings/string_number_conversions.h"
[email protected]adb225d2013-08-30 13:14:4319#include "net/base/io_buffer.h"
20#include "net/base/net_errors.h"
21#include "net/socket/client_socket_handle.h"
Bence Béky7294fc22018-02-08 14:26:1722#include "net/websockets/websocket_basic_stream_adapters.h"
[email protected]adb225d2013-08-30 13:14:4323#include "net/websockets/websocket_errors.h"
24#include "net/websockets/websocket_frame.h"
[email protected]adb225d2013-08-30 13:14:4325
26namespace net {
27
28namespace {
29
Ramin Halavaticdb199a62018-01-25 12:38:1930// Please refer to the comment in class header if the usage changes.
31constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
32 net::DefineNetworkTrafficAnnotation("websocket_basic_stream", R"(
33 semantics {
34 sender: "WebSocket Basic Stream"
35 description:
36 "Implementation of WebSocket API from web content (a page the user "
37 "visits)."
38 trigger: "Website calls the WebSocket API."
39 data:
40 "Any data provided by web content, masked and framed in accordance "
41 "with RFC6455."
42 destination: OTHER
43 destination_other:
44 "The address that the website has chosen to communicate to."
45 }
46 policy {
47 cookies_allowed: YES
48 cookies_store: "user"
49 setting: "These requests cannot be disabled."
50 policy_exception_justification:
51 "Not implemented. WebSocket is a core web platform API."
52 }
53 comments:
54 "The browser will never add cookies to a WebSocket message. But the "
55 "handshake that was performed when the WebSocket connection was "
56 "established may have contained cookies."
57 )");
58
tfarina8a2c66c22015-10-13 19:14:4959// This uses type uint64_t to match the definition of
[email protected]2f5d9f62013-09-26 12:14:2860// WebSocketFrameHeader::payload_length in websocket_frame.h.
tfarina8a2c66c22015-10-13 19:14:4961const uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2862
[email protected]adb225d2013-08-30 13:14:4363// The number of bytes to attempt to read at a time.
64// TODO(ricea): See if there is a better number or algorithm to fulfill our
65// requirements:
66// 1. We would like to use minimal memory on low-bandwidth or idle connections
67// 2. We would like to read as close to line speed as possible on
68// high-bandwidth connections
69// 3. We can't afford to cause jank on the IO thread by copying large buffers
70// around
71// 4. We would like to hit any sweet-spots that might exist in terms of network
72// packet sizes / encryption block sizes / IPC alignment issues, etc.
73const int kReadBufferSize = 32 * 1024;
74
[email protected]9576544a2013-10-11 08:36:3375// Returns the total serialized size of |frames|. This function assumes that
76// |frames| will be serialized with mask field. This function forces the
77// masked bit of the frames on.
78int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3379 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4980 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3381
tfarina8a2c66c22015-10-13 19:14:4982 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1983 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3384 // Force the masked bit on.
85 frame->header.masked = true;
86 // We enforce flow control so the renderer should never be able to force us
87 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4988 uint64_t frame_size = frame->header.payload_length +
89 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:3490 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:3391 << "Aborting to prevent overflow";
92 total_size += frame_size;
93 }
pkasting4bff6be2014-10-15 17:54:3494 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:3395}
96
[email protected]adb225d2013-08-30 13:14:4397} // namespace
98
Yoichi Osato14073bd2019-06-04 11:06:3799// Overrides default read buffer size for WebSocket. This flag will be used to
100// investigate the performance issue of crbug.com/865001 and be deleted later
101// on.
102const char kWebSocketReadBufferSize[] = "websocket-read-buffer-size";
103
[email protected]adb225d2013-08-30 13:14:43104WebSocketBasicStream::WebSocketBasicStream(
Bence Béky7294fc22018-02-08 14:26:17105 std::unique_ptr<Adapter> connection,
[email protected]86602d3f2013-11-06 00:08:22106 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
107 const std::string& sub_protocol,
108 const std::string& extensions)
Yoichi Osato14073bd2019-06-04 11:06:37109 : connection_(std::move(connection)),
[email protected]86602d3f2013-11-06 00:08:22110 http_read_buffer_(http_read_buffer),
111 sub_protocol_(sub_protocol),
112 extensions_(extensions),
[email protected]adb225d2013-08-30 13:14:43113 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:36114 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:23115 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
Raul Tambre94493c652019-03-11 17:18:35116 http_read_buffer_ = nullptr;
[email protected]adb225d2013-08-30 13:14:43117 DCHECK(connection_->is_initialized());
Yoichi Osato14073bd2019-06-04 11:06:37118 base::CommandLine* const command_line =
119 base::CommandLine::ForCurrentProcess();
120 DCHECK(command_line);
121 int websocket_buffer_size = kReadBufferSize;
122 if (command_line->HasSwitch(kWebSocketReadBufferSize)) {
123 std::string size_string =
124 command_line->GetSwitchValueASCII(kWebSocketReadBufferSize);
125 if (!base::StringToInt(size_string, &websocket_buffer_size) ||
126 websocket_buffer_size <= 0) {
127 websocket_buffer_size = kReadBufferSize;
128 }
129 }
130 DVLOG(1) << "WebSocketReadBufferSize is " << websocket_buffer_size;
131 read_buffer_ =
132 (base::MakeRefCounted<IOBufferWithSize>(websocket_buffer_size));
[email protected]adb225d2013-08-30 13:14:43133}
134
135WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
136
yhirano592ff7f2015-12-07 08:45:19137int WebSocketBasicStream::ReadFrames(
danakj9c5cab52016-04-16 00:54:33138 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05139 CompletionOnceCallback callback) {
140 read_callback_ = std::move(callback);
[email protected]adb225d2013-08-30 13:14:43141
Bence Békyf4f56e22018-07-17 02:00:05142 return ReadEverything(frames);
[email protected]adb225d2013-08-30 13:14:43143}
144
yhirano592ff7f2015-12-07 08:45:19145int WebSocketBasicStream::WriteFrames(
danakj9c5cab52016-04-16 00:54:33146 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05147 CompletionOnceCallback callback) {
[email protected]adb225d2013-08-30 13:14:43148 // This function always concatenates all frames into a single buffer.
149 // TODO(ricea): Investigate whether it would be better in some cases to
150 // perform multiple writes with smaller buffers.
Bence Békyf4f56e22018-07-17 02:00:05151
152 write_callback_ = std::move(callback);
153
[email protected]adb225d2013-08-30 13:14:43154 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33155 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
Bence Béky65623972018-03-05 15:31:56156 auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
[email protected]9576544a2013-10-11 08:36:33157
[email protected]adb225d2013-08-30 13:14:43158 char* dest = combined_buffer->data();
159 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19160 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43161 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28162 int result =
163 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
164 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43165 << "WriteWebSocketFrameHeader() says that " << remaining_size
166 << " is not enough to write the header in. This should not happen.";
167 CHECK_GE(result, 0) << "Potentially security-critical check failed";
168 dest += result;
169 remaining_size -= result;
170
tfarina8a2c66c22015-10-13 19:14:49171 CHECK_LE(frame->header.payload_length,
172 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34173 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44174 if (frame_size > 0) {
[email protected]403ee6e2014-01-27 10:10:44175 const char* const frame_data = frame->data->data();
176 std::copy(frame_data, frame_data + frame_size, dest);
177 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
178 dest += frame_size;
179 remaining_size -= frame_size;
180 }
[email protected]adb225d2013-08-30 13:14:43181 }
182 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
183 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56184 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
185 combined_buffer.get(), total_size);
Bence Békyf4f56e22018-07-17 02:00:05186 return WriteEverything(drainable_buffer);
[email protected]adb225d2013-08-30 13:14:43187}
188
Bence Béky7294fc22018-02-08 14:26:17189void WebSocketBasicStream::Close() {
190 connection_->Disconnect();
191}
[email protected]adb225d2013-08-30 13:14:43192
193std::string WebSocketBasicStream::GetSubProtocol() const {
194 return sub_protocol_;
195}
196
197std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
198
[email protected]adb225d2013-08-30 13:14:43199/*static*/
danakj9c5cab52016-04-16 00:54:33200std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43201WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33202 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43203 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
204 const std::string& sub_protocol,
205 const std::string& extensions,
206 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17207 auto stream = std::make_unique<WebSocketBasicStream>(
208 std::make_unique<WebSocketClientSocketHandleAdapter>(
209 std::move(connection)),
210 http_read_buffer, sub_protocol, extensions);
[email protected]adb225d2013-08-30 13:14:43211 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48212 return stream;
[email protected]adb225d2013-08-30 13:14:43213}
214
Bence Békyf4f56e22018-07-17 02:00:05215int WebSocketBasicStream::ReadEverything(
216 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
217 DCHECK(frames->empty());
218
219 // If there is data left over after parsing the HTTP headers, attempt to parse
220 // it as WebSocket frames.
221 if (http_read_buffer_.get()) {
222 DCHECK_GE(http_read_buffer_->offset(), 0);
223 // We cannot simply copy the data into read_buffer_, as it might be too
224 // large.
225 scoped_refptr<GrowableIOBuffer> buffered_data;
226 buffered_data.swap(http_read_buffer_);
227 DCHECK(!http_read_buffer_);
228 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
229 if (!parser_.Decode(buffered_data->StartOfBuffer(), buffered_data->offset(),
230 &frame_chunks))
231 return WebSocketErrorToNetError(parser_.websocket_error());
232 if (!frame_chunks.empty()) {
233 int result = ConvertChunksToFrames(&frame_chunks, frames);
234 if (result != ERR_IO_PENDING)
235 return result;
236 }
237 }
238
239 // Run until socket stops giving us data or we get some frames.
240 while (true) {
241 // base::Unretained(this) here is safe because net::Socket guarantees not to
242 // call any callbacks after Disconnect(), which we call from the destructor.
243 // The caller of ReadEverything() is required to keep |frames| valid.
244 int result = connection_->Read(
245 read_buffer_.get(), read_buffer_->size(),
246 base::BindOnce(&WebSocketBasicStream::OnReadComplete,
247 base::Unretained(this), base::Unretained(frames)));
248 if (result == ERR_IO_PENDING)
249 return result;
250 result = HandleReadResult(result, frames);
251 if (result != ERR_IO_PENDING)
252 return result;
253 DCHECK(frames->empty());
254 }
255}
256
257void WebSocketBasicStream::OnReadComplete(
258 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
259 int result) {
260 result = HandleReadResult(result, frames);
261 if (result == ERR_IO_PENDING)
262 result = ReadEverything(frames);
263 if (result != ERR_IO_PENDING)
264 std::move(read_callback_).Run(result);
265}
266
[email protected]adb225d2013-08-30 13:14:43267int WebSocketBasicStream::WriteEverything(
Bence Békyf4f56e22018-07-17 02:00:05268 const scoped_refptr<DrainableIOBuffer>& buffer) {
[email protected]adb225d2013-08-30 13:14:43269 while (buffer->BytesRemaining() > 0) {
270 // The use of base::Unretained() here is safe because on destruction we
271 // disconnect the socket, preventing any further callbacks.
Bence Békyf4f56e22018-07-17 02:00:05272 int result = connection_->Write(
273 buffer.get(), buffer->BytesRemaining(),
274 base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
275 base::Unretained(this), buffer),
276 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43277 if (result > 0) {
rajendrant75fe34f2017-03-28 05:53:00278 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
[email protected]adb225d2013-08-30 13:14:43279 buffer->DidConsume(result);
280 } else {
281 return result;
282 }
283 }
284 return OK;
285}
286
287void WebSocketBasicStream::OnWriteComplete(
288 const scoped_refptr<DrainableIOBuffer>& buffer,
[email protected]adb225d2013-08-30 13:14:43289 int result) {
290 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28291 DCHECK_NE(ERR_IO_PENDING, result);
Bence Békyf4f56e22018-07-17 02:00:05292 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43293 return;
294 }
295
[email protected]2f5d9f62013-09-26 12:14:28296 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00297 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
298
[email protected]adb225d2013-08-30 13:14:43299 buffer->DidConsume(result);
Bence Békyf4f56e22018-07-17 02:00:05300 result = WriteEverything(buffer);
[email protected]adb225d2013-08-30 13:14:43301 if (result != ERR_IO_PENDING)
Bence Békyf4f56e22018-07-17 02:00:05302 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43303}
304
305int WebSocketBasicStream::HandleReadResult(
306 int result,
danakj9c5cab52016-04-16 00:54:33307 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43308 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28309 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43310 if (result < 0)
311 return result;
312 if (result == 0)
313 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00314
315 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Downstream", result);
316
danakj9c5cab52016-04-16 00:54:33317 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28318 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43319 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28320 if (frame_chunks.empty())
321 return ERR_IO_PENDING;
322 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43323}
324
[email protected]2f5d9f62013-09-26 12:14:28325int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33326 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
327 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28328 for (size_t i = 0; i < frame_chunks->size(); ++i) {
danakj9c5cab52016-04-16 00:54:33329 std::unique_ptr<WebSocketFrame> frame;
yhirano592ff7f2015-12-07 08:45:19330 int result = ConvertChunkToFrame(std::move((*frame_chunks)[i]), &frame);
[email protected]2f5d9f62013-09-26 12:14:28331 if (result != OK)
332 return result;
333 if (frame)
dchengc7eeda422015-12-26 03:56:48334 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28335 }
yhirano592ff7f2015-12-07 08:45:19336 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28337 if (frames->empty())
338 return ERR_IO_PENDING;
339 return OK;
340}
341
342int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33343 std::unique_ptr<WebSocketFrameChunk> chunk,
344 std::unique_ptr<WebSocketFrame>* frame) {
Raul Tambre94493c652019-03-11 17:18:35345 DCHECK(frame->get() == nullptr);
[email protected]2f5d9f62013-09-26 12:14:28346 bool is_first_chunk = false;
347 if (chunk->header) {
Raul Tambre94493c652019-03-11 17:18:35348 DCHECK(current_frame_header_ == nullptr)
[email protected]2f5d9f62013-09-26 12:14:28349 << "Received the header for a new frame without notification that "
350 << "the previous frame was complete (bug in WebSocketFrameParser?)";
351 is_first_chunk = true;
352 current_frame_header_.swap(chunk->header);
353 }
dchengb206dc412014-08-26 19:46:23354 const int chunk_size = chunk->data.get() ? chunk->data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28355 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
356 << "(final_chunk = " << chunk->final_chunk
357 << ", data size = " << chunk_size
358 << ") (bug in WebSocketFrameParser?)";
359 scoped_refptr<IOBufferWithSize> data_buffer;
360 data_buffer.swap(chunk->data);
361 const bool is_final_chunk = chunk->final_chunk;
362 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
363 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
364 bool protocol_error = false;
365 if (!current_frame_header_->final) {
366 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
367 << " received with FIN bit unset.";
368 protocol_error = true;
369 }
370 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
371 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
372 << ", payload_length=" << current_frame_header_->payload_length
373 << " exceeds maximum payload length for a control message.";
374 protocol_error = true;
375 }
376 if (protocol_error) {
377 current_frame_header_.reset();
378 return ERR_WS_PROTOCOL_ERROR;
379 }
380 if (!is_final_chunk) {
381 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
dchengb206dc412014-08-26 19:46:23382 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28383 DVLOG(3) << "Appending to an existing split control frame.";
384 AddToIncompleteControlFrameBody(data_buffer);
385 } else {
386 DVLOG(3) << "Creating new storage for an incomplete control frame.";
Bence Béky65623972018-03-05 15:31:56387 incomplete_control_frame_body_ =
388 base::MakeRefCounted<GrowableIOBuffer>();
[email protected]2f5d9f62013-09-26 12:14:28389 // This method checks for oversize control frames above, so as long as
390 // the frame parser is working correctly, this won't overflow. If a bug
391 // does cause it to overflow, it will CHECK() in
392 // AddToIncompleteControlFrameBody() without writing outside the buffer.
393 incomplete_control_frame_body_->SetCapacity(kMaxControlFramePayload);
394 AddToIncompleteControlFrameBody(data_buffer);
395 }
396 return OK;
397 }
dchengb206dc412014-08-26 19:46:23398 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28399 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
400 AddToIncompleteControlFrameBody(data_buffer);
401 const int body_size = incomplete_control_frame_body_->offset();
402 DCHECK_EQ(body_size,
403 static_cast<int>(current_frame_header_->payload_length));
Bence Béky65623972018-03-05 15:31:56404 auto body = base::MakeRefCounted<IOBufferWithSize>(body_size);
[email protected]2f5d9f62013-09-26 12:14:28405 memcpy(body->data(),
406 incomplete_control_frame_body_->StartOfBuffer(),
407 body_size);
Raul Tambre94493c652019-03-11 17:18:35408 incomplete_control_frame_body_ = nullptr; // Frame now complete.
[email protected]2f5d9f62013-09-26 12:14:28409 DCHECK(is_final_chunk);
410 *frame = CreateFrame(is_final_chunk, body);
411 return OK;
412 }
413 }
414
415 // Apply basic sanity checks to the |payload_length| field from the frame
416 // header. A check for exact equality can only be used when the whole frame
417 // arrives in one chunk.
418 DCHECK_GE(current_frame_header_->payload_length,
tfarina8a2c66c22015-10-13 19:14:49419 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28420 DCHECK(!is_first_chunk || !is_final_chunk ||
421 current_frame_header_->payload_length ==
tfarina8a2c66c22015-10-13 19:14:49422 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28423
424 // Convert the chunk to a complete frame.
425 *frame = CreateFrame(is_final_chunk, data_buffer);
426 return OK;
427}
428
danakj9c5cab52016-04-16 00:54:33429std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28430 bool is_final_chunk,
431 const scoped_refptr<IOBufferWithSize>& data) {
danakj9c5cab52016-04-16 00:54:33432 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28433 const bool is_final_chunk_in_message =
434 is_final_chunk && current_frame_header_->final;
dchengb206dc412014-08-26 19:46:23435 const int data_size = data.get() ? data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28436 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55437 // Empty frames convey no useful information unless they are the first frame
438 // (containing the type and flags) or have the "final" bit set.
439 if (is_final_chunk_in_message || data_size > 0 ||
440 current_frame_header_->opcode !=
441 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56442 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28443 result_frame->header.CopyFrom(*current_frame_header_);
444 result_frame->header.final = is_final_chunk_in_message;
445 result_frame->header.payload_length = data_size;
446 result_frame->data = data;
447 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47448 // the message. Also clear the reserved bits.
449 // TODO(ricea): If a future extension requires the reserved bits to be
450 // retained on continuation frames, make this behaviour conditional on a
451 // flag set at construction time.
452 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28453 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47454 current_frame_header_->reserved1 = false;
455 current_frame_header_->reserved2 = false;
456 current_frame_header_->reserved3 = false;
457 }
[email protected]2f5d9f62013-09-26 12:14:28458 }
459 // Make sure that a frame header is not applied to any chunks that do not
460 // belong to it.
461 if (is_final_chunk)
462 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48463 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28464}
465
466void WebSocketBasicStream::AddToIncompleteControlFrameBody(
467 const scoped_refptr<IOBufferWithSize>& data_buffer) {
dchengb206dc412014-08-26 19:46:23468 if (!data_buffer.get())
[email protected]2f5d9f62013-09-26 12:14:28469 return;
470 const int new_offset =
471 incomplete_control_frame_body_->offset() + data_buffer->size();
472 CHECK_GE(incomplete_control_frame_body_->capacity(), new_offset)
473 << "Control frame body larger than frame header indicates; frame parser "
474 "bug?";
475 memcpy(incomplete_control_frame_body_->data(),
476 data_buffer->data(),
477 data_buffer->size());
478 incomplete_control_frame_body_->set_offset(new_offset);
479}
480
[email protected]adb225d2013-08-30 13:14:43481} // namespace net