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