1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "net/quic/quic_chromium_packet_writer.h"
#include <string>
#include <utility>
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/task/sequenced_task_runner.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/quic/quic_chromium_client_session.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
namespace net {
namespace {
enum NotReusableReason {
NOT_REUSABLE_NULLPTR = 0,
NOT_REUSABLE_TOO_SMALL = 1,
NOT_REUSABLE_REF_COUNT = 2,
NUM_NOT_REUSABLE_REASONS = 3,
};
const int kMaxRetries = 12; // 2^12 = 4 seconds, which should be a LOT.
void RecordNotReusableReason(NotReusableReason reason) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.WritePacketNotReusable", reason,
NUM_NOT_REUSABLE_REASONS);
}
void RecordRetryCount(int count) {
UMA_HISTOGRAM_EXACT_LINEAR("Net.QuicSession.RetryAfterWriteErrorCount2",
count, kMaxRetries + 1);
}
const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("quic_chromium_packet_writer", R"(
semantics {
sender: "QUIC Packet Writer"
description:
"A QUIC packet is written to the wire based on a request from "
"a QUIC stream."
trigger:
"A request from QUIC stream."
data: "Any data sent by the stream."
destination: OTHER
destination_other: "Any destination choosen by the stream."
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled in settings."
policy_exception_justification:
"Essential for network access."
}
comments:
"All requests that are received by QUIC streams have network traffic "
"annotation, but the annotation is not passed to the writer function "
"due to technial overheads. Please see QuicChromiumClientSession and "
"QuicChromiumClientStream classes for references."
)");
EcnCodePoint QuicheEcnToChromiumEcn(const quic::QuicEcnCodepoint codepoint) {
switch (codepoint) {
case quic::ECN_NOT_ECT:
return ECN_NOT_ECT;
case quic::ECN_ECT1:
return ECN_ECT1;
case quic::ECN_ECT0:
return ECN_ECT0;
case quic::ECN_CE:
return ECN_CE;
default:
break;
}
NOTREACHED();
}
} // namespace
QuicChromiumPacketWriter::ReusableIOBuffer::ReusableIOBuffer(size_t capacity)
: IOBufferWithSize(capacity), capacity_(capacity) {}
QuicChromiumPacketWriter::ReusableIOBuffer::~ReusableIOBuffer() = default;
void QuicChromiumPacketWriter::ReusableIOBuffer::Set(const char* buffer,
size_t buf_len) {
CHECK_LE(buf_len, capacity_);
CHECK(HasOneRef());
size_ = buf_len;
std::memcpy(data(), buffer, buf_len);
}
QuicChromiumPacketWriter::QuicChromiumPacketWriter(
DatagramClientSocket* socket,
base::SequencedTaskRunner* task_runner)
: socket_(socket),
packet_(base::MakeRefCounted<ReusableIOBuffer>(
quic::kMaxOutgoingPacketSize)) {
retry_timer_.SetTaskRunner(task_runner);
write_callback_ = base::BindRepeating(
&QuicChromiumPacketWriter::OnWriteComplete, weak_factory_.GetWeakPtr());
}
QuicChromiumPacketWriter::~QuicChromiumPacketWriter() {
UMA_HISTOGRAM_ENUMERATION(
"Net.QuicSession.OutgoingEcn",
static_cast<EcnPermutations>(outgoing_ecn_history_));
}
void QuicChromiumPacketWriter::set_force_write_blocked(
bool force_write_blocked) {
force_write_blocked_ = force_write_blocked;
if (!IsWriteBlocked() && delegate_ != nullptr)
delegate_->OnWriteUnblocked();
}
void QuicChromiumPacketWriter::SetPacket(const char* buffer, size_t buf_len) {
if (!packet_) [[unlikely]] {
packet_ = base::MakeRefCounted<ReusableIOBuffer>(
std::max(buf_len, static_cast<size_t>(quic::kMaxOutgoingPacketSize)));
RecordNotReusableReason(NOT_REUSABLE_NULLPTR);
}
if (packet_->capacity() < buf_len) [[unlikely]] {
packet_ = base::MakeRefCounted<ReusableIOBuffer>(buf_len);
RecordNotReusableReason(NOT_REUSABLE_TOO_SMALL);
}
if (!packet_->HasOneRef()) [[unlikely]] {
packet_ = base::MakeRefCounted<ReusableIOBuffer>(
std::max(buf_len, static_cast<size_t>(quic::kMaxOutgoingPacketSize)));
RecordNotReusableReason(NOT_REUSABLE_REF_COUNT);
}
packet_->Set(buffer, buf_len);
}
quic::WriteResult QuicChromiumPacketWriter::WritePacket(
const char* buffer,
size_t buf_len,
const quiche::QuicheIpAddress& self_address,
const quic::QuicSocketAddress& peer_address,
quic::PerPacketOptions* /*options*/,
const quic::QuicPacketWriterParams& params) {
CHECK(!IsWriteBlocked());
SetPacket(buffer, buf_len);
EcnCodePoint new_ecn = QuicheEcnToChromiumEcn(params.ecn_codepoint);
outgoing_ecn_history_ |= (1 << static_cast<uint8_t>(new_ecn));
if (new_ecn != outgoing_ecn_) {
socket_->SetTos(DSCP_NO_CHANGE, new_ecn);
outgoing_ecn_ = new_ecn;
}
return WritePacketToSocketImpl();
}
void QuicChromiumPacketWriter::WritePacketToSocket(
scoped_refptr<ReusableIOBuffer> packet) {
CHECK(!force_write_blocked_);
CHECK(!IsWriteBlocked());
packet_ = std::move(packet);
quic::WriteResult result = WritePacketToSocketImpl();
if (result.error_code != ERR_IO_PENDING)
OnWriteComplete(result.error_code);
}
quic::WriteResult QuicChromiumPacketWriter::WritePacketToSocketImpl() {
base::TimeTicks now = base::TimeTicks::Now();
// When the connection is closed, the socket is cleaned up. If socket is
// invalidated, packets should not be written to the socket.
CHECK(socket_);
int rv = socket_->Write(packet_.get(), packet_->size(), write_callback_,
kTrafficAnnotation);
if (MaybeRetryAfterWriteError(rv))
return quic::WriteResult(quic::WRITE_STATUS_BLOCKED_DATA_BUFFERED,
ERR_IO_PENDING);
if (rv < 0 && rv != ERR_IO_PENDING && delegate_ != nullptr) {
// If write error, then call delegate's HandleWriteError, which
// may be able to migrate and rewrite packet on a new socket.
// HandleWriteError returns the outcome of that rewrite attempt.
rv = delegate_->HandleWriteError(rv, std::move(packet_));
DCHECK(packet_ == nullptr);
}
quic::WriteStatus status = quic::WRITE_STATUS_OK;
if (rv < 0) {
if (rv != ERR_IO_PENDING) {
status = quic::WRITE_STATUS_ERROR;
} else {
status = quic::WRITE_STATUS_BLOCKED_DATA_BUFFERED;
write_in_progress_ = true;
}
}
base::TimeDelta delta = base::TimeTicks::Now() - now;
if (status == quic::WRITE_STATUS_OK) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.PacketWriteTime.Synchronous", delta);
} else if (quic::IsWriteBlockedStatus(status)) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.PacketWriteTime.Asynchronous", delta);
}
return quic::WriteResult(status, rv);
}
void QuicChromiumPacketWriter::RetryPacketAfterNoBuffers() {
DCHECK_GT(retry_count_, 0);
if (socket_) {
quic::WriteResult result = WritePacketToSocketImpl();
if (result.error_code != ERR_IO_PENDING) {
OnWriteComplete(result.error_code);
}
}
}
bool QuicChromiumPacketWriter::IsWriteBlocked() const {
return (force_write_blocked_ || write_in_progress_);
}
void QuicChromiumPacketWriter::SetWritable() {
write_in_progress_ = false;
}
std::optional<int> QuicChromiumPacketWriter::MessageTooBigErrorCode() const {
return ERR_MSG_TOO_BIG;
}
void QuicChromiumPacketWriter::OnWriteComplete(int rv) {
DCHECK_NE(rv, ERR_IO_PENDING);
write_in_progress_ = false;
if (delegate_ == nullptr)
return;
if (rv < 0) {
if (MaybeRetryAfterWriteError(rv))
return;
// If write error, then call delegate's HandleWriteError, which
// may be able to migrate and rewrite packet on a new socket.
// HandleWriteError returns the outcome of that rewrite attempt.
rv = delegate_->HandleWriteError(rv, std::move(packet_));
DCHECK(packet_ == nullptr);
if (rv == ERR_IO_PENDING) {
// Set write blocked back as write error is encountered in this writer,
// delegate may be able to handle write error but this writer will never
// be used to write any new data.
write_in_progress_ = true;
return;
}
}
if (retry_count_ != 0) {
RecordRetryCount(retry_count_);
retry_count_ = 0;
}
if (rv < 0)
delegate_->OnWriteError(rv);
else if (!force_write_blocked_)
delegate_->OnWriteUnblocked();
}
bool QuicChromiumPacketWriter::MaybeRetryAfterWriteError(int rv) {
if (rv != ERR_NO_BUFFER_SPACE)
return false;
if (retry_count_ >= kMaxRetries) {
RecordRetryCount(retry_count_);
return false;
}
retry_timer_.Start(
FROM_HERE, base::Milliseconds(UINT64_C(1) << retry_count_),
base::BindOnce(&QuicChromiumPacketWriter::RetryPacketAfterNoBuffers,
weak_factory_.GetWeakPtr()));
retry_count_++;
write_in_progress_ = true;
return true;
}
quic::QuicByteCount QuicChromiumPacketWriter::GetMaxPacketSize(
const quic::QuicSocketAddress& peer_address) const {
return quic::kMaxOutgoingPacketSize;
}
bool QuicChromiumPacketWriter::SupportsReleaseTime() const {
return false;
}
bool QuicChromiumPacketWriter::IsBatchMode() const {
return false;
}
bool QuicChromiumPacketWriter::SupportsEcn() const {
return true;
}
quic::QuicPacketBuffer QuicChromiumPacketWriter::GetNextWriteLocation(
const quiche::QuicheIpAddress& self_address,
const quic::QuicSocketAddress& peer_address) {
return {nullptr, nullptr};
}
quic::WriteResult QuicChromiumPacketWriter::Flush() {
return quic::WriteResult(quic::WRITE_STATUS_OK, 0);
}
bool QuicChromiumPacketWriter::OnSocketClosed(DatagramClientSocket* socket) {
if (socket_ == socket) {
socket_ = nullptr;
return true;
}
return false;
}
void QuicChromiumPacketWriter::RegisterQuicConnectionClosePayload(
base::span<uint8_t> payload) {
if (socket_) {
socket_->RegisterQuicConnectionClosePayload(payload);
}
}
void QuicChromiumPacketWriter::UnregisterQuicConnectionClosePayload() {
if (socket_) {
socket_->UnregisterQuicConnectionClosePayload();
}
}
} // namespace net
|