blob: 22d0c688621f734705240652ac12c22ab89beda5 [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)
[email protected]adb225d2013-08-30 13:14:43102 : read_buffer_(new 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);
[email protected]adb225d2013-08-30 13:14:43169 scoped_refptr<IOBufferWithSize> combined_buffer(
170 new IOBufferWithSize(total_size));
[email protected]9576544a2013-10-11 08:36:33171
[email protected]adb225d2013-08-30 13:14:43172 char* dest = combined_buffer->data();
173 int remaining_size = total_size;
yhirano592ff7f2015-12-07 08:45:19174 for (const auto& frame : *frames) {
[email protected]adb225d2013-08-30 13:14:43175 WebSocketMaskingKey mask = generate_websocket_masking_key_();
[email protected]2f5d9f62013-09-26 12:14:28176 int result =
177 WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
178 DCHECK_NE(ERR_INVALID_ARGUMENT, result)
[email protected]adb225d2013-08-30 13:14:43179 << "WriteWebSocketFrameHeader() says that " << remaining_size
180 << " is not enough to write the header in. This should not happen.";
181 CHECK_GE(result, 0) << "Potentially security-critical check failed";
182 dest += result;
183 remaining_size -= result;
184
tfarina8a2c66c22015-10-13 19:14:49185 CHECK_LE(frame->header.payload_length,
186 static_cast<uint64_t>(remaining_size));
pkasting4bff6be2014-10-15 17:54:34187 const int frame_size = static_cast<int>(frame->header.payload_length);
[email protected]403ee6e2014-01-27 10:10:44188 if (frame_size > 0) {
[email protected]403ee6e2014-01-27 10:10:44189 const char* const frame_data = frame->data->data();
190 std::copy(frame_data, frame_data + frame_size, dest);
191 MaskWebSocketFramePayload(mask, 0, dest, frame_size);
192 dest += frame_size;
193 remaining_size -= frame_size;
194 }
[email protected]adb225d2013-08-30 13:14:43195 }
196 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
197 << remaining_size << " bytes left over.";
198 scoped_refptr<DrainableIOBuffer> drainable_buffer(
dchengb206dc412014-08-26 19:46:23199 new DrainableIOBuffer(combined_buffer.get(), total_size));
[email protected]adb225d2013-08-30 13:14:43200 return WriteEverything(drainable_buffer, callback);
201}
202
Bence Béky7294fc22018-02-08 14:26:17203void WebSocketBasicStream::Close() {
204 connection_->Disconnect();
205}
[email protected]adb225d2013-08-30 13:14:43206
207std::string WebSocketBasicStream::GetSubProtocol() const {
208 return sub_protocol_;
209}
210
211std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
212
[email protected]adb225d2013-08-30 13:14:43213/*static*/
danakj9c5cab52016-04-16 00:54:33214std::unique_ptr<WebSocketBasicStream>
[email protected]adb225d2013-08-30 13:14:43215WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
danakj9c5cab52016-04-16 00:54:33216 std::unique_ptr<ClientSocketHandle> connection,
[email protected]adb225d2013-08-30 13:14:43217 const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
218 const std::string& sub_protocol,
219 const std::string& extensions,
220 WebSocketMaskingKeyGeneratorFunction key_generator_function) {
Bence Béky7294fc22018-02-08 14:26:17221 auto stream = std::make_unique<WebSocketBasicStream>(
222 std::make_unique<WebSocketClientSocketHandleAdapter>(
223 std::move(connection)),
224 http_read_buffer, sub_protocol, extensions);
[email protected]adb225d2013-08-30 13:14:43225 stream->generate_websocket_masking_key_ = key_generator_function;
dchengc7eeda422015-12-26 03:56:48226 return stream;
[email protected]adb225d2013-08-30 13:14:43227}
228
229int WebSocketBasicStream::WriteEverything(
230 const scoped_refptr<DrainableIOBuffer>& buffer,
231 const CompletionCallback& callback) {
232 while (buffer->BytesRemaining() > 0) {
233 // The use of base::Unretained() here is safe because on destruction we
234 // disconnect the socket, preventing any further callbacks.
Bence Béky7294fc22018-02-08 14:26:17235 int result =
236 connection_->Write(buffer.get(), buffer->BytesRemaining(),
237 base::Bind(&WebSocketBasicStream::OnWriteComplete,
238 base::Unretained(this), buffer, callback),
239 kTrafficAnnotation);
[email protected]adb225d2013-08-30 13:14:43240 if (result > 0) {
rajendrant75fe34f2017-03-28 05:53:00241 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
[email protected]adb225d2013-08-30 13:14:43242 buffer->DidConsume(result);
243 } else {
244 return result;
245 }
246 }
247 return OK;
248}
249
250void WebSocketBasicStream::OnWriteComplete(
251 const scoped_refptr<DrainableIOBuffer>& buffer,
252 const CompletionCallback& callback,
253 int result) {
254 if (result < 0) {
[email protected]2f5d9f62013-09-26 12:14:28255 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]adb225d2013-08-30 13:14:43256 callback.Run(result);
257 return;
258 }
259
[email protected]2f5d9f62013-09-26 12:14:28260 DCHECK_NE(0, result);
rajendrant75fe34f2017-03-28 05:53:00261 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Upstream", result);
262
[email protected]adb225d2013-08-30 13:14:43263 buffer->DidConsume(result);
264 result = WriteEverything(buffer, callback);
265 if (result != ERR_IO_PENDING)
266 callback.Run(result);
267}
268
269int WebSocketBasicStream::HandleReadResult(
270 int result,
danakj9c5cab52016-04-16 00:54:33271 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]adb225d2013-08-30 13:14:43272 DCHECK_NE(ERR_IO_PENDING, result);
[email protected]2f5d9f62013-09-26 12:14:28273 DCHECK(frames->empty());
[email protected]adb225d2013-08-30 13:14:43274 if (result < 0)
275 return result;
276 if (result == 0)
277 return ERR_CONNECTION_CLOSED;
rajendrant75fe34f2017-03-28 05:53:00278
279 UMA_HISTOGRAM_COUNTS_100000("Net.WebSocket.DataUse.Downstream", result);
280
danakj9c5cab52016-04-16 00:54:33281 std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
[email protected]2f5d9f62013-09-26 12:14:28282 if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
[email protected]adb225d2013-08-30 13:14:43283 return WebSocketErrorToNetError(parser_.websocket_error());
[email protected]2f5d9f62013-09-26 12:14:28284 if (frame_chunks.empty())
285 return ERR_IO_PENDING;
286 return ConvertChunksToFrames(&frame_chunks, frames);
[email protected]adb225d2013-08-30 13:14:43287}
288
[email protected]2f5d9f62013-09-26 12:14:28289int WebSocketBasicStream::ConvertChunksToFrames(
danakj9c5cab52016-04-16 00:54:33290 std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
291 std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
[email protected]2f5d9f62013-09-26 12:14:28292 for (size_t i = 0; i < frame_chunks->size(); ++i) {
danakj9c5cab52016-04-16 00:54:33293 std::unique_ptr<WebSocketFrame> frame;
yhirano592ff7f2015-12-07 08:45:19294 int result = ConvertChunkToFrame(std::move((*frame_chunks)[i]), &frame);
[email protected]2f5d9f62013-09-26 12:14:28295 if (result != OK)
296 return result;
297 if (frame)
dchengc7eeda422015-12-26 03:56:48298 frames->push_back(std::move(frame));
[email protected]2f5d9f62013-09-26 12:14:28299 }
yhirano592ff7f2015-12-07 08:45:19300 frame_chunks->clear();
[email protected]2f5d9f62013-09-26 12:14:28301 if (frames->empty())
302 return ERR_IO_PENDING;
303 return OK;
304}
305
306int WebSocketBasicStream::ConvertChunkToFrame(
danakj9c5cab52016-04-16 00:54:33307 std::unique_ptr<WebSocketFrameChunk> chunk,
308 std::unique_ptr<WebSocketFrame>* frame) {
[email protected]2f5d9f62013-09-26 12:14:28309 DCHECK(frame->get() == NULL);
310 bool is_first_chunk = false;
311 if (chunk->header) {
312 DCHECK(current_frame_header_ == NULL)
313 << "Received the header for a new frame without notification that "
314 << "the previous frame was complete (bug in WebSocketFrameParser?)";
315 is_first_chunk = true;
316 current_frame_header_.swap(chunk->header);
317 }
dchengb206dc412014-08-26 19:46:23318 const int chunk_size = chunk->data.get() ? chunk->data->size() : 0;
[email protected]2f5d9f62013-09-26 12:14:28319 DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
320 << "(final_chunk = " << chunk->final_chunk
321 << ", data size = " << chunk_size
322 << ") (bug in WebSocketFrameParser?)";
323 scoped_refptr<IOBufferWithSize> data_buffer;
324 data_buffer.swap(chunk->data);
325 const bool is_final_chunk = chunk->final_chunk;
326 const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
327 if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
328 bool protocol_error = false;
329 if (!current_frame_header_->final) {
330 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
331 << " received with FIN bit unset.";
332 protocol_error = true;
333 }
334 if (current_frame_header_->payload_length > kMaxControlFramePayload) {
335 DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
336 << ", payload_length=" << current_frame_header_->payload_length
337 << " exceeds maximum payload length for a control message.";
338 protocol_error = true;
339 }
340 if (protocol_error) {
341 current_frame_header_.reset();
342 return ERR_WS_PROTOCOL_ERROR;
343 }
344 if (!is_final_chunk) {
345 DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
dchengb206dc412014-08-26 19:46:23346 if (incomplete_control_frame_body_.get()) {
[email protected]2f5d9f62013-09-26 12:14:28347 DVLOG(3) << "Appending to an existing split control frame.";
348 AddToIncompleteControlFrameBody(data_buffer);
349 } else {
350 DVLOG(3) << "Creating new storage for an incomplete control frame.";
351 incomplete_control_frame_body_ = new GrowableIOBuffer();
352 // 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));
367 scoped_refptr<IOBufferWithSize> body = new IOBufferWithSize(body_size);
368 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) {
[email protected]2f5d9f62013-09-26 12:14:28405 result_frame.reset(new WebSocketFrame(opcode));
406 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