xref: /aosp_15_r20/external/cronet/net/websockets/websocket_basic_stream.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
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 
7 #include <stddef.h>
8 #include <stdint.h>
9 
10 #include <algorithm>
11 #include <limits>
12 #include <ostream>
13 #include <utility>
14 
15 #include "base/check.h"
16 #include "base/check_op.h"
17 #include "base/functional/bind.h"
18 #include "base/functional/callback.h"
19 #include "base/logging.h"
20 #include "base/numerics/safe_conversions.h"
21 #include "base/values.h"
22 #include "build/build_config.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/net_errors.h"
25 #include "net/log/net_log_event_type.h"
26 #include "net/socket/client_socket_handle.h"
27 #include "net/traffic_annotation/network_traffic_annotation.h"
28 #include "net/websockets/websocket_basic_stream_adapters.h"
29 #include "net/websockets/websocket_errors.h"
30 #include "net/websockets/websocket_frame.h"
31 
32 namespace net {
33 
34 namespace {
35 
36 // Please refer to the comment in class header if the usage changes.
37 constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
38     net::DefineNetworkTrafficAnnotation("websocket_basic_stream", R"(
39       semantics {
40         sender: "WebSocket Basic Stream"
41         description:
42           "Implementation of WebSocket API from web content (a page the user "
43           "visits)."
44         trigger: "Website calls the WebSocket API."
45         data:
46           "Any data provided by web content, masked and framed in accordance "
47           "with RFC6455."
48         destination: OTHER
49         destination_other:
50           "The address that the website has chosen to communicate to."
51       }
52       policy {
53         cookies_allowed: YES
54         cookies_store: "user"
55         setting: "These requests cannot be disabled."
56         policy_exception_justification:
57           "Not implemented. WebSocket is a core web platform API."
58       }
59       comments:
60         "The browser will never add cookies to a WebSocket message. But the "
61         "handshake that was performed when the WebSocket connection was "
62         "established may have contained cookies."
63       )");
64 
65 // This uses type uint64_t to match the definition of
66 // WebSocketFrameHeader::payload_length in websocket_frame.h.
67 constexpr uint64_t kMaxControlFramePayload = 125;
68 
69 // The number of bytes to attempt to read at a time. It's used only for high
70 // throughput connections.
71 // TODO(ricea): See if there is a better number or algorithm to fulfill our
72 // requirements:
73 //  1. We would like to use minimal memory on low-bandwidth or idle connections
74 //  2. We would like to read as close to line speed as possible on
75 //     high-bandwidth connections
76 //  3. We can't afford to cause jank on the IO thread by copying large buffers
77 //     around
78 //  4. We would like to hit any sweet-spots that might exist in terms of network
79 //     packet sizes / encryption block sizes / IPC alignment issues, etc.
80 #if BUILDFLAG(IS_ANDROID)
81 constexpr size_t kLargeReadBufferSize = 32 * 1024;
82 #else
83 // |2^n - delta| is better than 2^n on Linux. See crrev.com/c/1792208.
84 constexpr size_t kLargeReadBufferSize = 131000;
85 #endif
86 
87 // The number of bytes to attempt to read at a time. It's set as an initial read
88 // buffer size and used for low throughput connections.
89 constexpr size_t kSmallReadBufferSize = 1000;
90 
91 // The threshold to decide whether to switch the read buffer size.
92 constexpr double kThresholdInBytesPerSecond = 1200 * 1000;
93 
94 // Returns the total serialized size of |frames|. This function assumes that
95 // |frames| will be serialized with mask field. This function forces the
96 // masked bit of the frames on.
CalculateSerializedSizeAndTurnOnMaskBit(std::vector<std::unique_ptr<WebSocketFrame>> * frames)97 int CalculateSerializedSizeAndTurnOnMaskBit(
98     std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
99   constexpr uint64_t kMaximumTotalSize = std::numeric_limits<int>::max();
100 
101   uint64_t total_size = 0;
102   for (const auto& frame : *frames) {
103     // Force the masked bit on.
104     frame->header.masked = true;
105     // We enforce flow control so the renderer should never be able to force us
106     // to cache anywhere near 2GB of frames.
107     uint64_t frame_size = frame->header.payload_length +
108                           GetWebSocketFrameHeaderSize(frame->header);
109     CHECK_LE(frame_size, kMaximumTotalSize - total_size)
110         << "Aborting to prevent overflow";
111     total_size += frame_size;
112   }
113   return static_cast<int>(total_size);
114 }
115 
NetLogBufferSizeParam(int buffer_size)116 base::Value::Dict NetLogBufferSizeParam(int buffer_size) {
117   base::Value::Dict dict;
118   dict.Set("read_buffer_size_in_bytes", buffer_size);
119   return dict;
120 }
121 
NetLogFrameHeaderParam(const WebSocketFrameHeader * header)122 base::Value::Dict NetLogFrameHeaderParam(const WebSocketFrameHeader* header) {
123   base::Value::Dict dict;
124   dict.Set("final", header->final);
125   dict.Set("reserved1", header->reserved1);
126   dict.Set("reserved2", header->reserved2);
127   dict.Set("reserved3", header->reserved3);
128   dict.Set("opcode", header->opcode);
129   dict.Set("masked", header->masked);
130   dict.Set("payload_length", static_cast<double>(header->payload_length));
131   return dict;
132 }
133 
134 }  // namespace
135 
136 WebSocketBasicStream::BufferSizeManager::BufferSizeManager() = default;
137 
138 WebSocketBasicStream::BufferSizeManager::~BufferSizeManager() = default;
139 
OnRead(base::TimeTicks now)140 void WebSocketBasicStream::BufferSizeManager::OnRead(base::TimeTicks now) {
141   read_start_timestamps_.push(now);
142 }
143 
OnReadComplete(base::TimeTicks now,int size)144 void WebSocketBasicStream::BufferSizeManager::OnReadComplete(
145     base::TimeTicks now,
146     int size) {
147   DCHECK_GT(size, 0);
148   // This cannot overflow because the result is at most
149   // kLargeReadBufferSize*rolling_average_window_.
150   rolling_byte_total_ += size;
151   recent_read_sizes_.push(size);
152   DCHECK_LE(read_start_timestamps_.size(), rolling_average_window_);
153   if (read_start_timestamps_.size() == rolling_average_window_) {
154     DCHECK_EQ(read_start_timestamps_.size(), recent_read_sizes_.size());
155     base::TimeDelta duration = now - read_start_timestamps_.front();
156     base::TimeDelta threshold_duration =
157         base::Seconds(rolling_byte_total_ / kThresholdInBytesPerSecond);
158     read_start_timestamps_.pop();
159     rolling_byte_total_ -= recent_read_sizes_.front();
160     recent_read_sizes_.pop();
161     if (threshold_duration < duration) {
162       buffer_size_ = BufferSize::kSmall;
163     } else {
164       buffer_size_ = BufferSize::kLarge;
165     }
166   }
167 }
168 
WebSocketBasicStream(std::unique_ptr<Adapter> connection,const scoped_refptr<GrowableIOBuffer> & http_read_buffer,const std::string & sub_protocol,const std::string & extensions,const NetLogWithSource & net_log)169 WebSocketBasicStream::WebSocketBasicStream(
170     std::unique_ptr<Adapter> connection,
171     const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
172     const std::string& sub_protocol,
173     const std::string& extensions,
174     const NetLogWithSource& net_log)
175     : read_buffer_(
176           base::MakeRefCounted<IOBufferWithSize>(kSmallReadBufferSize)),
177       target_read_buffer_size_(read_buffer_->size()),
178       connection_(std::move(connection)),
179       http_read_buffer_(http_read_buffer),
180       sub_protocol_(sub_protocol),
181       extensions_(extensions),
182       net_log_(net_log),
183       generate_websocket_masking_key_(&GenerateWebSocketMaskingKey) {
184   // http_read_buffer_ should not be set if it contains no data.
185   if (http_read_buffer_.get() && http_read_buffer_->offset() == 0)
186     http_read_buffer_ = nullptr;
187   DCHECK(connection_->is_initialized());
188 }
189 
~WebSocketBasicStream()190 WebSocketBasicStream::~WebSocketBasicStream() { Close(); }
191 
ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>> * frames,CompletionOnceCallback callback)192 int WebSocketBasicStream::ReadFrames(
193     std::vector<std::unique_ptr<WebSocketFrame>>* frames,
194     CompletionOnceCallback callback) {
195   read_callback_ = std::move(callback);
196   complete_control_frame_body_.clear();
197   if (http_read_buffer_ && is_http_read_buffer_decoded_) {
198     http_read_buffer_.reset();
199   }
200   return ReadEverything(frames);
201 }
202 
WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>> * frames,CompletionOnceCallback callback)203 int WebSocketBasicStream::WriteFrames(
204     std::vector<std::unique_ptr<WebSocketFrame>>* frames,
205     CompletionOnceCallback callback) {
206   // This function always concatenates all frames into a single buffer.
207   // TODO(ricea): Investigate whether it would be better in some cases to
208   // perform multiple writes with smaller buffers.
209 
210   write_callback_ = std::move(callback);
211 
212   // First calculate the size of the buffer we need to allocate.
213   int total_size = CalculateSerializedSizeAndTurnOnMaskBit(frames);
214   auto combined_buffer = base::MakeRefCounted<IOBufferWithSize>(total_size);
215 
216   char* dest = combined_buffer->data();
217   int remaining_size = total_size;
218   for (const auto& frame : *frames) {
219     net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_SENT_FRAME_HEADER,
220                       [&] { return NetLogFrameHeaderParam(&frame->header); });
221     WebSocketMaskingKey mask = generate_websocket_masking_key_();
222     int result =
223         WriteWebSocketFrameHeader(frame->header, &mask, dest, remaining_size);
224     DCHECK_NE(ERR_INVALID_ARGUMENT, result)
225         << "WriteWebSocketFrameHeader() says that " << remaining_size
226         << " is not enough to write the header in. This should not happen.";
227     CHECK_GE(result, 0) << "Potentially security-critical check failed";
228     dest += result;
229     remaining_size -= result;
230 
231     CHECK_LE(frame->header.payload_length,
232              static_cast<uint64_t>(remaining_size));
233     const int frame_size = static_cast<int>(frame->header.payload_length);
234     if (frame_size > 0) {
235       const char* const frame_data = frame->payload;
236       std::copy(frame_data, frame_data + frame_size, dest);
237       MaskWebSocketFramePayload(mask, 0, dest, frame_size);
238       dest += frame_size;
239       remaining_size -= frame_size;
240     }
241   }
242   DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; "
243                                << remaining_size << " bytes left over.";
244   auto drainable_buffer = base::MakeRefCounted<DrainableIOBuffer>(
245       std::move(combined_buffer), total_size);
246   return WriteEverything(drainable_buffer);
247 }
248 
Close()249 void WebSocketBasicStream::Close() {
250   connection_->Disconnect();
251 }
252 
GetSubProtocol() const253 std::string WebSocketBasicStream::GetSubProtocol() const {
254   return sub_protocol_;
255 }
256 
GetExtensions() const257 std::string WebSocketBasicStream::GetExtensions() const { return extensions_; }
258 
GetNetLogWithSource() const259 const NetLogWithSource& WebSocketBasicStream::GetNetLogWithSource() const {
260   return net_log_;
261 }
262 
263 /*static*/
264 std::unique_ptr<WebSocketBasicStream>
CreateWebSocketBasicStreamForTesting(std::unique_ptr<ClientSocketHandle> connection,const scoped_refptr<GrowableIOBuffer> & http_read_buffer,const std::string & sub_protocol,const std::string & extensions,const NetLogWithSource & net_log,WebSocketMaskingKeyGeneratorFunction key_generator_function)265 WebSocketBasicStream::CreateWebSocketBasicStreamForTesting(
266     std::unique_ptr<ClientSocketHandle> connection,
267     const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
268     const std::string& sub_protocol,
269     const std::string& extensions,
270     const NetLogWithSource& net_log,
271     WebSocketMaskingKeyGeneratorFunction key_generator_function) {
272   auto stream = std::make_unique<WebSocketBasicStream>(
273       std::make_unique<WebSocketClientSocketHandleAdapter>(
274           std::move(connection)),
275       http_read_buffer, sub_protocol, extensions, net_log);
276   stream->generate_websocket_masking_key_ = key_generator_function;
277   return stream;
278 }
279 
ReadEverything(std::vector<std::unique_ptr<WebSocketFrame>> * frames)280 int WebSocketBasicStream::ReadEverything(
281     std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
282   DCHECK(frames->empty());
283 
284   // If there is data left over after parsing the HTTP headers, attempt to parse
285   // it as WebSocket frames.
286   if (http_read_buffer_.get() && !is_http_read_buffer_decoded_) {
287     DCHECK_GE(http_read_buffer_->offset(), 0);
288     is_http_read_buffer_decoded_ = true;
289     std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
290     if (!parser_.Decode(http_read_buffer_->StartOfBuffer(),
291                         http_read_buffer_->offset(), &frame_chunks))
292       return WebSocketErrorToNetError(parser_.websocket_error());
293     if (!frame_chunks.empty()) {
294       int result = ConvertChunksToFrames(&frame_chunks, frames);
295       if (result != ERR_IO_PENDING)
296         return result;
297     }
298   }
299 
300   // Run until socket stops giving us data or we get some frames.
301   while (true) {
302     if (buffer_size_manager_.buffer_size() != buffer_size_) {
303       read_buffer_ = base::MakeRefCounted<IOBufferWithSize>(
304           buffer_size_manager_.buffer_size() == BufferSize::kSmall
305               ? kSmallReadBufferSize
306               : kLargeReadBufferSize);
307       buffer_size_ = buffer_size_manager_.buffer_size();
308       net_log_.AddEvent(
309           net::NetLogEventType::WEBSOCKET_READ_BUFFER_SIZE_CHANGED,
310           [&] { return NetLogBufferSizeParam(read_buffer_->size()); });
311     }
312     buffer_size_manager_.OnRead(base::TimeTicks::Now());
313 
314     // base::Unretained(this) here is safe because net::Socket guarantees not to
315     // call any callbacks after Disconnect(), which we call from the destructor.
316     // The caller of ReadEverything() is required to keep |frames| valid.
317     int result = connection_->Read(
318         read_buffer_.get(), read_buffer_->size(),
319         base::BindOnce(&WebSocketBasicStream::OnReadComplete,
320                        base::Unretained(this), base::Unretained(frames)));
321     if (result == ERR_IO_PENDING)
322       return result;
323     result = HandleReadResult(result, frames);
324     if (result != ERR_IO_PENDING)
325       return result;
326     DCHECK(frames->empty());
327   }
328 }
329 
OnReadComplete(std::vector<std::unique_ptr<WebSocketFrame>> * frames,int result)330 void WebSocketBasicStream::OnReadComplete(
331     std::vector<std::unique_ptr<WebSocketFrame>>* frames,
332     int result) {
333   result = HandleReadResult(result, frames);
334   if (result == ERR_IO_PENDING)
335     result = ReadEverything(frames);
336   if (result != ERR_IO_PENDING)
337     std::move(read_callback_).Run(result);
338 }
339 
WriteEverything(const scoped_refptr<DrainableIOBuffer> & buffer)340 int WebSocketBasicStream::WriteEverything(
341     const scoped_refptr<DrainableIOBuffer>& buffer) {
342   while (buffer->BytesRemaining() > 0) {
343     // The use of base::Unretained() here is safe because on destruction we
344     // disconnect the socket, preventing any further callbacks.
345     int result = connection_->Write(
346         buffer.get(), buffer->BytesRemaining(),
347         base::BindOnce(&WebSocketBasicStream::OnWriteComplete,
348                        base::Unretained(this), buffer),
349         kTrafficAnnotation);
350     if (result > 0) {
351       buffer->DidConsume(result);
352     } else {
353       return result;
354     }
355   }
356   return OK;
357 }
358 
OnWriteComplete(const scoped_refptr<DrainableIOBuffer> & buffer,int result)359 void WebSocketBasicStream::OnWriteComplete(
360     const scoped_refptr<DrainableIOBuffer>& buffer,
361     int result) {
362   if (result < 0) {
363     DCHECK_NE(ERR_IO_PENDING, result);
364     std::move(write_callback_).Run(result);
365     return;
366   }
367 
368   DCHECK_NE(0, result);
369 
370   buffer->DidConsume(result);
371   result = WriteEverything(buffer);
372   if (result != ERR_IO_PENDING)
373     std::move(write_callback_).Run(result);
374 }
375 
HandleReadResult(int result,std::vector<std::unique_ptr<WebSocketFrame>> * frames)376 int WebSocketBasicStream::HandleReadResult(
377     int result,
378     std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
379   DCHECK_NE(ERR_IO_PENDING, result);
380   DCHECK(frames->empty());
381   if (result < 0)
382     return result;
383   if (result == 0)
384     return ERR_CONNECTION_CLOSED;
385 
386   buffer_size_manager_.OnReadComplete(base::TimeTicks::Now(), result);
387 
388   std::vector<std::unique_ptr<WebSocketFrameChunk>> frame_chunks;
389   if (!parser_.Decode(read_buffer_->data(), result, &frame_chunks))
390     return WebSocketErrorToNetError(parser_.websocket_error());
391   if (frame_chunks.empty())
392     return ERR_IO_PENDING;
393   return ConvertChunksToFrames(&frame_chunks, frames);
394 }
395 
ConvertChunksToFrames(std::vector<std::unique_ptr<WebSocketFrameChunk>> * frame_chunks,std::vector<std::unique_ptr<WebSocketFrame>> * frames)396 int WebSocketBasicStream::ConvertChunksToFrames(
397     std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
398     std::vector<std::unique_ptr<WebSocketFrame>>* frames) {
399   for (size_t i = 0; i < frame_chunks->size(); ++i) {
400     auto& chunk = (*frame_chunks)[i];
401     DCHECK(chunk == frame_chunks->back() || chunk->final_chunk)
402         << "Only last chunk can have |final_chunk| set to be false.";
403     if (const auto& header = chunk->header) {
404       net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_RECV_FRAME_HEADER,
405                         [&] { return NetLogFrameHeaderParam(header.get()); });
406     }
407     std::unique_ptr<WebSocketFrame> frame;
408     int result = ConvertChunkToFrame(std::move(chunk), &frame);
409     if (result != OK)
410       return result;
411     if (frame)
412       frames->push_back(std::move(frame));
413   }
414   frame_chunks->clear();
415   if (frames->empty())
416     return ERR_IO_PENDING;
417   return OK;
418 }
419 
ConvertChunkToFrame(std::unique_ptr<WebSocketFrameChunk> chunk,std::unique_ptr<WebSocketFrame> * frame)420 int WebSocketBasicStream::ConvertChunkToFrame(
421     std::unique_ptr<WebSocketFrameChunk> chunk,
422     std::unique_ptr<WebSocketFrame>* frame) {
423   DCHECK(frame->get() == nullptr);
424   bool is_first_chunk = false;
425   if (chunk->header) {
426     DCHECK(current_frame_header_ == nullptr)
427         << "Received the header for a new frame without notification that "
428         << "the previous frame was complete (bug in WebSocketFrameParser?)";
429     is_first_chunk = true;
430     current_frame_header_.swap(chunk->header);
431   }
432   DCHECK(current_frame_header_) << "Unexpected header-less chunk received "
433                                 << "(final_chunk = " << chunk->final_chunk
434                                 << ", payload size = " << chunk->payload.size()
435                                 << ") (bug in WebSocketFrameParser?)";
436   const bool is_final_chunk = chunk->final_chunk;
437   const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
438   if (WebSocketFrameHeader::IsKnownControlOpCode(opcode)) {
439     bool protocol_error = false;
440     if (!current_frame_header_->final) {
441       DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
442                << " received with FIN bit unset.";
443       protocol_error = true;
444     }
445     if (current_frame_header_->payload_length > kMaxControlFramePayload) {
446       DVLOG(1) << "WebSocket protocol error. Control frame, opcode=" << opcode
447                << ", payload_length=" << current_frame_header_->payload_length
448                << " exceeds maximum payload length for a control message.";
449       protocol_error = true;
450     }
451     if (protocol_error) {
452       current_frame_header_.reset();
453       return ERR_WS_PROTOCOL_ERROR;
454     }
455 
456     if (!is_final_chunk) {
457       DVLOG(2) << "Encountered a split control frame, opcode " << opcode;
458       AddToIncompleteControlFrameBody(chunk->payload);
459       return OK;
460     }
461 
462     if (!incomplete_control_frame_body_.empty()) {
463       DVLOG(2) << "Rejoining a split control frame, opcode " << opcode;
464       AddToIncompleteControlFrameBody(chunk->payload);
465       DCHECK(is_final_chunk);
466       DCHECK(complete_control_frame_body_.empty());
467       complete_control_frame_body_ = std::move(incomplete_control_frame_body_);
468       *frame = CreateFrame(is_final_chunk, complete_control_frame_body_);
469       return OK;
470     }
471   }
472 
473   // Apply basic sanity checks to the |payload_length| field from the frame
474   // header. A check for exact equality can only be used when the whole frame
475   // arrives in one chunk.
476   DCHECK_GE(current_frame_header_->payload_length,
477             base::checked_cast<uint64_t>(chunk->payload.size()));
478   DCHECK(!is_first_chunk || !is_final_chunk ||
479          current_frame_header_->payload_length ==
480              base::checked_cast<uint64_t>(chunk->payload.size()));
481 
482   // Convert the chunk to a complete frame.
483   *frame = CreateFrame(is_final_chunk, chunk->payload);
484   return OK;
485 }
486 
CreateFrame(bool is_final_chunk,base::span<const char> data)487 std::unique_ptr<WebSocketFrame> WebSocketBasicStream::CreateFrame(
488     bool is_final_chunk,
489     base::span<const char> data) {
490   std::unique_ptr<WebSocketFrame> result_frame;
491   const bool is_final_chunk_in_message =
492       is_final_chunk && current_frame_header_->final;
493   const WebSocketFrameHeader::OpCode opcode = current_frame_header_->opcode;
494   // Empty frames convey no useful information unless they are the first frame
495   // (containing the type and flags) or have the "final" bit set.
496   if (is_final_chunk_in_message || data.size() > 0 ||
497       current_frame_header_->opcode !=
498           WebSocketFrameHeader::kOpCodeContinuation) {
499     result_frame = std::make_unique<WebSocketFrame>(opcode);
500     result_frame->header.CopyFrom(*current_frame_header_);
501     result_frame->header.final = is_final_chunk_in_message;
502     result_frame->header.payload_length = data.size();
503     result_frame->payload = data.data();
504     // Ensure that opcodes Text and Binary are only used for the first frame in
505     // the message. Also clear the reserved bits.
506     // TODO(ricea): If a future extension requires the reserved bits to be
507     // retained on continuation frames, make this behaviour conditional on a
508     // flag set at construction time.
509     if (!is_final_chunk && WebSocketFrameHeader::IsKnownDataOpCode(opcode)) {
510       current_frame_header_->opcode = WebSocketFrameHeader::kOpCodeContinuation;
511       current_frame_header_->reserved1 = false;
512       current_frame_header_->reserved2 = false;
513       current_frame_header_->reserved3 = false;
514     }
515   }
516   // Make sure that a frame header is not applied to any chunks that do not
517   // belong to it.
518   if (is_final_chunk)
519     current_frame_header_.reset();
520   return result_frame;
521 }
522 
AddToIncompleteControlFrameBody(base::span<const char> data)523 void WebSocketBasicStream::AddToIncompleteControlFrameBody(
524     base::span<const char> data) {
525   if (data.empty()) {
526     return;
527   }
528   incomplete_control_frame_body_.insert(incomplete_control_frame_body_.end(),
529                                         data.begin(), data.end());
530   // This method checks for oversize control frames above, so as long as
531   // the frame parser is working correctly, this won't overflow. If a bug
532   // does cause it to overflow, it will CHECK() in
533   // AddToIncompleteControlFrameBody() without writing outside the buffer.
534   CHECK_LE(incomplete_control_frame_body_.size(), kMaxControlFramePayload)
535       << "Control frame body larger than frame header indicates; frame parser "
536          "bug?";
537 }
538 
539 }  // namespace net
540