blob: ef26145f0fe6983bb663a0b4f398262b6ac11884 [file] [log] [blame]
Avi Drissman64595482022-09-14 20:52:291// Copyright 2013 The Chromium Authors
[email protected]adb225d2013-08-30 13:14:432// 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>
Peter Kasting017c1ba2022-10-28 15:26:339
[email protected]adb225d2013-08-30 13:14:4310#include <algorithm>
11#include <limits>
yhirano592ff7f2015-12-07 08:45:1912#include <utility>
[email protected]adb225d2013-08-30 13:14:4313
Avi Drissman41c4a412023-01-11 22:45:3714#include "base/functional/bind.h"
[email protected]adb225d2013-08-30 13:14:4315#include "base/logging.h"
[email protected]cb154062014-01-17 03:32:4016#include "base/numerics/safe_conversions.h"
Yoichi Osato13f94a762019-09-09 09:47:3517#include "build/build_config.h"
[email protected]adb225d2013-08-30 13:14:4318#include "net/base/io_buffer.h"
19#include "net/base/net_errors.h"
20#include "net/socket/client_socket_handle.h"
Bence Béky7294fc22018-02-08 14:26:1721#include "net/websockets/websocket_basic_stream_adapters.h"
[email protected]adb225d2013-08-30 13:14:4322#include "net/websockets/websocket_errors.h"
23#include "net/websockets/websocket_frame.h"
[email protected]adb225d2013-08-30 13:14:4324
25namespace net {
26
27namespace {
28
Ramin Halavaticdb199a62018-01-25 12:38:1929// Please refer to the comment in class header if the usage changes.
30constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
31 net::DefineNetworkTrafficAnnotation("websocket_basic_stream", R"(
32 semantics {
33 sender: "WebSocket Basic Stream"
34 description:
35 "Implementation of WebSocket API from web content (a page the user "
36 "visits)."
37 trigger: "Website calls the WebSocket API."
38 data:
39 "Any data provided by web content, masked and framed in accordance "
40 "with RFC6455."
41 destination: OTHER
42 destination_other:
43 "The address that the website has chosen to communicate to."
44 }
45 policy {
46 cookies_allowed: YES
47 cookies_store: "user"
48 setting: "These requests cannot be disabled."
49 policy_exception_justification:
50 "Not implemented. WebSocket is a core web platform API."
51 }
52 comments:
53 "The browser will never add cookies to a WebSocket message. But the "
54 "handshake that was performed when the WebSocket connection was "
55 "established may have contained cookies."
56 )");
57
tfarina8a2c66c22015-10-13 19:14:4958// This uses type uint64_t to match the definition of
[email protected]2f5d9f62013-09-26 12:14:2859// WebSocketFrameHeader::payload_length in websocket_frame.h.
Adam Ricee77e5b7d2020-08-31 23:31:0960constexpr uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2861
Nanami Mikiya292e4912022-01-24 06:37:0562// The number of bytes to attempt to read at a time. It's used only for high
63// throughput connections.
[email protected]adb225d2013-08-30 13:14:4364// 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.
Xiaohan Wang2a6845b2022-01-08 04:40:5773#if BUILDFLAG(IS_ANDROID)
Nanami Mikiyac78894c2022-01-18 11:32:1074constexpr size_t kLargeReadBufferSize = 32 * 1024;
Yoichi Osato13f94a762019-09-09 09:47:3575#else
Yoichi Osatoba82cef2019-09-10 04:16:0576// |2^n - delta| is better than 2^n on Linux. See crrev.com/c/1792208.
Nanami Mikiyac78894c2022-01-18 11:32:1077constexpr size_t kLargeReadBufferSize = 131000;
Yoichi Osato13f94a762019-09-09 09:47:3578#endif
[email protected]adb225d2013-08-30 13:14:4379
Nanami Mikiya292e4912022-01-24 06:37:0580// The number of bytes to attempt to read at a time. It's set as an initial read
81// buffer size and used for low throughput connections.
82constexpr size_t kSmallReadBufferSize = 1000;
83
Nanami Mikiyac78894c2022-01-18 11:32:1084// The threshold to decide whether to switch the read buffer size.
85constexpr double kThresholdInBytesPerSecond = 1200 * 1000;
86
[email protected]9576544a2013-10-11 08:36:3387// Returns the total serialized size of |frames|. This function assumes that
88// |frames| will be serialized with mask field. This function forces the
89// masked bit of the frames on.
90int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3391 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4992 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3393
tfarina8a2c66c22015-10-13 19:14:4994 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1995 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3396 // Force the masked bit on.
97 frame->header.masked = true;
98 // We enforce flow control so the renderer should never be able to force us
99 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:49100 uint64_t frame_size = frame->header.payload_length +
101 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:34102 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:33103 << "Aborting to prevent overflow";
104 total_size += frame_size;
105 }
pkasting4bff6be2014-10-15 17:54:34106 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:33107}
108
Nanami Mikiyad6b837e2022-02-01 05:58:57109base::Value NetLogBufferSizeParam(int buffer_size) {
Travis Skareadae7ff2022-07-27 16:23:33110 base::Value::Dict dict;
111 dict.Set("read_buffer_size_in_bytes", buffer_size);
112 return base::Value(std::move(dict));
Nanami Mikiyad6b837e2022-02-01 05:58:57113}
114
Nanami Mikiyaeedf2722022-02-03 04:12:13115base::Value NetLogFrameHeaderParam(const WebSocketFrameHeader* header) {
Travis Skareadae7ff2022-07-27 16:23:33116 base::Value::Dict dict;
117 dict.Set("final", header->final);
118 dict.Set("reserved1", header->reserved1);
119 dict.Set("reserved2", header->reserved2);
120 dict.Set("reserved3", header->reserved3);
121 dict.Set("opcode", header->opcode);
122 dict.Set("masked", header->masked);
123 dict.Set("payload_length", static_cast<double>(header->payload_length));
124 return base::Value(std::move(dict));
Nanami Mikiyaeedf2722022-02-03 04:12:13125}
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) {
Nanami Mikiya9d44a6b2022-02-04 03:40:19212 net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_SENT_FRAME_HEADER,
213 [&] { return NetLogFrameHeaderParam(&frame->header); });
[email protected]adb225d2013-08-30 13:14:43214 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28215 int result =
216 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
217 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43218 << "WriteWebSocketFrameHeader() says that " << remaining_size
219 << " is not enough to write the header in. This should not happen.";
220 CHECK_GE(result, 0) << "Potentially security-critical check failed";
221 dest += result;
222 remaining_size -= result;
223
tfarina8a2c66c22015-10-13 19:14:49224 CHECK_LE(frame->header.payload_length,
225 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34226 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44227 if (frame_size > 0) {
Yoichi Osato05cd3642019-09-09 18:13:08228 const char* const frame_data = frame->payload;
[email protected]403ee6e2014-01-27 10:10:44229 std::copy(frame_data, frame_data + frame_size, dest);
230 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
231 dest += frame_size;
232 remaining_size -= frame_size;
233 }
[email protected]adb225d2013-08-30 13:14:43234 }
235 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
236 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56237 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
Nanami Mikiyaf9e4f4cf2021-11-25 07:30:13238 std::move(combined_buffer), total_size);
Bence Békyf4f56e22018-07-17 02:00:05239 return WriteEverything(drainable_buffer);
[email protected]adb225d2013-08-30 13:14:43240}
241
Bence Béky7294fc22018-02-08 14:26:17242void WebSocketBasicStream::Close() {
243 connection_->Disconnect();
244}
[email protected]adb225d2013-08-30 13:14:43245
246std::string WebSocketBasicStream::GetSubProtocol() const {
247 return sub_protocol_;
248}
249
250std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
251
Nanami Mikiyaab5e17d2022-02-07 07:39:42252const NetLogWithSource& WebSocketBasicStream::GetNetLogWithSource() const {
253 return net_log_;
254}
255
[email protected]adb225d2013-08-30 13:14:43256/*static*/
danakj9c5cab52016-04-16 00:54:33257std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43258WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33259 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43260 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
261 const std::string& sub_protocol,
262 const std::string& extensions,
Nanami Mikiyad6b837e2022-02-01 05:58:57263 const NetLogWithSource& net_log,
[email protected]adb225d2013-08-30 13:14:43264 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17265 auto stream = std::make_unique<WebSocketBasicStream>(
266 std::make_unique<WebSocketClientSocketHandleAdapter>(
267 std::move(connection)),
Nanami Mikiyad6b837e2022-02-01 05:58:57268 http_read_buffer, sub_protocol, extensions, net_log);
[email protected]adb225d2013-08-30 13:14:43269 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48270 return stream;
[email protected]adb225d2013-08-30 13:14:43271}
272
Bence Békyf4f56e22018-07-17 02:00:05273int WebSocketBasicStream::ReadEverything(
274 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
275 DCHECK(frames->empty());
276
277 // If there is data left over after parsing the HTTP headers, attempt to parse
278 // it as WebSocket frames.
Yutaka Hirano76aacb202019-09-05 16:36:56279 if (http_read_buffer_.get() && !is_http_read_buffer_decoded_) {
Bence Békyf4f56e22018-07-17 02:00:05280 DCHECK_GE(http_read_buffer_->offset(), 0);
Yutaka Hirano76aacb202019-09-05 16:36:56281 is_http_read_buffer_decoded_ = true;
Bence Békyf4f56e22018-07-17 02:00:05282 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
Yutaka Hirano76aacb202019-09-05 16:36:56283 if (!parser_.Decode(http_read_buffer_->StartOfBuffer(),
284 http_read_buffer_->offset(), &frame_chunks))
Bence Békyf4f56e22018-07-17 02:00:05285 return WebSocketErrorToNetError(parser_.websocket_error());
286 if (!frame_chunks.empty()) {
287 int result = ConvertChunksToFrames(&frame_chunks, frames);
288 if (result != ERR_IO_PENDING)
289 return result;
290 }
291 }
292
293 // Run until socket stops giving us data or we get some frames.
294 while (true) {
Nanami Mikiya292e4912022-01-24 06:37:05295 if (buffer_size_manager_.buffer_size() != buffer_size_) {
296 read_buffer_ = base::MakeRefCounted<IOBufferWithSize>(
297 buffer_size_manager_.buffer_size() == BufferSize::kSmall
298 ? kSmallReadBufferSize
299 : kLargeReadBufferSize);
Nanami Mikiyae8539612022-01-31 03:21:24300 buffer_size_ = buffer_size_manager_.buffer_size();
Nanami Mikiyad6b837e2022-02-01 05:58:57301 net_log_.AddEvent(
302 net::NetLogEventType::WEBSOCKET_READ_BUFFER_SIZE_CHANGED,
303 [&] { return NetLogBufferSizeParam(read_buffer_->size()); });
Nanami Mikiyac78894c2022-01-18 11:32:10304 }
Nanami Mikiya292e4912022-01-24 06:37:05305 buffer_size_manager_.OnRead(base::TimeTicks::Now());
Nanami Mikiyac78894c2022-01-18 11:32:10306
Bence Békyf4f56e22018-07-17 02:00:05307 // base::Unretained(this) here is safe because net::Socket guarantees not to
308 // call any callbacks after Disconnect(), which we call from the destructor.
309 // The caller of ReadEverything() is required to keep |frames| valid.
310 int result = connection_->Read(
311 read_buffer_.get(), read_buffer_->size(),
312 base::BindOnce(&WebSocketBasicStream::OnReadComplete,
313 base::Unretained(this), base::Unretained(frames)));
314 if (result == ERR_IO_PENDING)
315 return result;
316 result = HandleReadResult(result, frames);
317 if (result != ERR_IO_PENDING)
318 return result;
319 DCHECK(frames->empty());
320 }
321}
322
323void WebSocketBasicStream::OnReadComplete(
324 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
325 int result) {
326 result = HandleReadResult(result, frames);
327 if (result == ERR_IO_PENDING)
328 result = ReadEverything(frames);
329 if (result != ERR_IO_PENDING)
330 std::move(read_callback_).Run(result);
331}
332
[email protected]adb225d2013-08-30 13:14:43333int WebSocketBasicStream::WriteEverything(
Bence Békyf4f56e22018-07-17 02:00:05334 const scoped_refptr<DrainableIOBuffer>& buffer) {
[email protected]adb225d2013-08-30 13:14:43335 while (buffer->BytesRemaining() > 0) {
336 // The use of base::Unretained() here is safe because on destruction we
337 // disconnect the socket, preventing any further callbacks.
Bence Békyf4f56e22018-07-17 02:00:05338 int result = connection_->Write(
339 buffer.get(), buffer->BytesRemaining(),
340 base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
341 base::Unretained(this), buffer),
342 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43343 if (result > 0) {
344 buffer->DidConsume(result);
345 } else {
346 return result;
347 }
348 }
349 return OK;
350}
351
352void WebSocketBasicStream::OnWriteComplete(
353 const scoped_refptr<DrainableIOBuffer>& buffer,
[email protected]adb225d2013-08-30 13:14:43354 int result) {
355 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28356 DCHECK_NE(ERR_IO_PENDING, result);
Bence Békyf4f56e22018-07-17 02:00:05357 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43358 return;
359 }
360
[email protected]2f5d9f62013-09-26 12:14:28361 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00362
[email protected]adb225d2013-08-30 13:14:43363 buffer->DidConsume(result);
Bence Békyf4f56e22018-07-17 02:00:05364 result = WriteEverything(buffer);
[email protected]adb225d2013-08-30 13:14:43365 if (result != ERR_IO_PENDING)
Bence Békyf4f56e22018-07-17 02:00:05366 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43367}
368
369int WebSocketBasicStream::HandleReadResult(
370 int result,
danakj9c5cab52016-04-16 00:54:33371 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43372 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28373 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43374 if (result < 0)
375 return result;
376 if (result == 0)
377 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00378
Nanami Mikiya292e4912022-01-24 06:37:05379 buffer_size_manager_.OnReadComplete(base::TimeTicks::Now(), result);
Nanami Mikiyac78894c2022-01-18 11:32:10380
danakj9c5cab52016-04-16 00:54:33381 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28382 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43383 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28384 if (frame_chunks.empty())
385 return ERR_IO_PENDING;
386 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43387}
388
[email protected]2f5d9f62013-09-26 12:14:28389int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33390 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
391 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28392 for (size_t i = 0; i < frame_chunks->size(); ++i) {
Yutaka Hirano76aacb202019-09-05 16:36:56393 auto& chunk = (*frame_chunks)[i];
394 DCHECK(chunk == frame_chunks->back() || chunk->final_chunk)
395 << "Only last chunk can have |final_chunk| set to be false.";
Nanami Mikiyaeedf2722022-02-03 04:12:13396 if (const auto& header = chunk->header) {
397 net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_RECV_FRAME_HEADER,
398 [&] { return NetLogFrameHeaderParam(header.get()); });
399 }
danakj9c5cab52016-04-16 00:54:33400 std::unique_ptr<WebSocketFrame> frame;
Yutaka Hirano76aacb202019-09-05 16:36:56401 int result = ConvertChunkToFrame(std::move(chunk), &frame);
[email protected]2f5d9f62013-09-26 12:14:28402 if (result != OK)
403 return result;
404 if (frame)
dchengc7eeda422015-12-26 03:56:48405 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28406 }
yhirano592ff7f2015-12-07 08:45:19407 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28408 if (frames->empty())
409 return ERR_IO_PENDING;
410 return OK;
411}
412
413int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33414 std::unique_ptr<WebSocketFrameChunk> chunk,
415 std::unique_ptr<WebSocketFrame>* frame) {
Raul Tambre94493c652019-03-11 17:18:35416 DCHECK(frame->get() == nullptr);
[email protected]2f5d9f62013-09-26 12:14:28417 bool is_first_chunk = false;
418 if (chunk->header) {
Raul Tambre94493c652019-03-11 17:18:35419 DCHECK(current_frame_header_ == nullptr)
[email protected]2f5d9f62013-09-26 12:14:28420 << "Received the header for a new frame without notification that "
421 << "the previous frame was complete (bug in WebSocketFrameParser?)";
422 is_first_chunk = true;
423 current_frame_header_.swap(chunk->header);
424 }
[email protected]2f5d9f62013-09-26 12:14:28425 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
426 << "(final_chunk = " << chunk->final_chunk
Yoichi Osato05cd3642019-09-09 18:13:08427 << ", payload size = " << chunk->payload.size()
[email protected]2f5d9f62013-09-26 12:14:28428 << ") (bug in WebSocketFrameParser?)";
[email protected]2f5d9f62013-09-26 12:14:28429 const bool is_final_chunk = chunk->final_chunk;
430 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
431 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
432 bool protocol_error = false;
433 if (!current_frame_header_->final) {
434 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
435 << " received with FIN bit unset.";
436 protocol_error = true;
437 }
438 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
439 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
440 << ", payload_length=" << current_frame_header_->payload_length
441 << " exceeds maximum payload length for a control message.";
442 protocol_error = true;
443 }
444 if (protocol_error) {
445 current_frame_header_.reset();
446 return ERR_WS_PROTOCOL_ERROR;
447 }
Yutaka Hirano76aacb202019-09-05 16:36:56448
[email protected]2f5d9f62013-09-26 12:14:28449 if (!is_final_chunk) {
450 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08451 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28452 return OK;
453 }
Yutaka Hirano76aacb202019-09-05 16:36:56454
455 if (!incomplete_control_frame_body_.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28456 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08457 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28458 DCHECK(is_final_chunk);
Yutaka Hirano76aacb202019-09-05 16:36:56459 DCHECK(complete_control_frame_body_.empty());
460 complete_control_frame_body_ = std::move(incomplete_control_frame_body_);
461 *frame = CreateFrame(is_final_chunk, complete_control_frame_body_);
[email protected]2f5d9f62013-09-26 12:14:28462 return OK;
463 }
464 }
465
466 // Apply basic sanity checks to the |payload_length| field from the frame
467 // header. A check for exact equality can only be used when the whole frame
468 // arrives in one chunk.
469 DCHECK_GE(current_frame_header_->payload_length,
Yoichi Osato05cd3642019-09-09 18:13:08470 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28471 DCHECK(!is_first_chunk || !is_final_chunk ||
472 current_frame_header_->payload_length ==
Yoichi Osato05cd3642019-09-09 18:13:08473 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28474
475 // Convert the chunk to a complete frame.
Yoichi Osato05cd3642019-09-09 18:13:08476 *frame = CreateFrame(is_final_chunk, chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28477 return OK;
478}
479
danakj9c5cab52016-04-16 00:54:33480std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28481 bool is_final_chunk,
Yutaka Hirano76aacb202019-09-05 16:36:56482 base::span<const char> data) {
danakj9c5cab52016-04-16 00:54:33483 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28484 const bool is_final_chunk_in_message =
485 is_final_chunk && current_frame_header_->final;
[email protected]2f5d9f62013-09-26 12:14:28486 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55487 // Empty frames convey no useful information unless they are the first frame
488 // (containing the type and flags) or have the "final" bit set.
Yutaka Hirano76aacb202019-09-05 16:36:56489 if (is_final_chunk_in_message || data.size() > 0 ||
[email protected]e678d4fe2013-10-11 11:27:55490 current_frame_header_->opcode !=
491 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56492 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28493 result_frame->header.CopyFrom(*current_frame_header_);
494 result_frame->header.final = is_final_chunk_in_message;
Yutaka Hirano76aacb202019-09-05 16:36:56495 result_frame->header.payload_length = data.size();
Yoichi Osato05cd3642019-09-09 18:13:08496 result_frame->payload = data.data();
[email protected]2f5d9f62013-09-26 12:14:28497 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47498 // the message. Also clear the reserved bits.
499 // TODO(ricea): If a future extension requires the reserved bits to be
500 // retained on continuation frames, make this behaviour conditional on a
501 // flag set at construction time.
502 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28503 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47504 current_frame_header_->reserved1 = false;
505 current_frame_header_->reserved2 = false;
506 current_frame_header_->reserved3 = false;
507 }
[email protected]2f5d9f62013-09-26 12:14:28508 }
509 // Make sure that a frame header is not applied to any chunks that do not
510 // belong to it.
511 if (is_final_chunk)
512 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48513 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28514}
515
516void WebSocketBasicStream::AddToIncompleteControlFrameBody(
Yutaka Hirano76aacb202019-09-05 16:36:56517 base::span<const char> data) {
518 if (data.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28519 return;
Yutaka Hirano76aacb202019-09-05 16:36:56520 }
521 incomplete_control_frame_body_.insert(incomplete_control_frame_body_.end(),
522 data.begin(), data.end());
523 // This method checks for oversize control frames above, so as long as
524 // the frame parser is working correctly, this won't overflow. If a bug
525 // does cause it to overflow, it will CHECK() in
526 // AddToIncompleteControlFrameBody() without writing outside the buffer.
527 CHECK_LE(incomplete_control_frame_body_.size(), kMaxControlFramePayload)
[email protected]2f5d9f62013-09-26 12:14:28528 << "Control frame body larger than frame header indicates; frame parser "
529 "bug?";
[email protected]2f5d9f62013-09-26 12:14:28530}
531
[email protected]adb225d2013-08-30 13:14:43532} // namespace net