blob: a2c189bc6251f773d46c32f205803fef672093aa [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"
Yoichi Osato13f94a762019-09-09 09:47:3519#include "build/build_config.h"
[email protected]adb225d2013-08-30 13:14:4320#include "net/base/io_buffer.h"
21#include "net/base/net_errors.h"
22#include "net/socket/client_socket_handle.h"
Bence Béky7294fc22018-02-08 14:26:1723#include "net/websockets/websocket_basic_stream_adapters.h"
[email protected]adb225d2013-08-30 13:14:4324#include "net/websockets/websocket_errors.h"
25#include "net/websockets/websocket_frame.h"
[email protected]adb225d2013-08-30 13:14:4326
27namespace net {
28
29namespace {
30
Ramin Halavaticdb199a62018-01-25 12:38:1931// Please refer to the comment in class header if the usage changes.
32constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
33 net::DefineNetworkTrafficAnnotation("websocket_basic_stream", R"(
34 semantics {
35 sender: "WebSocket Basic Stream"
36 description:
37 "Implementation of WebSocket API from web content (a page the user "
38 "visits)."
39 trigger: "Website calls the WebSocket API."
40 data:
41 "Any data provided by web content, masked and framed in accordance "
42 "with RFC6455."
43 destination: OTHER
44 destination_other:
45 "The address that the website has chosen to communicate to."
46 }
47 policy {
48 cookies_allowed: YES
49 cookies_store: "user"
50 setting: "These requests cannot be disabled."
51 policy_exception_justification:
52 "Not implemented. WebSocket is a core web platform API."
53 }
54 comments:
55 "The browser will never add cookies to a WebSocket message. But the "
56 "handshake that was performed when the WebSocket connection was "
57 "established may have contained cookies."
58 )");
59
tfarina8a2c66c22015-10-13 19:14:4960// This uses type uint64_t to match the definition of
[email protected]2f5d9f62013-09-26 12:14:2861// WebSocketFrameHeader::payload_length in websocket_frame.h.
tfarina8a2c66c22015-10-13 19:14:4962const uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2863
[email protected]adb225d2013-08-30 13:14:4364// The number of bytes to attempt to read at a time.
65// TODO(ricea): See if there is a better number or algorithm to fulfill our
66// requirements:
67// 1. We would like to use minimal memory on low-bandwidth or idle connections
68// 2. We would like to read as close to line speed as possible on
69// high-bandwidth connections
70// 3. We can't afford to cause jank on the IO thread by copying large buffers
71// around
72// 4. We would like to hit any sweet-spots that might exist in terms of network
73// packet sizes / encryption block sizes / IPC alignment issues, etc.
Yoichi Osato13f94a762019-09-09 09:47:3574#if defined(OS_ANDROID)
[email protected]adb225d2013-08-30 13:14:4375const int kReadBufferSize = 32 * 1024;
Yoichi Osato13f94a762019-09-09 09:47:3576#else
77const int kReadBufferSize = 131000;
78#endif
[email protected]adb225d2013-08-30 13:14:4379
[email protected]9576544a2013-10-11 08:36:3380// Returns the total serialized size of |frames|. This function assumes that
81// |frames| will be serialized with mask field. This function forces the
82// masked bit of the frames on.
83int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3384 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4985 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3386
tfarina8a2c66c22015-10-13 19:14:4987 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1988 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3389 // Force the masked bit on.
90 frame->header.masked = true;
91 // We enforce flow control so the renderer should never be able to force us
92 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4993 uint64_t frame_size = frame->header.payload_length +
94 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:3495 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:3396 << "Aborting to prevent overflow";
97 total_size += frame_size;
98 }
pkasting4bff6be2014-10-15 17:54:3499 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:33100}
101
[email protected]adb225d2013-08-30 13:14:43102} // namespace
103
Yoichi Osato14073bd2019-06-04 11:06:37104// Overrides default read buffer size for WebSocket. This flag will be used to
105// investigate the performance issue of crbug.com/865001 and be deleted later
106// on.
107const char kWebSocketReadBufferSize[] = "websocket-read-buffer-size";
108
[email protected]adb225d2013-08-30 13:14:43109WebSocketBasicStream::WebSocketBasicStream(
Bence Béky7294fc22018-02-08 14:26:17110 std::unique_ptr<Adapter> connection,
[email protected]86602d3f2013-11-06 00:08:22111 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
112 const std::string& sub_protocol,
113 const std::string& extensions)
Yoichi Osato14073bd2019-06-04 11:06:37114 : connection_(std::move(connection)),
[email protected]86602d3f2013-11-06 00:08:22115 http_read_buffer_(http_read_buffer),
116 sub_protocol_(sub_protocol),
117 extensions_(extensions),
[email protected]adb225d2013-08-30 13:14:43118 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:36119 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:23120 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
Raul Tambre94493c652019-03-11 17:18:35121 http_read_buffer_ = nullptr;
[email protected]adb225d2013-08-30 13:14:43122 DCHECK(connection_->is_initialized());
Yoichi Osato14073bd2019-06-04 11:06:37123 base::CommandLine* const command_line =
124 base::CommandLine::ForCurrentProcess();
125 DCHECK(command_line);
126 int websocket_buffer_size = kReadBufferSize;
127 if (command_line->HasSwitch(kWebSocketReadBufferSize)) {
128 std::string size_string =
129 command_line->GetSwitchValueASCII(kWebSocketReadBufferSize);
130 if (!base::StringToInt(size_string, &websocket_buffer_size) ||
131 websocket_buffer_size <= 0) {
132 websocket_buffer_size = kReadBufferSize;
133 }
134 }
135 DVLOG(1) << "WebSocketReadBufferSize is " << websocket_buffer_size;
136 read_buffer_ =
137 (base::MakeRefCounted<IOBufferWithSize>(websocket_buffer_size));
[email protected]adb225d2013-08-30 13:14:43138}
139
140WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
141
yhirano592ff7f2015-12-07 08:45:19142int WebSocketBasicStream::ReadFrames(
danakj9c5cab52016-04-16 00:54:33143 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05144 CompletionOnceCallback callback) {
145 read_callback_ = std::move(callback);
Yutaka Hirano76aacb202019-09-05 16:36:56146 complete_control_frame_body_.clear();
147 if (http_read_buffer_ && is_http_read_buffer_decoded_) {
148 http_read_buffer_.reset();
149 }
Bence Békyf4f56e22018-07-17 02:00:05150 return ReadEverything(frames);
[email protected]adb225d2013-08-30 13:14:43151}
152
yhirano592ff7f2015-12-07 08:45:19153int WebSocketBasicStream::WriteFrames(
danakj9c5cab52016-04-16 00:54:33154 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05155 CompletionOnceCallback callback) {
[email protected]adb225d2013-08-30 13:14:43156 // This function always concatenates all frames into a single buffer.
157 // TODO(ricea): Investigate whether it would be better in some cases to
158 // perform multiple writes with smaller buffers.
Bence Békyf4f56e22018-07-17 02:00:05159
160 write_callback_ = std::move(callback);
161
[email protected]adb225d2013-08-30 13:14:43162 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33163 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
Bence Béky65623972018-03-05 15:31:56164 auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
[email protected]9576544a2013-10-11 08:36:33165
[email protected]adb225d2013-08-30 13:14:43166 char* dest = combined_buffer->data();
167 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19168 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43169 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28170 int result =
171 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
172 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43173 << "WriteWebSocketFrameHeader() says that " << remaining_size
174 << " is not enough to write the header in. This should not happen.";
175 CHECK_GE(result, 0) << "Potentially security-critical check failed";
176 dest += result;
177 remaining_size -= result;
178
tfarina8a2c66c22015-10-13 19:14:49179 CHECK_LE(frame->header.payload_length,
180 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34181 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44182 if (frame_size > 0) {
Yutaka Hirano76aacb202019-09-05 16:36:56183 const char* const frame_data = frame->data;
[email protected]403ee6e2014-01-27 10:10:44184 std::copy(frame_data, frame_data + frame_size, dest);
185 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
186 dest += frame_size;
187 remaining_size -= frame_size;
188 }
[email protected]adb225d2013-08-30 13:14:43189 }
190 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
191 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56192 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
193 combined_buffer.get(), total_size);
Bence Békyf4f56e22018-07-17 02:00:05194 return WriteEverything(drainable_buffer);
[email protected]adb225d2013-08-30 13:14:43195}
196
Bence Béky7294fc22018-02-08 14:26:17197void WebSocketBasicStream::Close() {
198 connection_->Disconnect();
199}
[email protected]adb225d2013-08-30 13:14:43200
201std::string WebSocketBasicStream::GetSubProtocol() const {
202 return sub_protocol_;
203}
204
205std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
206
[email protected]adb225d2013-08-30 13:14:43207/*static*/
danakj9c5cab52016-04-16 00:54:33208std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43209WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33210 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43211 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
212 const std::string& sub_protocol,
213 const std::string& extensions,
214 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17215 auto stream = std::make_unique<WebSocketBasicStream>(
216 std::make_unique<WebSocketClientSocketHandleAdapter>(
217 std::move(connection)),
218 http_read_buffer, sub_protocol, extensions);
[email protected]adb225d2013-08-30 13:14:43219 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48220 return stream;
[email protected]adb225d2013-08-30 13:14:43221}
222
Bence Békyf4f56e22018-07-17 02:00:05223int WebSocketBasicStream::ReadEverything(
224 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
225 DCHECK(frames->empty());
226
227 // If there is data left over after parsing the HTTP headers, attempt to parse
228 // it as WebSocket frames.
Yutaka Hirano76aacb202019-09-05 16:36:56229 if (http_read_buffer_.get() && !is_http_read_buffer_decoded_) {
Bence Békyf4f56e22018-07-17 02:00:05230 DCHECK_GE(http_read_buffer_->offset(), 0);
Yutaka Hirano76aacb202019-09-05 16:36:56231 is_http_read_buffer_decoded_ = true;
Bence Békyf4f56e22018-07-17 02:00:05232 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
Yutaka Hirano76aacb202019-09-05 16:36:56233 if (!parser_.Decode(http_read_buffer_->StartOfBuffer(),
234 http_read_buffer_->offset(), &frame_chunks))
Bence Békyf4f56e22018-07-17 02:00:05235 return WebSocketErrorToNetError(parser_.websocket_error());
236 if (!frame_chunks.empty()) {
237 int result = ConvertChunksToFrames(&frame_chunks, frames);
238 if (result != ERR_IO_PENDING)
239 return result;
240 }
241 }
242
243 // Run until socket stops giving us data or we get some frames.
244 while (true) {
245 // base::Unretained(this) here is safe because net::Socket guarantees not to
246 // call any callbacks after Disconnect(), which we call from the destructor.
247 // The caller of ReadEverything() is required to keep |frames| valid.
248 int result = connection_->Read(
249 read_buffer_.get(), read_buffer_->size(),
250 base::BindOnce(&WebSocketBasicStream::OnReadComplete,
251 base::Unretained(this), base::Unretained(frames)));
252 if (result == ERR_IO_PENDING)
253 return result;
254 result = HandleReadResult(result, frames);
255 if (result != ERR_IO_PENDING)
256 return result;
257 DCHECK(frames->empty());
258 }
259}
260
261void WebSocketBasicStream::OnReadComplete(
262 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
263 int result) {
264 result = HandleReadResult(result, frames);
265 if (result == ERR_IO_PENDING)
266 result = ReadEverything(frames);
267 if (result != ERR_IO_PENDING)
268 std::move(read_callback_).Run(result);
269}
270
[email protected]adb225d2013-08-30 13:14:43271int WebSocketBasicStream::WriteEverything(
Bence Békyf4f56e22018-07-17 02:00:05272 const scoped_refptr<DrainableIOBuffer>& buffer) {
[email protected]adb225d2013-08-30 13:14:43273 while (buffer->BytesRemaining() > 0) {
274 // The use of base::Unretained() here is safe because on destruction we
275 // disconnect the socket, preventing any further callbacks.
Bence Békyf4f56e22018-07-17 02:00:05276 int result = connection_->Write(
277 buffer.get(), buffer->BytesRemaining(),
278 base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
279 base::Unretained(this), buffer),
280 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43281 if (result > 0) {
rajendrant75fe34f2017-03-28 05:53:00282 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
[email protected]adb225d2013-08-30 13:14:43283 buffer->DidConsume(result);
284 } else {
285 return result;
286 }
287 }
288 return OK;
289}
290
291void WebSocketBasicStream::OnWriteComplete(
292 const scoped_refptr<DrainableIOBuffer>& buffer,
[email protected]adb225d2013-08-30 13:14:43293 int result) {
294 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28295 DCHECK_NE(ERR_IO_PENDING, result);
Bence Békyf4f56e22018-07-17 02:00:05296 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43297 return;
298 }
299
[email protected]2f5d9f62013-09-26 12:14:28300 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00301 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
302
[email protected]adb225d2013-08-30 13:14:43303 buffer->DidConsume(result);
Bence Békyf4f56e22018-07-17 02:00:05304 result = WriteEverything(buffer);
[email protected]adb225d2013-08-30 13:14:43305 if (result != ERR_IO_PENDING)
Bence Békyf4f56e22018-07-17 02:00:05306 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43307}
308
309int WebSocketBasicStream::HandleReadResult(
310 int result,
danakj9c5cab52016-04-16 00:54:33311 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43312 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28313 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43314 if (result < 0)
315 return result;
316 if (result == 0)
317 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00318
319 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Downstream", result);
320
danakj9c5cab52016-04-16 00:54:33321 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28322 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43323 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28324 if (frame_chunks.empty())
325 return ERR_IO_PENDING;
326 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43327}
328
[email protected]2f5d9f62013-09-26 12:14:28329int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33330 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
331 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28332 for (size_t i = 0; i < frame_chunks->size(); ++i) {
Yutaka Hirano76aacb202019-09-05 16:36:56333 auto& chunk = (*frame_chunks)[i];
334 DCHECK(chunk == frame_chunks->back() || chunk->final_chunk)
335 << "Only last chunk can have |final_chunk| set to be false.";
danakj9c5cab52016-04-16 00:54:33336 std::unique_ptr<WebSocketFrame> frame;
Yutaka Hirano76aacb202019-09-05 16:36:56337 int result = ConvertChunkToFrame(std::move(chunk), &frame);
[email protected]2f5d9f62013-09-26 12:14:28338 if (result != OK)
339 return result;
340 if (frame)
dchengc7eeda422015-12-26 03:56:48341 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28342 }
yhirano592ff7f2015-12-07 08:45:19343 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28344 if (frames->empty())
345 return ERR_IO_PENDING;
346 return OK;
347}
348
349int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33350 std::unique_ptr<WebSocketFrameChunk> chunk,
351 std::unique_ptr<WebSocketFrame>* frame) {
Raul Tambre94493c652019-03-11 17:18:35352 DCHECK(frame->get() == nullptr);
[email protected]2f5d9f62013-09-26 12:14:28353 bool is_first_chunk = false;
354 if (chunk->header) {
Raul Tambre94493c652019-03-11 17:18:35355 DCHECK(current_frame_header_ == nullptr)
[email protected]2f5d9f62013-09-26 12:14:28356 << "Received the header for a new frame without notification that "
357 << "the previous frame was complete (bug in WebSocketFrameParser?)";
358 is_first_chunk = true;
359 current_frame_header_.swap(chunk->header);
360 }
[email protected]2f5d9f62013-09-26 12:14:28361 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
362 << "(final_chunk = " << chunk->final_chunk
Yutaka Hirano76aacb202019-09-05 16:36:56363 << ", data size = " << chunk->data.size()
[email protected]2f5d9f62013-09-26 12:14:28364 << ") (bug in WebSocketFrameParser?)";
[email protected]2f5d9f62013-09-26 12:14:28365 const bool is_final_chunk = chunk->final_chunk;
366 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
367 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
368 bool protocol_error = false;
369 if (!current_frame_header_->final) {
370 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
371 << " received with FIN bit unset.";
372 protocol_error = true;
373 }
374 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
375 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
376 << ", payload_length=" << current_frame_header_->payload_length
377 << " exceeds maximum payload length for a control message.";
378 protocol_error = true;
379 }
380 if (protocol_error) {
381 current_frame_header_.reset();
382 return ERR_WS_PROTOCOL_ERROR;
383 }
Yutaka Hirano76aacb202019-09-05 16:36:56384
[email protected]2f5d9f62013-09-26 12:14:28385 if (!is_final_chunk) {
386 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
Yutaka Hirano76aacb202019-09-05 16:36:56387 AddToIncompleteControlFrameBody(chunk->data);
[email protected]2f5d9f62013-09-26 12:14:28388 return OK;
389 }
Yutaka Hirano76aacb202019-09-05 16:36:56390
391 if (!incomplete_control_frame_body_.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28392 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
Yutaka Hirano76aacb202019-09-05 16:36:56393 AddToIncompleteControlFrameBody(chunk->data);
[email protected]2f5d9f62013-09-26 12:14:28394 DCHECK(is_final_chunk);
Yutaka Hirano76aacb202019-09-05 16:36:56395 DCHECK(complete_control_frame_body_.empty());
396 complete_control_frame_body_ = std::move(incomplete_control_frame_body_);
397 *frame = CreateFrame(is_final_chunk, complete_control_frame_body_);
[email protected]2f5d9f62013-09-26 12:14:28398 return OK;
399 }
400 }
401
402 // Apply basic sanity checks to the |payload_length| field from the frame
403 // header. A check for exact equality can only be used when the whole frame
404 // arrives in one chunk.
405 DCHECK_GE(current_frame_header_->payload_length,
Yutaka Hirano76aacb202019-09-05 16:36:56406 base::checked_cast<uint64_t>(chunk->data.size()));
[email protected]2f5d9f62013-09-26 12:14:28407 DCHECK(!is_first_chunk || !is_final_chunk ||
408 current_frame_header_->payload_length ==
Yutaka Hirano76aacb202019-09-05 16:36:56409 base::checked_cast<uint64_t>(chunk->data.size()));
[email protected]2f5d9f62013-09-26 12:14:28410
411 // Convert the chunk to a complete frame.
Yutaka Hirano76aacb202019-09-05 16:36:56412 *frame = CreateFrame(is_final_chunk, chunk->data);
[email protected]2f5d9f62013-09-26 12:14:28413 return OK;
414}
415
danakj9c5cab52016-04-16 00:54:33416std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28417 bool is_final_chunk,
Yutaka Hirano76aacb202019-09-05 16:36:56418 base::span<const char> data) {
danakj9c5cab52016-04-16 00:54:33419 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28420 const bool is_final_chunk_in_message =
421 is_final_chunk && current_frame_header_->final;
[email protected]2f5d9f62013-09-26 12:14:28422 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55423 // Empty frames convey no useful information unless they are the first frame
424 // (containing the type and flags) or have the "final" bit set.
Yutaka Hirano76aacb202019-09-05 16:36:56425 if (is_final_chunk_in_message || data.size() > 0 ||
[email protected]e678d4fe2013-10-11 11:27:55426 current_frame_header_->opcode !=
427 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56428 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28429 result_frame->header.CopyFrom(*current_frame_header_);
430 result_frame->header.final = is_final_chunk_in_message;
Yutaka Hirano76aacb202019-09-05 16:36:56431 result_frame->header.payload_length = data.size();
432 result_frame->data = data.data();
[email protected]2f5d9f62013-09-26 12:14:28433 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47434 // the message. Also clear the reserved bits.
435 // TODO(ricea): If a future extension requires the reserved bits to be
436 // retained on continuation frames, make this behaviour conditional on a
437 // flag set at construction time.
438 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28439 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47440 current_frame_header_->reserved1 = false;
441 current_frame_header_->reserved2 = false;
442 current_frame_header_->reserved3 = false;
443 }
[email protected]2f5d9f62013-09-26 12:14:28444 }
445 // Make sure that a frame header is not applied to any chunks that do not
446 // belong to it.
447 if (is_final_chunk)
448 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48449 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28450}
451
452void WebSocketBasicStream::AddToIncompleteControlFrameBody(
Yutaka Hirano76aacb202019-09-05 16:36:56453 base::span<const char> data) {
454 if (data.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28455 return;
Yutaka Hirano76aacb202019-09-05 16:36:56456 }
457 incomplete_control_frame_body_.insert(incomplete_control_frame_body_.end(),
458 data.begin(), data.end());
459 // This method checks for oversize control frames above, so as long as
460 // the frame parser is working correctly, this won't overflow. If a bug
461 // does cause it to overflow, it will CHECK() in
462 // AddToIncompleteControlFrameBody() without writing outside the buffer.
463 CHECK_LE(incomplete_control_frame_body_.size(), kMaxControlFramePayload)
[email protected]2f5d9f62013-09-26 12:14:28464 << "Control frame body larger than frame header indicates; frame parser "
465 "bug?";
[email protected]2f5d9f62013-09-26 12:14:28466}
467
[email protected]adb225d2013-08-30 13:14:43468} // namespace net