blob: 8140b0c52a69407cfe923252540d457644a256d4 [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
Yoichi Osatoba82cef2019-09-10 04:16:0577// |2^n - delta| is better than 2^n on Linux. See crrev.com/c/1792208.
Yoichi Osato13f94a762019-09-09 09:47:3578const int kReadBufferSize = 131000;
79#endif
[email protected]adb225d2013-08-30 13:14:4380
[email protected]9576544a2013-10-11 08:36:3381// Returns the total serialized size of |frames|. This function assumes that
82// |frames| will be serialized with mask field. This function forces the
83// masked bit of the frames on.
84int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3385 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4986 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3387
tfarina8a2c66c22015-10-13 19:14:4988 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1989 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3390 // Force the masked bit on.
91 frame->header.masked = true;
92 // We enforce flow control so the renderer should never be able to force us
93 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4994 uint64_t frame_size = frame->header.payload_length +
95 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:3496 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:3397 << "Aborting to prevent overflow";
98 total_size += frame_size;
99 }
pkasting4bff6be2014-10-15 17:54:34100 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:33101}
102
[email protected]adb225d2013-08-30 13:14:43103} // namespace
104
Yoichi Osato14073bd2019-06-04 11:06:37105// Overrides default read buffer size for WebSocket. This flag will be used to
106// investigate the performance issue of crbug.com/865001 and be deleted later
107// on.
108const char kWebSocketReadBufferSize[] = "websocket-read-buffer-size";
109
[email protected]adb225d2013-08-30 13:14:43110WebSocketBasicStream::WebSocketBasicStream(
Bence Béky7294fc22018-02-08 14:26:17111 std::unique_ptr<Adapter> connection,
[email protected]86602d3f2013-11-06 00:08:22112 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
113 const std::string& sub_protocol,
114 const std::string& extensions)
Yoichi Osato14073bd2019-06-04 11:06:37115 : connection_(std::move(connection)),
[email protected]86602d3f2013-11-06 00:08:22116 http_read_buffer_(http_read_buffer),
117 sub_protocol_(sub_protocol),
118 extensions_(extensions),
[email protected]adb225d2013-08-30 13:14:43119 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:36120 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:23121 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
Raul Tambre94493c652019-03-11 17:18:35122 http_read_buffer_ = nullptr;
[email protected]adb225d2013-08-30 13:14:43123 DCHECK(connection_->is_initialized());
Yoichi Osato14073bd2019-06-04 11:06:37124 base::CommandLine* const command_line =
125 base::CommandLine::ForCurrentProcess();
126 DCHECK(command_line);
127 int websocket_buffer_size = kReadBufferSize;
128 if (command_line->HasSwitch(kWebSocketReadBufferSize)) {
129 std::string size_string =
130 command_line->GetSwitchValueASCII(kWebSocketReadBufferSize);
131 if (!base::StringToInt(size_string, &websocket_buffer_size) ||
132 websocket_buffer_size <= 0) {
133 websocket_buffer_size = kReadBufferSize;
134 }
135 }
136 DVLOG(1) << "WebSocketReadBufferSize is " << websocket_buffer_size;
137 read_buffer_ =
138 (base::MakeRefCounted<IOBufferWithSize>(websocket_buffer_size));
[email protected]adb225d2013-08-30 13:14:43139}
140
141WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
142
yhirano592ff7f2015-12-07 08:45:19143int WebSocketBasicStream::ReadFrames(
danakj9c5cab52016-04-16 00:54:33144 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05145 CompletionOnceCallback callback) {
146 read_callback_ = std::move(callback);
Yutaka Hirano76aacb202019-09-05 16:36:56147 complete_control_frame_body_.clear();
148 if (http_read_buffer_ && is_http_read_buffer_decoded_) {
149 http_read_buffer_.reset();
150 }
Bence Békyf4f56e22018-07-17 02:00:05151 return ReadEverything(frames);
[email protected]adb225d2013-08-30 13:14:43152}
153
yhirano592ff7f2015-12-07 08:45:19154int WebSocketBasicStream::WriteFrames(
danakj9c5cab52016-04-16 00:54:33155 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
Bence Békyf4f56e22018-07-17 02:00:05156 CompletionOnceCallback callback) {
[email protected]adb225d2013-08-30 13:14:43157 // This function always concatenates all frames into a single buffer.
158 // TODO(ricea): Investigate whether it would be better in some cases to
159 // perform multiple writes with smaller buffers.
Bence Békyf4f56e22018-07-17 02:00:05160
161 write_callback_ = std::move(callback);
162
[email protected]adb225d2013-08-30 13:14:43163 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33164 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
Bence Béky65623972018-03-05 15:31:56165 auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
[email protected]9576544a2013-10-11 08:36:33166
[email protected]adb225d2013-08-30 13:14:43167 char* dest = combined_buffer->data();
168 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19169 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43170 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28171 int result =
172 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
173 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43174 << "WriteWebSocketFrameHeader() says that " << remaining_size
175 << " is not enough to write the header in. This should not happen.";
176 CHECK_GE(result, 0) << "Potentially security-critical check failed";
177 dest += result;
178 remaining_size -= result;
179
tfarina8a2c66c22015-10-13 19:14:49180 CHECK_LE(frame->header.payload_length,
181 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34182 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44183 if (frame_size > 0) {
Yoichi Osato05cd3642019-09-09 18:13:08184 const char* const frame_data = frame->payload;
[email protected]403ee6e2014-01-27 10:10:44185 std::copy(frame_data, frame_data + frame_size, dest);
186 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
187 dest += frame_size;
188 remaining_size -= frame_size;
189 }
[email protected]adb225d2013-08-30 13:14:43190 }
191 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
192 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56193 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
194 combined_buffer.get(), total_size);
Bence Békyf4f56e22018-07-17 02:00:05195 return WriteEverything(drainable_buffer);
[email protected]adb225d2013-08-30 13:14:43196}
197
Bence Béky7294fc22018-02-08 14:26:17198void WebSocketBasicStream::Close() {
199 connection_->Disconnect();
200}
[email protected]adb225d2013-08-30 13:14:43201
202std::string WebSocketBasicStream::GetSubProtocol() const {
203 return sub_protocol_;
204}
205
206std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
207
[email protected]adb225d2013-08-30 13:14:43208/*static*/
danakj9c5cab52016-04-16 00:54:33209std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43210WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33211 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43212 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
213 const std::string& sub_protocol,
214 const std::string& extensions,
215 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17216 auto stream = std::make_unique<WebSocketBasicStream>(
217 std::make_unique<WebSocketClientSocketHandleAdapter>(
218 std::move(connection)),
219 http_read_buffer, sub_protocol, extensions);
[email protected]adb225d2013-08-30 13:14:43220 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48221 return stream;
[email protected]adb225d2013-08-30 13:14:43222}
223
Bence Békyf4f56e22018-07-17 02:00:05224int WebSocketBasicStream::ReadEverything(
225 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
226 DCHECK(frames->empty());
227
228 // If there is data left over after parsing the HTTP headers, attempt to parse
229 // it as WebSocket frames.
Yutaka Hirano76aacb202019-09-05 16:36:56230 if (http_read_buffer_.get() && !is_http_read_buffer_decoded_) {
Bence Békyf4f56e22018-07-17 02:00:05231 DCHECK_GE(http_read_buffer_->offset(), 0);
Yutaka Hirano76aacb202019-09-05 16:36:56232 is_http_read_buffer_decoded_ = true;
Bence Békyf4f56e22018-07-17 02:00:05233 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
Yutaka Hirano76aacb202019-09-05 16:36:56234 if (!parser_.Decode(http_read_buffer_->StartOfBuffer(),
235 http_read_buffer_->offset(), &frame_chunks))
Bence Békyf4f56e22018-07-17 02:00:05236 return WebSocketErrorToNetError(parser_.websocket_error());
237 if (!frame_chunks.empty()) {
238 int result = ConvertChunksToFrames(&frame_chunks, frames);
239 if (result != ERR_IO_PENDING)
240 return result;
241 }
242 }
243
244 // Run until socket stops giving us data or we get some frames.
245 while (true) {
246 // base::Unretained(this) here is safe because net::Socket guarantees not to
247 // call any callbacks after Disconnect(), which we call from the destructor.
248 // The caller of ReadEverything() is required to keep |frames| valid.
249 int result = connection_->Read(
250 read_buffer_.get(), read_buffer_->size(),
251 base::BindOnce(&WebSocketBasicStream::OnReadComplete,
252 base::Unretained(this), base::Unretained(frames)));
253 if (result == ERR_IO_PENDING)
254 return result;
255 result = HandleReadResult(result, frames);
256 if (result != ERR_IO_PENDING)
257 return result;
258 DCHECK(frames->empty());
259 }
260}
261
262void WebSocketBasicStream::OnReadComplete(
263 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
264 int result) {
265 result = HandleReadResult(result, frames);
266 if (result == ERR_IO_PENDING)
267 result = ReadEverything(frames);
268 if (result != ERR_IO_PENDING)
269 std::move(read_callback_).Run(result);
270}
271
[email protected]adb225d2013-08-30 13:14:43272int WebSocketBasicStream::WriteEverything(
Bence Békyf4f56e22018-07-17 02:00:05273 const scoped_refptr<DrainableIOBuffer>& buffer) {
[email protected]adb225d2013-08-30 13:14:43274 while (buffer->BytesRemaining() > 0) {
275 // The use of base::Unretained() here is safe because on destruction we
276 // disconnect the socket, preventing any further callbacks.
Bence Békyf4f56e22018-07-17 02:00:05277 int result = connection_->Write(
278 buffer.get(), buffer->BytesRemaining(),
279 base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
280 base::Unretained(this), buffer),
281 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43282 if (result > 0) {
rajendrant75fe34f2017-03-28 05:53:00283 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
[email protected]adb225d2013-08-30 13:14:43284 buffer->DidConsume(result);
285 } else {
286 return result;
287 }
288 }
289 return OK;
290}
291
292void WebSocketBasicStream::OnWriteComplete(
293 const scoped_refptr<DrainableIOBuffer>& buffer,
[email protected]adb225d2013-08-30 13:14:43294 int result) {
295 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28296 DCHECK_NE(ERR_IO_PENDING, result);
Bence Békyf4f56e22018-07-17 02:00:05297 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43298 return;
299 }
300
[email protected]2f5d9f62013-09-26 12:14:28301 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00302 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
303
[email protected]adb225d2013-08-30 13:14:43304 buffer->DidConsume(result);
Bence Békyf4f56e22018-07-17 02:00:05305 result = WriteEverything(buffer);
[email protected]adb225d2013-08-30 13:14:43306 if (result != ERR_IO_PENDING)
Bence Békyf4f56e22018-07-17 02:00:05307 std::move(write_callback_).Run(result);
[email protected]adb225d2013-08-30 13:14:43308}
309
310int WebSocketBasicStream::HandleReadResult(
311 int result,
danakj9c5cab52016-04-16 00:54:33312 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43313 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28314 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43315 if (result < 0)
316 return result;
317 if (result == 0)
318 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00319
320 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Downstream", result);
321
danakj9c5cab52016-04-16 00:54:33322 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28323 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43324 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28325 if (frame_chunks.empty())
326 return ERR_IO_PENDING;
327 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43328}
329
[email protected]2f5d9f62013-09-26 12:14:28330int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33331 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
332 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28333 for (size_t i = 0; i < frame_chunks->size(); ++i) {
Yutaka Hirano76aacb202019-09-05 16:36:56334 auto& chunk = (*frame_chunks)[i];
335 DCHECK(chunk == frame_chunks->back() || chunk->final_chunk)
336 << "Only last chunk can have |final_chunk| set to be false.";
danakj9c5cab52016-04-16 00:54:33337 std::unique_ptr<WebSocketFrame> frame;
Yutaka Hirano76aacb202019-09-05 16:36:56338 int result = ConvertChunkToFrame(std::move(chunk), &frame);
[email protected]2f5d9f62013-09-26 12:14:28339 if (result != OK)
340 return result;
341 if (frame)
dchengc7eeda422015-12-26 03:56:48342 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28343 }
yhirano592ff7f2015-12-07 08:45:19344 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28345 if (frames->empty())
346 return ERR_IO_PENDING;
347 return OK;
348}
349
350int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33351 std::unique_ptr<WebSocketFrameChunk> chunk,
352 std::unique_ptr<WebSocketFrame>* frame) {
Raul Tambre94493c652019-03-11 17:18:35353 DCHECK(frame->get() == nullptr);
[email protected]2f5d9f62013-09-26 12:14:28354 bool is_first_chunk = false;
355 if (chunk->header) {
Raul Tambre94493c652019-03-11 17:18:35356 DCHECK(current_frame_header_ == nullptr)
[email protected]2f5d9f62013-09-26 12:14:28357 << "Received the header for a new frame without notification that "
358 << "the previous frame was complete (bug in WebSocketFrameParser?)";
359 is_first_chunk = true;
360 current_frame_header_.swap(chunk->header);
361 }
[email protected]2f5d9f62013-09-26 12:14:28362 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
363 << "(final_chunk = " << chunk->final_chunk
Yoichi Osato05cd3642019-09-09 18:13:08364 << ", payload size = " << chunk->payload.size()
[email protected]2f5d9f62013-09-26 12:14:28365 << ") (bug in WebSocketFrameParser?)";
[email protected]2f5d9f62013-09-26 12:14:28366 const bool is_final_chunk = chunk->final_chunk;
367 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
368 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
369 bool protocol_error = false;
370 if (!current_frame_header_->final) {
371 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
372 << " received with FIN bit unset.";
373 protocol_error = true;
374 }
375 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
376 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
377 << ", payload_length=" << current_frame_header_->payload_length
378 << " exceeds maximum payload length for a control message.";
379 protocol_error = true;
380 }
381 if (protocol_error) {
382 current_frame_header_.reset();
383 return ERR_WS_PROTOCOL_ERROR;
384 }
Yutaka Hirano76aacb202019-09-05 16:36:56385
[email protected]2f5d9f62013-09-26 12:14:28386 if (!is_final_chunk) {
387 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08388 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28389 return OK;
390 }
Yutaka Hirano76aacb202019-09-05 16:36:56391
392 if (!incomplete_control_frame_body_.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28393 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
Yoichi Osato05cd3642019-09-09 18:13:08394 AddToIncompleteControlFrameBody(chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28395 DCHECK(is_final_chunk);
Yutaka Hirano76aacb202019-09-05 16:36:56396 DCHECK(complete_control_frame_body_.empty());
397 complete_control_frame_body_ = std::move(incomplete_control_frame_body_);
398 *frame = CreateFrame(is_final_chunk, complete_control_frame_body_);
[email protected]2f5d9f62013-09-26 12:14:28399 return OK;
400 }
401 }
402
403 // Apply basic sanity checks to the |payload_length| field from the frame
404 // header. A check for exact equality can only be used when the whole frame
405 // arrives in one chunk.
406 DCHECK_GE(current_frame_header_->payload_length,
Yoichi Osato05cd3642019-09-09 18:13:08407 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28408 DCHECK(!is_first_chunk || !is_final_chunk ||
409 current_frame_header_->payload_length ==
Yoichi Osato05cd3642019-09-09 18:13:08410 base::checked_cast<uint64_t>(chunk->payload.size()));
[email protected]2f5d9f62013-09-26 12:14:28411
412 // Convert the chunk to a complete frame.
Yoichi Osato05cd3642019-09-09 18:13:08413 *frame = CreateFrame(is_final_chunk, chunk->payload);
[email protected]2f5d9f62013-09-26 12:14:28414 return OK;
415}
416
danakj9c5cab52016-04-16 00:54:33417std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28418 bool is_final_chunk,
Yutaka Hirano76aacb202019-09-05 16:36:56419 base::span<const char> data) {
danakj9c5cab52016-04-16 00:54:33420 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28421 const bool is_final_chunk_in_message =
422 is_final_chunk && current_frame_header_->final;
[email protected]2f5d9f62013-09-26 12:14:28423 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55424 // Empty frames convey no useful information unless they are the first frame
425 // (containing the type and flags) or have the "final" bit set.
Yutaka Hirano76aacb202019-09-05 16:36:56426 if (is_final_chunk_in_message || data.size() > 0 ||
[email protected]e678d4fe2013-10-11 11:27:55427 current_frame_header_->opcode !=
428 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56429 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28430 result_frame->header.CopyFrom(*current_frame_header_);
431 result_frame->header.final = is_final_chunk_in_message;
Yutaka Hirano76aacb202019-09-05 16:36:56432 result_frame->header.payload_length = data.size();
Yoichi Osato05cd3642019-09-09 18:13:08433 result_frame->payload = data.data();
[email protected]2f5d9f62013-09-26 12:14:28434 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47435 // the message. Also clear the reserved bits.
436 // TODO(ricea): If a future extension requires the reserved bits to be
437 // retained on continuation frames, make this behaviour conditional on a
438 // flag set at construction time.
439 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28440 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47441 current_frame_header_->reserved1 = false;
442 current_frame_header_->reserved2 = false;
443 current_frame_header_->reserved3 = false;
444 }
[email protected]2f5d9f62013-09-26 12:14:28445 }
446 // Make sure that a frame header is not applied to any chunks that do not
447 // belong to it.
448 if (is_final_chunk)
449 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48450 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28451}
452
453void WebSocketBasicStream::AddToIncompleteControlFrameBody(
Yutaka Hirano76aacb202019-09-05 16:36:56454 base::span<const char> data) {
455 if (data.empty()) {
[email protected]2f5d9f62013-09-26 12:14:28456 return;
Yutaka Hirano76aacb202019-09-05 16:36:56457 }
458 incomplete_control_frame_body_.insert(incomplete_control_frame_body_.end(),
459 data.begin(), data.end());
460 // This method checks for oversize control frames above, so as long as
461 // the frame parser is working correctly, this won't overflow. If a bug
462 // does cause it to overflow, it will CHECK() in
463 // AddToIncompleteControlFrameBody() without writing outside the buffer.
464 CHECK_LE(incomplete_control_frame_body_.size(), kMaxControlFramePayload)
[email protected]2f5d9f62013-09-26 12:14:28465 << "Control frame body larger than frame header indicates; frame parser "
466 "bug?";
[email protected]2f5d9f62013-09-26 12:14:28467}
468
[email protected]adb225d2013-08-30 13:14:43469} // namespace net