blob: 542122fea5171ee30aa6a56c627f643eb3282cfb [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"
14#include "base/logging.h"
[email protected]cb154062014-01-17 03:32:4015#include "base/numerics/safe_conversions.h"
Yoichi Osato13f94a762019-09-09 09:47:3516#include "build/build_config.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"
Bence Béky7294fc22018-02-08 14:26:1720#include "net/websockets/websocket_basic_stream_adapters.h"
[email protected]adb225d2013-08-30 13:14:4321#include "net/websockets/websocket_errors.h"
22#include "net/websockets/websocket_frame.h"
[email protected]adb225d2013-08-30 13:14:4323
24namespace net {
25
26namespace {
27
Ramin Halavaticdb199a62018-01-25 12:38:1928// Please refer to the comment in class header if the usage changes.
29constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
30 net::DefineNetworkTrafficAnnotation("websocket_basic_stream", R"(
31 semantics {
32 sender: "WebSocket Basic Stream"
33 description:
34 "Implementation of WebSocket API from web content (a page the user "
35 "visits)."
36 trigger: "Website calls the WebSocket API."
37 data:
38 "Any data provided by web content, masked and framed in accordance "
39 "with RFC6455."
40 destination: OTHER
41 destination_other:
42 "The address that the website has chosen to communicate to."
43 }
44 policy {
45 cookies_allowed: YES
46 cookies_store: "user"
47 setting: "These requests cannot be disabled."
48 policy_exception_justification:
49 "Not implemented. WebSocket is a core web platform API."
50 }
51 comments:
52 "The browser will never add cookies to a WebSocket message. But the "
53 "handshake that was performed when the WebSocket connection was "
54 "established may have contained cookies."
55 )");
56
tfarina8a2c66c22015-10-13 19:14:4957// This uses type uint64_t to match the definition of
[email protected]2f5d9f62013-09-26 12:14:2858// WebSocketFrameHeader::payload_length in websocket_frame.h.
Adam Ricee77e5b7d2020-08-31 23:31:0959constexpr uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2860
Nanami Mikiya292e4912022-01-24 06:37:0561// The number of bytes to attempt to read at a time. It's used only for high
62// throughput connections.
[email protected]adb225d2013-08-30 13:14:4363// TODO(ricea): See if there is a better number or algorithm to fulfill our
64// requirements:
65// 1. We would like to use minimal memory on low-bandwidth or idle connections
66// 2. We would like to read as close to line speed as possible on
67// high-bandwidth connections
68// 3. We can't afford to cause jank on the IO thread by copying large buffers
69// around
70// 4. We would like to hit any sweet-spots that might exist in terms of network
71// packet sizes / encryption block sizes / IPC alignment issues, etc.
Xiaohan Wang2a6845b2022-01-08 04:40:5772#if BUILDFLAG(IS_ANDROID)
Nanami Mikiyac78894c2022-01-18 11:32:1073constexpr size_t kLargeReadBufferSize = 32 * 1024;
Yoichi Osato13f94a762019-09-09 09:47:3574#else
Yoichi Osatoba82cef2019-09-10 04:16:0575// |2^n - delta| is better than 2^n on Linux. See crrev.com/c/1792208.
Nanami Mikiyac78894c2022-01-18 11:32:1076constexpr size_t kLargeReadBufferSize = 131000;
Yoichi Osato13f94a762019-09-09 09:47:3577#endif
[email protected]adb225d2013-08-30 13:14:4378
Nanami Mikiya292e4912022-01-24 06:37:0579// The number of bytes to attempt to read at a time. It's set as an initial read
80// buffer size and used for low throughput connections.
81constexpr size_t kSmallReadBufferSize = 1000;
82
Nanami Mikiyac78894c2022-01-18 11:32:1083// The threshold to decide whether to switch the read buffer size.
84constexpr double kThresholdInBytesPerSecond = 1200 * 1000;
85
[email protected]9576544a2013-10-11 08:36:3386// Returns the total serialized size of |frames|. This function assumes that
87// |frames| will be serialized with mask field. This function forces the
88// masked bit of the frames on.
89int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3390 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4991 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3392
tfarina8a2c66c22015-10-13 19:14:4993 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1994 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3395 // Force the masked bit on.
96 frame->header.masked = true;
97 // We enforce flow control so the renderer should never be able to force us
98 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4999 uint64_t frame_size = frame->header.payload_length +
100 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:34101 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:33102 << "Aborting to prevent overflow";
103 total_size += frame_size;
104 }
pkasting4bff6be2014-10-15 17:54:34105 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:33106}
107
Nanami Mikiyad6b837e2022-02-01 05:58:57108base::Value NetLogBufferSizeParam(int buffer_size) {
109 base::Value dict(base::Value::Type::DICTIONARY);
110 dict.SetIntKey("read_buffer_size_in_bytes", buffer_size);
111 return dict;
112}
113
Nanami Mikiyaeedf2722022-02-03 04:12:13114base::Value NetLogFrameHeaderParam(const WebSocketFrameHeader* header) {
115 base::Value dict(base::Value::Type::DICTIONARY);
116 dict.SetBoolKey("final", header->final);
117 dict.SetBoolKey("reserved1", header->reserved1);
118 dict.SetBoolKey("reserved2", header->reserved2);
119 dict.SetBoolKey("reserved3", header->reserved3);
120 dict.SetIntKey("opcode", header->opcode);
121 dict.SetBoolKey("masked", header->masked);
122 dict.SetDoubleKey("payload_length",
123 static_cast<double>(header->payload_length));
124 return dict;
125}
126
Nanami Mikiya292e4912022-01-24 06:37:05127} // namespace
128
129WebSocketBasicStream::BufferSizeManager::BufferSizeManager() = default;
130
131WebSocketBasicStream::BufferSizeManager::~BufferSizeManager() = default;
132
133void WebSocketBasicStream::BufferSizeManager::OnRead(base::TimeTicks now) {
134 read_start_timestamps_.push(now);
Nanami Mikiyac78894c2022-01-18 11:32:10135}
136
Nanami Mikiya292e4912022-01-24 06:37:05137void WebSocketBasicStream::BufferSizeManager::OnReadComplete(
138 base::TimeTicks now,
139 int size) {
140 DCHECK_GT(size, 0);
141 // This cannot overflow because the result is at most
142 // kLargeReadBufferSize*rolling_average_window_.
143 rolling_byte_total_ += size;
144 recent_read_sizes_.push(size);
145 DCHECK_LE(read_start_timestamps_.size(), rolling_average_window_);
146 if (read_start_timestamps_.size() == rolling_average_window_) {
147 DCHECK_EQ(read_start_timestamps_.size(), recent_read_sizes_.size());
148 base::TimeDelta duration = now - read_start_timestamps_.front();
149 base::TimeDelta threshold_duration =
150 base::Seconds(rolling_byte_total_ / kThresholdInBytesPerSecond);
151 read_start_timestamps_.pop();
152 rolling_byte_total_ -= recent_read_sizes_.front();
153 recent_read_sizes_.pop();
154 if (threshold_duration < duration) {
155 buffer_size_ = BufferSize::kSmall;
156 } else {
157 buffer_size_ = BufferSize::kLarge;
158 }
Nanami Mikiyac78894c2022-01-18 11:32:10159 }
160}
161
[email protected]adb225d2013-08-30 13:14:43162WebSocketBasicStream::WebSocketBasicStream(
Bence Béky7294fc22018-02-08 14:26:17163 std::unique_ptr<Adapter> connection,
[email protected]86602d3f2013-11-06 00:08:22164 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
165 const std::string& sub_protocol,
Nanami Mikiyad6b837e2022-02-01 05:58:57166 const std::string& extensions,
167 const NetLogWithSource& net_log)
Nanami Mikiyac78894c2022-01-18 11:32:10168 : read_buffer_(
Nanami Mikiya292e4912022-01-24 06:37:05169 base::MakeRefCounted<IOBufferWithSize>(kSmallReadBufferSize)),
Nanami Mikiyac78894c2022-01-18 11:32:10170 target_read_buffer_size_(read_buffer_->size()),
Adam Ricee77e5b7d2020-08-31 23:31:09171 connection_(std::move(connection)),
[email protected]86602d3f2013-11-06 00:08:22172 http_read_buffer_(http_read_buffer),
173 sub_protocol_(sub_protocol),
174 extensions_(extensions),
Nanami Mikiyad6b837e2022-02-01 05:58:57175 net_log_(net_log),
[email protected]adb225d2013-08-30 13:14:43176 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:36177 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:23178 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
Raul Tambre94493c652019-03-11 17:18:35179 http_read_buffer_ = nullptr;
[email protected]adb225d2013-08-30 13:14:43180 DCHECK(connection_->is_initialized());
181}
182
183WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
184
yhirano592ff7f2015-12-07 08:45:19185int WebSocketBasicStream::ReadFrames(
danakj9c5cab52016-04-16 00:54:33186 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05187 CompletionOnceCallback callback) {
188 read_callback_ = std::move(callback);
Yutaka Hirano76aacb202019-09-05 16:36:56189 complete_control_frame_body_.clear();
190 if (http_read_buffer_ && is_http_read_buffer_decoded_) {
191 http_read_buffer_.reset();
192 }
Bence Békyf4f56e22018-07-17 02:00:05193 return ReadEverything(frames);
[email protected]adb225d2013-08-30 13:14:43194}
195
yhirano592ff7f2015-12-07 08:45:19196int WebSocketBasicStream::WriteFrames(
danakj9c5cab52016-04-16 00:54:33197 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05198 CompletionOnceCallback callback) {
[email protected]adb225d2013-08-30 13:14:43199 // This function always concatenates all frames into a single buffer.
200 // TODO(ricea): Investigate whether it would be better in some cases to
201 // perform multiple writes with smaller buffers.
Bence Békyf4f56e22018-07-17 02:00:05202
203 write_callback_ = std::move(callback);
204
[email protected]adb225d2013-08-30 13:14:43205 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33206 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
Bence Béky65623972018-03-05 15:31:56207 auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
[email protected]9576544a2013-10-11 08:36:33208
[email protected]adb225d2013-08-30 13:14:43209 char* dest = combined_buffer->data();
210 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19211 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43212 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28213 int result =
214 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
215 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43216 << "WriteWebSocketFrameHeader() says that " << remaining_size
217 << " is not enough to write the header in. This should not happen.";
218 CHECK_GE(result, 0) << "Potentially security-critical check failed";
219 dest += result;
220 remaining_size -= result;
221
tfarina8a2c66c22015-10-13 19:14:49222 CHECK_LE(frame->header.payload_length,
223 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34224 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44225 if (frame_size > 0) {
Yoichi Osato05cd3642019-09-09 18:13:08226 const char* const frame_data = frame->payload;
[email protected]403ee6e2014-01-27 10:10:44227 std::copy(frame_data, frame_data + frame_size, dest);
228 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
229 dest += frame_size;
230 remaining_size -= frame_size;
231 }
[email protected]adb225d2013-08-30 13:14:43232 }
233 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
234 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56235 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
Nanami Mikiyaf9e4f4cf2021-11-25 07:30:13236 std::move(combined_buffer), total_size);
Bence Békyf4f56e22018-07-17 02:00:05237 return WriteEverything(drainable_buffer);
[email protected]adb225d2013-08-30 13:14:43238}
239
Bence Béky7294fc22018-02-08 14:26:17240void WebSocketBasicStream::Close() {
241 connection_->Disconnect();
242}
[email protected]adb225d2013-08-30 13:14:43243
244std::string WebSocketBasicStream::GetSubProtocol() const {
245 return sub_protocol_;
246}
247
248std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
249
[email protected]adb225d2013-08-30 13:14:43250/*static*/
danakj9c5cab52016-04-16 00:54:33251std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43252WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33253 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43254 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
255 const std::string& sub_protocol,
256 const std::string& extensions,
Nanami Mikiyad6b837e2022-02-01 05:58:57257 const NetLogWithSource& net_log,
[email protected]adb225d2013-08-30 13:14:43258 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17259 auto stream = std::make_unique<WebSocketBasicStream>(
260 std::make_unique<WebSocketClientSocketHandleAdapter>(
261 std::move(connection)),
Nanami Mikiyad6b837e2022-02-01 05:58:57262 http_read_buffer, sub_protocol, extensions, net_log);
[email protected]adb225d2013-08-30 13:14:43263 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48264 return stream;
[email protected]adb225d2013-08-30 13:14:43265}
266
Bence Békyf4f56e22018-07-17 02:00:05267int WebSocketBasicStream::ReadEverything(
268 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
269 DCHECK(frames->empty());
270
271 // If there is data left over after parsing the HTTP headers, attempt to parse
272 // it as WebSocket frames.
Yutaka Hirano76aacb202019-09-05 16:36:56273 if (http_read_buffer_.get() && !is_http_read_buffer_decoded_) {
Bence Békyf4f56e22018-07-17 02:00:05274 DCHECK_GE(http_read_buffer_->offset(), 0);
Yutaka Hirano76aacb202019-09-05 16:36:56275 is_http_read_buffer_decoded_ = true;
Bence Békyf4f56e22018-07-17 02:00:05276 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
Yutaka Hirano76aacb202019-09-05 16:36:56277 if (!parser_.Decode(http_read_buffer_->StartOfBuffer(),
278 http_read_buffer_->offset(), &frame_chunks))
Bence Békyf4f56e22018-07-17 02:00:05279 return WebSocketErrorToNetError(parser_.websocket_error());
280 if (!frame_chunks.empty()) {
281 int result = ConvertChunksToFrames(&frame_chunks, frames);
282 if (result != ERR_IO_PENDING)
283 return result;
284 }
285 }
286
287 // Run until socket stops giving us data or we get some frames.
288 while (true) {
Nanami Mikiya292e4912022-01-24 06:37:05289 if (buffer_size_manager_.buffer_size() != buffer_size_) {
290 read_buffer_ = base::MakeRefCounted<IOBufferWithSize>(
291 buffer_size_manager_.buffer_size() == BufferSize::kSmall
292 ? kSmallReadBufferSize
293 : kLargeReadBufferSize);
Nanami Mikiyae8539612022-01-31 03:21:24294 buffer_size_ = buffer_size_manager_.buffer_size();
Nanami Mikiyad6b837e2022-02-01 05:58:57295 net_log_.AddEvent(
296 net::NetLogEventType::WEBSOCKET_READ_BUFFER_SIZE_CHANGED,
297 [&] { return NetLogBufferSizeParam(read_buffer_->size()); });
Nanami Mikiyac78894c2022-01-18 11:32:10298 }
Nanami Mikiya292e4912022-01-24 06:37:05299 buffer_size_manager_.OnRead(base::TimeTicks::Now());
Nanami Mikiyac78894c2022-01-18 11:32:10300
Bence Békyf4f56e22018-07-17 02:00:05301 // base::Unretained(this) here is safe because net::Socket guarantees not to
302 // call any callbacks after Disconnect(), which we call from the destructor.
303 // The caller of ReadEverything() is required to keep |frames| valid.
304 int result = connection_->Read(
305 read_buffer_.get(), read_buffer_->size(),
306 base::BindOnce(&WebSocketBasicStream::OnReadComplete,
307 base::Unretained(this), base::Unretained(frames)));
308 if (result == ERR_IO_PENDING)
309 return result;
310 result = HandleReadResult(result, frames);
311 if (result != ERR_IO_PENDING)
312 return result;
313 DCHECK(frames->empty());
314 }
315}
316
317void WebSocketBasicStream::OnReadComplete(
318 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
319 int result) {
320 result = HandleReadResult(result, frames);
321 if (result == ERR_IO_PENDING)
322 result = ReadEverything(frames);
323 if (result != ERR_IO_PENDING)
324 std::move(read_callback_).Run(result);
325}
326
[email protected]adb225d2013-08-30 13:14:43327int WebSocketBasicStream::WriteEverything(
Bence Békyf4f56e22018-07-17 02:00:05328 const scoped_refptr<DrainableIOBuffer>& buffer) {
[email protected]adb225d2013-08-30 13:14:43329 while (buffer->BytesRemaining() > 0) {
330 // The use of base::Unretained() here is safe because on destruction we
331 // disconnect the socket, preventing any further callbacks.
Bence Békyf4f56e22018-07-17 02:00:05332 int result = connection_->Write(
333 buffer.get(), buffer->BytesRemaining(),
334 base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
335 base::Unretained(this), buffer),
336 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43337 if (result > 0) {
338 buffer->DidConsume(result);
339 } else {
340 return result;
341 }
342 }
343 return OK;
344}
345
346void WebSocketBasicStream::OnWriteComplete(
347 const scoped_refptr<DrainableIOBuffer>& buffer,
[email protected]adb225d2013-08-30 13:14:43348 int result) {
349 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28350 DCHECK_NE(ERR_IO_PENDING, result);
Bence Békyf4f56e22018-07-17 02:00:05351 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43352 return;
353 }
354
[email protected]2f5d9f62013-09-26 12:14:28355 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00356
[email protected]adb225d2013-08-30 13:14:43357 buffer->DidConsume(result);
Bence Békyf4f56e22018-07-17 02:00:05358 result = WriteEverything(buffer);
[email protected]adb225d2013-08-30 13:14:43359 if (result != ERR_IO_PENDING)
Bence Békyf4f56e22018-07-17 02:00:05360 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43361}
362
363int WebSocketBasicStream::HandleReadResult(
364 int result,
danakj9c5cab52016-04-16 00:54:33365 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43366 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28367 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43368 if (result < 0)
369 return result;
370 if (result == 0)
371 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00372
Nanami Mikiya292e4912022-01-24 06:37:05373 buffer_size_manager_.OnReadComplete(base::TimeTicks::Now(), result);
Nanami Mikiyac78894c2022-01-18 11:32:10374
danakj9c5cab52016-04-16 00:54:33375 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28376 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43377 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28378 if (frame_chunks.empty())
379 return ERR_IO_PENDING;
380 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43381}
382
[email protected]2f5d9f62013-09-26 12:14:28383int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33384 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
385 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28386 for (size_t i = 0; i < frame_chunks->size(); ++i) {
Yutaka Hirano76aacb202019-09-05 16:36:56387 auto& chunk = (*frame_chunks)[i];
388 DCHECK(chunk == frame_chunks->back() || chunk->final_chunk)
389 << "Only last chunk can have |final_chunk| set to be false.";
Nanami Mikiyaeedf2722022-02-03 04:12:13390 if (const auto& header = chunk->header) {
391 net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_RECV_FRAME_HEADER,
392 [&] { return NetLogFrameHeaderParam(header.get()); });
393 }
danakj9c5cab52016-04-16 00:54:33394 std::unique_ptr<WebSocketFrame> frame;
Yutaka Hirano76aacb202019-09-05 16:36:56395 int result = ConvertChunkToFrame(std::move(chunk), &frame);
[email protected]2f5d9f62013-09-26 12:14:28396 if (result != OK)
397 return result;
398 if (frame)
dchengc7eeda422015-12-26 03:56:48399 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28400 }
yhirano592ff7f2015-12-07 08:45:19401 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28402 if (frames->empty())
403 return ERR_IO_PENDING;
404 return OK;
405}
406
407int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33408 std::unique_ptr<WebSocketFrameChunk> chunk,
409 std::unique_ptr<WebSocketFrame>* frame) {
Raul Tambre94493c652019-03-11 17:18:35410 DCHECK(frame->get() == nullptr);
[email protected]2f5d9f62013-09-26 12:14:28411 bool is_first_chunk = false;
412 if (chunk->header) {
Raul Tambre94493c652019-03-11 17:18:35413 DCHECK(current_frame_header_ == nullptr)
[email protected]2f5d9f62013-09-26 12:14:28414 << "Received the header for a new frame without notification that "
415 << "the previous frame was complete (bug in WebSocketFrameParser?)";
416 is_first_chunk = true;
417 current_frame_header_.swap(chunk->header);
418 }
[email protected]2f5d9f62013-09-26 12:14:28419 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
420 << "(final_chunk = " << chunk->final_chunk
Yoichi Osato05cd3642019-09-09 18:13:08421 << ", payload size = " << chunk->payload.size()
[email protected]2f5d9f62013-09-26 12:14:28422 << ") (bug in WebSocketFrameParser?)";
[email protected]2f5d9f62013-09-26 12:14:28423 const bool is_final_chunk = chunk->final_chunk;
424 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
425 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
426 bool protocol_error = false;
427 if (!current_frame_header_->final) {
428 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
429 << " received with FIN bit unset.";
430 protocol_error = true;
431 }
432 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
433 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
434 << ", payload_length=" << current_frame_header_->payload_length
435 << " exceeds maximum payload length for a control message.";
436 protocol_error = true;
437 }
438 if (protocol_error) {
439 current_frame_header_.reset();
440 return ERR_WS_PROTOCOL_ERROR;
441 }
Yutaka Hirano76aacb202019-09-05 16:36:56442
[email protected]2f5d9f62013-09-26 12:14:28443 if (!is_final_chunk) {
444 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08445 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28446 return OK;
447 }
Yutaka Hirano76aacb202019-09-05 16:36:56448
449 if (!incomplete_control_frame_body_.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28450 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08451 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28452 DCHECK(is_final_chunk);
Yutaka Hirano76aacb202019-09-05 16:36:56453 DCHECK(complete_control_frame_body_.empty());
454 complete_control_frame_body_ = std::move(incomplete_control_frame_body_);
455 *frame = CreateFrame(is_final_chunk, complete_control_frame_body_);
[email protected]2f5d9f62013-09-26 12:14:28456 return OK;
457 }
458 }
459
460 // Apply basic sanity checks to the |payload_length| field from the frame
461 // header. A check for exact equality can only be used when the whole frame
462 // arrives in one chunk.
463 DCHECK_GE(current_frame_header_->payload_length,
Yoichi Osato05cd3642019-09-09 18:13:08464 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28465 DCHECK(!is_first_chunk || !is_final_chunk ||
466 current_frame_header_->payload_length ==
Yoichi Osato05cd3642019-09-09 18:13:08467 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28468
469 // Convert the chunk to a complete frame.
Yoichi Osato05cd3642019-09-09 18:13:08470 *frame = CreateFrame(is_final_chunk, chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28471 return OK;
472}
473
danakj9c5cab52016-04-16 00:54:33474std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28475 bool is_final_chunk,
Yutaka Hirano76aacb202019-09-05 16:36:56476 base::span<const char> data) {
danakj9c5cab52016-04-16 00:54:33477 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28478 const bool is_final_chunk_in_message =
479 is_final_chunk && current_frame_header_->final;
[email protected]2f5d9f62013-09-26 12:14:28480 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55481 // Empty frames convey no useful information unless they are the first frame
482 // (containing the type and flags) or have the "final" bit set.
Yutaka Hirano76aacb202019-09-05 16:36:56483 if (is_final_chunk_in_message || data.size() > 0 ||
[email protected]e678d4fe2013-10-11 11:27:55484 current_frame_header_->opcode !=
485 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56486 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28487 result_frame->header.CopyFrom(*current_frame_header_);
488 result_frame->header.final = is_final_chunk_in_message;
Yutaka Hirano76aacb202019-09-05 16:36:56489 result_frame->header.payload_length = data.size();
Yoichi Osato05cd3642019-09-09 18:13:08490 result_frame->payload = data.data();
[email protected]2f5d9f62013-09-26 12:14:28491 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47492 // the message. Also clear the reserved bits.
493 // TODO(ricea): If a future extension requires the reserved bits to be
494 // retained on continuation frames, make this behaviour conditional on a
495 // flag set at construction time.
496 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28497 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47498 current_frame_header_->reserved1 = false;
499 current_frame_header_->reserved2 = false;
500 current_frame_header_->reserved3 = false;
501 }
[email protected]2f5d9f62013-09-26 12:14:28502 }
503 // Make sure that a frame header is not applied to any chunks that do not
504 // belong to it.
505 if (is_final_chunk)
506 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48507 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28508}
509
510void WebSocketBasicStream::AddToIncompleteControlFrameBody(
Yutaka Hirano76aacb202019-09-05 16:36:56511 base::span<const char> data) {
512 if (data.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28513 return;
Yutaka Hirano76aacb202019-09-05 16:36:56514 }
515 incomplete_control_frame_body_.insert(incomplete_control_frame_body_.end(),
516 data.begin(), data.end());
517 // This method checks for oversize control frames above, so as long as
518 // the frame parser is working correctly, this won't overflow. If a bug
519 // does cause it to overflow, it will CHECK() in
520 // AddToIncompleteControlFrameBody() without writing outside the buffer.
521 CHECK_LE(incomplete_control_frame_body_.size(), kMaxControlFramePayload)
[email protected]2f5d9f62013-09-26 12:14:28522 << "Control frame body larger than frame header indicates; frame parser "
523 "bug?";
[email protected]2f5d9f62013-09-26 12:14:28524}
525
[email protected]adb225d2013-08-30 13:14:43526} // namespace net