blob: 31267ba9a809fd7efd06e5b0148f60a0ade9d531 [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"
rajendrant75fe34f2017-03-28 05:53:0015#include "base/metrics/histogram_macros.h"
[email protected]cb154062014-01-17 03:32:4016#include "base/numerics/safe_conversions.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.
tfarina8a2c66c22015-10-13 19:14:4959const uint64_t kMaxControlFramePayload = 125;
[email protected]2f5d9f62013-09-26 12:14:2860
[email protected]adb225d2013-08-30 13:14:4361// The number of bytes to attempt to read at a time.
62// TODO(ricea): See if there is a better number or algorithm to fulfill our
63// requirements:
64// 1. We would like to use minimal memory on low-bandwidth or idle connections
65// 2. We would like to read as close to line speed as possible on
66// high-bandwidth connections
67// 3. We can't afford to cause jank on the IO thread by copying large buffers
68// around
69// 4. We would like to hit any sweet-spots that might exist in terms of network
70// packet sizes / encryption block sizes / IPC alignment issues, etc.
71const int kReadBufferSize = 32 * 1024;
72
[email protected]9576544a2013-10-11 08:36:3373// Returns the total serialized size of |frames|. This function assumes that
74// |frames| will be serialized with mask field. This function forces the
75// masked bit of the frames on.
76int CalculateSerializedSizeAndTurnOnMaskBit(
danakj9c5cab52016-04-16 00:54:3377 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
tfarina8a2c66c22015-10-13 19:14:4978 const uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
[email protected]9576544a2013-10-11 08:36:3379
tfarina8a2c66c22015-10-13 19:14:4980 uint64_t total_size = 0;
yhirano592ff7f2015-12-07 08:45:1981 for (const auto& frame : *frames) {
[email protected]9576544a2013-10-11 08:36:3382 // Force the masked bit on.
83 frame->header.masked = true;
84 // We enforce flow control so the renderer should never be able to force us
85 // to cache anywhere near 2GB of frames.
tfarina8a2c66c22015-10-13 19:14:4986 uint64_t frame_size = frame->header.payload_length +
87 GetWebSocketFrameHeaderSize(frame->header);
pkasting4bff6be2014-10-15 17:54:3488 CHECK_LE(frame_size, kMaximumTotalSize - total_size)
[email protected]9576544a2013-10-11 08:36:3389 << "Aborting to prevent overflow";
90 total_size += frame_size;
91 }
pkasting4bff6be2014-10-15 17:54:3492 return static_cast<int>(total_size);
[email protected]9576544a2013-10-11 08:36:3393}
94
[email protected]adb225d2013-08-30 13:14:4395} // namespace
96
97WebSocketBasicStream::WebSocketBasicStream(
Bence Béky7294fc22018-02-08 14:26:1798 std::unique_ptr<Adapter> connection,
[email protected]86602d3f2013-11-06 00:08:2299 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
100 const std::string& sub_protocol,
101 const std::string& extensions)
Bence Béky65623972018-03-05 15:31:56102 : read_buffer_(base::MakeRefCounted<IOBufferWithSize>(kReadBufferSize)),
dchengc7eeda422015-12-26 03:56:48103 connection_(std::move(connection)),
[email protected]86602d3f2013-11-06 00:08:22104 http_read_buffer_(http_read_buffer),
105 sub_protocol_(sub_protocol),
106 extensions_(extensions),
[email protected]adb225d2013-08-30 13:14:43107 generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
[email protected]50133d7a2013-11-07 13:08:36108 // http_read_buffer_ should not be set if it contains no data.
dchengb206dc412014-08-26 19:46:23109 if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
[email protected]50133d7a2013-11-07 13:08:36110 http_read_buffer_ = NULL;
[email protected]adb225d2013-08-30 13:14:43111 DCHECK(connection_->is_initialized());
112}
113
114WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
115
yhirano592ff7f2015-12-07 08:45:19116int WebSocketBasicStream::ReadFrames(
danakj9c5cab52016-04-16 00:54:33117 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
yhirano592ff7f2015-12-07 08:45:19118 const CompletionCallback& callback) {
[email protected]2f5d9f62013-09-26 12:14:28119 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43120 // If there is data left over after parsing the HTTP headers, attempt to parse
121 // it as WebSocket frames.
dchengb206dc412014-08-26 19:46:23122 if (http_read_buffer_.get()) {
[email protected]adb225d2013-08-30 13:14:43123 DCHECK_GE(http_read_buffer_->offset(), 0);
124 // We cannot simply copy the data into read_buffer_, as it might be too
125 // large.
126 scoped_refptr<GrowableIOBuffer> buffered_data;
127 buffered_data.swap(http_read_buffer_);
melandory1346cde2016-06-11 00:42:12128 DCHECK(!http_read_buffer_);
danakj9c5cab52016-04-16 00:54:33129 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]adb225d2013-08-30 13:14:43130 if (!parser_.Decode(buffered_data->StartOfBuffer(),
131 buffered_data->offset(),
[email protected]2f5d9f62013-09-26 12:14:28132 &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43133 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28134 if (!frame_chunks.empty()) {
135 int result = ConvertChunksToFrames(&frame_chunks, frames);
136 if (result != ERR_IO_PENDING)
137 return result;
138 }
[email protected]adb225d2013-08-30 13:14:43139 }
140
[email protected]2f5d9f62013-09-26 12:14:28141 // Run until socket stops giving us data or we get some frames.
[email protected]adb225d2013-08-30 13:14:43142 while (true) {
143 // base::Unretained(this) here is safe because net::Socket guarantees not to
144 // call any callbacks after Disconnect(), which we call from the
[email protected]2f5d9f62013-09-26 12:14:28145 // destructor. The caller of ReadFrames() is required to keep |frames|
[email protected]adb225d2013-08-30 13:14:43146 // valid.
Bence Béky7294fc22018-02-08 14:26:17147 int result = connection_->Read(
148 read_buffer_.get(), read_buffer_->size(),
[email protected]2f5d9f62013-09-26 12:14:28149 base::Bind(&WebSocketBasicStream::OnReadComplete,
Bence Béky7294fc22018-02-08 14:26:17150 base::Unretained(this), base::Unretained(frames), callback));
[email protected]adb225d2013-08-30 13:14:43151 if (result == ERR_IO_PENDING)
152 return result;
[email protected]2f5d9f62013-09-26 12:14:28153 result = HandleReadResult(result, frames);
[email protected]adb225d2013-08-30 13:14:43154 if (result != ERR_IO_PENDING)
155 return result;
[email protected]2f5d9f62013-09-26 12:14:28156 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43157 }
158}
159
yhirano592ff7f2015-12-07 08:45:19160int WebSocketBasicStream::WriteFrames(
danakj9c5cab52016-04-16 00:54:33161 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
yhirano592ff7f2015-12-07 08:45:19162 const CompletionCallback& callback) {
[email protected]adb225d2013-08-30 13:14:43163 // This function always concatenates all frames into a single buffer.
164 // TODO(ricea): Investigate whether it would be better in some cases to
165 // perform multiple writes with smaller buffers.
166 //
167 // First calculate the size of the buffer we need to allocate.
[email protected]9576544a2013-10-11 08:36:33168 int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
Bence Béky65623972018-03-05 15:31:56169 auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
[email protected]9576544a2013-10-11 08:36:33170
[email protected]adb225d2013-08-30 13:14:43171 char* dest = combined_buffer->data();
172 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19173 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43174 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28175 int result =
176 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
177 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43178 << "WriteWebSocketFrameHeader() says that " << remaining_size
179 << " is not enough to write the header in. This should not happen.";
180 CHECK_GE(result, 0) << "Potentially security-critical check failed";
181 dest += result;
182 remaining_size -= result;
183
tfarina8a2c66c22015-10-13 19:14:49184 CHECK_LE(frame->header.payload_length,
185 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34186 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44187 if (frame_size > 0) {
[email protected]403ee6e2014-01-27 10:10:44188 const char* const frame_data = frame->data->data();
189 std::copy(frame_data, frame_data + frame_size, dest);
190 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
191 dest += frame_size;
192 remaining_size -= frame_size;
193 }
[email protected]adb225d2013-08-30 13:14:43194 }
195 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
196 << remaining_size << " bytes left over.";
Bence Béky65623972018-03-05 15:31:56197 auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
198 combined_buffer.get(), total_size);
[email protected]adb225d2013-08-30 13:14:43199 return WriteEverything(drainable_buffer, callback);
200}
201
Bence Béky7294fc22018-02-08 14:26:17202void WebSocketBasicStream::Close() {
203 connection_->Disconnect();
204}
[email protected]adb225d2013-08-30 13:14:43205
206std::string WebSocketBasicStream::GetSubProtocol() const {
207 return sub_protocol_;
208}
209
210std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
211
[email protected]adb225d2013-08-30 13:14:43212/*static*/
danakj9c5cab52016-04-16 00:54:33213std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43214WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33215 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43216 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
217 const std::string& sub_protocol,
218 const std::string& extensions,
219 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17220 auto stream = std::make_unique<WebSocketBasicStream>(
221 std::make_unique<WebSocketClientSocketHandleAdapter>(
222 std::move(connection)),
223 http_read_buffer, sub_protocol, extensions);
[email protected]adb225d2013-08-30 13:14:43224 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48225 return stream;
[email protected]adb225d2013-08-30 13:14:43226}
227
228int WebSocketBasicStream::WriteEverything(
229 const scoped_refptr<DrainableIOBuffer>& buffer,
230 const CompletionCallback& callback) {
231 while (buffer->BytesRemaining() > 0) {
232 // The use of base::Unretained() here is safe because on destruction we
233 // disconnect the socket, preventing any further callbacks.
Bence Béky7294fc22018-02-08 14:26:17234 int result =
235 connection_->Write(buffer.get(), buffer->BytesRemaining(),
236 base::Bind(&WebSocketBasicStream::OnWriteComplete,
237 base::Unretained(this), buffer, callback),
238 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43239 if (result > 0) {
rajendrant75fe34f2017-03-28 05:53:00240 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
[email protected]adb225d2013-08-30 13:14:43241 buffer->DidConsume(result);
242 } else {
243 return result;
244 }
245 }
246 return OK;
247}
248
249void WebSocketBasicStream::OnWriteComplete(
250 const scoped_refptr<DrainableIOBuffer>& buffer,
251 const CompletionCallback& callback,
252 int result) {
253 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28254 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]adb225d2013-08-30 13:14:43255 callback.Run(result);
256 return;
257 }
258
[email protected]2f5d9f62013-09-26 12:14:28259 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00260 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
261
[email protected]adb225d2013-08-30 13:14:43262 buffer->DidConsume(result);
263 result = WriteEverything(buffer, callback);
264 if (result != ERR_IO_PENDING)
265 callback.Run(result);
266}
267
268int WebSocketBasicStream::HandleReadResult(
269 int result,
danakj9c5cab52016-04-16 00:54:33270 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43271 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28272 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43273 if (result < 0)
274 return result;
275 if (result == 0)
276 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00277
278 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Downstream", result);
279
danakj9c5cab52016-04-16 00:54:33280 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28281 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43282 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28283 if (frame_chunks.empty())
284 return ERR_IO_PENDING;
285 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43286}
287
[email protected]2f5d9f62013-09-26 12:14:28288int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33289 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
290 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28291 for (size_t i = 0; i < frame_chunks->size(); ++i) {
danakj9c5cab52016-04-16 00:54:33292 std::unique_ptr<WebSocketFrame> frame;
yhirano592ff7f2015-12-07 08:45:19293 int result = ConvertChunkToFrame(std::move((*frame_chunks)[i]), &frame);
[email protected]2f5d9f62013-09-26 12:14:28294 if (result != OK)
295 return result;
296 if (frame)
dchengc7eeda422015-12-26 03:56:48297 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28298 }
yhirano592ff7f2015-12-07 08:45:19299 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28300 if (frames->empty())
301 return ERR_IO_PENDING;
302 return OK;
303}
304
305int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33306 std::unique_ptr<WebSocketFrameChunk> chunk,
307 std::unique_ptr<WebSocketFrame>* frame) {
[email protected]2f5d9f62013-09-26 12:14:28308 DCHECK(frame->get() == NULL);
309 bool is_first_chunk = false;
310 if (chunk->header) {
311 DCHECK(current_frame_header_ == NULL)
312 << "Received the header for a new frame without notification that "
313 << "the previous frame was complete (bug in WebSocketFrameParser?)";
314 is_first_chunk = true;
315 current_frame_header_.swap(chunk->header);
316 }
dchengb206dc412014-08-26 19:46:23317 const int chunk_size = chunk->data.get() ? chunk->data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28318 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
319 << "(final_chunk = " << chunk->final_chunk
320 << ", data size = " << chunk_size
321 << ") (bug in WebSocketFrameParser?)";
322 scoped_refptr<IOBufferWithSize> data_buffer;
323 data_buffer.swap(chunk->data);
324 const bool is_final_chunk = chunk->final_chunk;
325 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
326 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
327 bool protocol_error = false;
328 if (!current_frame_header_->final) {
329 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
330 << " received with FIN bit unset.";
331 protocol_error = true;
332 }
333 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
334 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
335 << ", payload_length=" << current_frame_header_->payload_length
336 << " exceeds maximum payload length for a control message.";
337 protocol_error = true;
338 }
339 if (protocol_error) {
340 current_frame_header_.reset();
341 return ERR_WS_PROTOCOL_ERROR;
342 }
343 if (!is_final_chunk) {
344 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
dchengb206dc412014-08-26 19:46:23345 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28346 DVLOG(3) << "Appending to an existing split control frame.";
347 AddToIncompleteControlFrameBody(data_buffer);
348 } else {
349 DVLOG(3) << "Creating new storage for an incomplete control frame.";
Bence Béky65623972018-03-05 15:31:56350 incomplete_control_frame_body_ =
351 base::MakeRefCounted<GrowableIOBuffer>();
[email protected]2f5d9f62013-09-26 12:14:28352 // This method checks for oversize control frames above, so as long as
353 // the frame parser is working correctly, this won't overflow. If a bug
354 // does cause it to overflow, it will CHECK() in
355 // AddToIncompleteControlFrameBody() without writing outside the buffer.
356 incomplete_control_frame_body_->SetCapacity(kMaxControlFramePayload);
357 AddToIncompleteControlFrameBody(data_buffer);
358 }
359 return OK;
360 }
dchengb206dc412014-08-26 19:46:23361 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28362 DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
363 AddToIncompleteControlFrameBody(data_buffer);
364 const int body_size = incomplete_control_frame_body_->offset();
365 DCHECK_EQ(body_size,
366 static_cast<int>(current_frame_header_->payload_length));
Bence Béky65623972018-03-05 15:31:56367 auto body = base::MakeRefCounted<IOBufferWithSize>(body_size);
[email protected]2f5d9f62013-09-26 12:14:28368 memcpy(body->data(),
369 incomplete_control_frame_body_->StartOfBuffer(),
370 body_size);
371 incomplete_control_frame_body_ = NULL; // Frame now complete.
372 DCHECK(is_final_chunk);
373 *frame = CreateFrame(is_final_chunk, body);
374 return OK;
375 }
376 }
377
378 // Apply basic sanity checks to the |payload_length| field from the frame
379 // header. A check for exact equality can only be used when the whole frame
380 // arrives in one chunk.
381 DCHECK_GE(current_frame_header_->payload_length,
tfarina8a2c66c22015-10-13 19:14:49382 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28383 DCHECK(!is_first_chunk || !is_final_chunk ||
384 current_frame_header_->payload_length ==
tfarina8a2c66c22015-10-13 19:14:49385 base::checked_cast<uint64_t>(chunk_size));
[email protected]2f5d9f62013-09-26 12:14:28386
387 // Convert the chunk to a complete frame.
388 *frame = CreateFrame(is_final_chunk, data_buffer);
389 return OK;
390}
391
danakj9c5cab52016-04-16 00:54:33392std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
[email protected]2f5d9f62013-09-26 12:14:28393 bool is_final_chunk,
394 const scoped_refptr<IOBufferWithSize>& data) {
danakj9c5cab52016-04-16 00:54:33395 std::unique_ptr<WebSocketFrame> result_frame;
[email protected]2f5d9f62013-09-26 12:14:28396 const bool is_final_chunk_in_message =
397 is_final_chunk && current_frame_header_->final;
dchengb206dc412014-08-26 19:46:23398 const int data_size = data.get() ? data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28399 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
[email protected]e678d4fe2013-10-11 11:27:55400 // Empty frames convey no useful information unless they are the first frame
401 // (containing the type and flags) or have the "final" bit set.
402 if (is_final_chunk_in_message || data_size > 0 ||
403 current_frame_header_->opcode !=
404 WebSocketFrameHeader::kOpCodeContinuation) {
Bence Béky65623972018-03-05 15:31:56405 result_frame = std::make_unique<WebSocketFrame>(opcode);
[email protected]2f5d9f62013-09-26 12:14:28406 result_frame->header.CopyFrom(*current_frame_header_);
407 result_frame->header.final = is_final_chunk_in_message;
408 result_frame->header.payload_length = data_size;
409 result_frame->data = data;
410 // Ensure that opcodes Text and Binary are only used for the first frame in
[email protected]d52c0c42014-02-19 08:27:47411 // the message. Also clear the reserved bits.
412 // TODO(ricea): If a future extension requires the reserved bits to be
413 // retained on continuation frames, make this behaviour conditional on a
414 // flag set at construction time.
415 if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
[email protected]2f5d9f62013-09-26 12:14:28416 current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
[email protected]d52c0c42014-02-19 08:27:47417 current_frame_header_->reserved1 = false;
418 current_frame_header_->reserved2 = false;
419 current_frame_header_->reserved3 = false;
420 }
[email protected]2f5d9f62013-09-26 12:14:28421 }
422 // Make sure that a frame header is not applied to any chunks that do not
423 // belong to it.
424 if (is_final_chunk)
425 current_frame_header_.reset();
dchengc7eeda422015-12-26 03:56:48426 return result_frame;
[email protected]2f5d9f62013-09-26 12:14:28427}
428
429void WebSocketBasicStream::AddToIncompleteControlFrameBody(
430 const scoped_refptr<IOBufferWithSize>& data_buffer) {
dchengb206dc412014-08-26 19:46:23431 if (!data_buffer.get())
[email protected]2f5d9f62013-09-26 12:14:28432 return;
433 const int new_offset =
434 incomplete_control_frame_body_->offset() + data_buffer->size();
435 CHECK_GE(incomplete_control_frame_body_->capacity(), new_offset)
436 << "Control frame body larger than frame header indicates; frame parser "
437 "bug?";
438 memcpy(incomplete_control_frame_body_->data(),
439 data_buffer->data(),
440 data_buffer->size());
441 incomplete_control_frame_body_->set_offset(new_offset);
442}
443
yhirano592ff7f2015-12-07 08:45:19444void WebSocketBasicStream::OnReadComplete(
danakj9c5cab52016-04-16 00:54:33445 std::vector<std::unique_ptr<WebSocketFrame>>* frames,
yhirano592ff7f2015-12-07 08:45:19446 const CompletionCallback& callback,
447 int result) {
[email protected]2f5d9f62013-09-26 12:14:28448 result = HandleReadResult(result, frames);
[email protected]adb225d2013-08-30 13:14:43449 if (result == ERR_IO_PENDING)
[email protected]2f5d9f62013-09-26 12:14:28450 result = ReadFrames(frames, callback);
[email protected]adb225d2013-08-30 13:14:43451 if (result != ERR_IO_PENDING)
452 callback.Run(result);
453}
454
455} // namespace net