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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
|
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/quic_socket_data_provider.h"
#include <algorithm>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include "base/functional/callback.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "net/base/hex_utils.h"
#include "net/socket/socket_test_util.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/null_encrypter.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/quic_crypto_server_config.h"
#include "net/third_party/quiche/src/quiche/quic/core/http/quic_spdy_session.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_packets.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_time.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_versions.h"
#include "net/third_party/quiche/src/quiche/quic/test_tools/crypto_test_utils.h"
#include "net/third_party/quiche/src/quiche/quic/test_tools/quic_test_utils.h"
#include "net/third_party/quiche/src/quiche/quic/tools/quic_simple_server_session.h"
namespace quic {
namespace {
class HttpStreamPrinter : public Http3DebugVisitor {
public:
explicit HttpStreamPrinter(std::ostream* output) : output_(output) {}
void OnControlStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnControlStreamCreated: " << stream_id << "\n";
}
}
void OnQpackEncoderStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnQpackEncoderStreamCreated: " << stream_id << "\n";
}
}
void OnQpackDecoderStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnQpackDecoderStreamCreated: " << stream_id << "\n";
}
}
void OnPeerControlStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnPeerControlStreamCreated: " << stream_id << "\n";
}
}
void OnPeerQpackEncoderStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnPeerQpackEncoderStreamCreated: " << stream_id << "\n";
}
}
void OnPeerQpackDecoderStreamCreated(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnPeerQpackDecoderStreamCreated: " << stream_id << "\n";
}
}
void OnSettingsFrameReceived(const SettingsFrame& frame) override {
if (output_) {
*output_ << "OnSettingsFrameReceived: " << frame << "\n";
}
}
void OnGoAwayFrameReceived(const GoAwayFrame& frame) override {
if (output_) {
*output_ << "OnGoAwayFrameReceived" << "\n";
}
}
void OnPriorityUpdateFrameReceived(
const PriorityUpdateFrame& frame) override {
if (output_) {
*output_ << "OnPriorityUpdateFrameReceived: " << frame << "\n";
}
}
void OnDataFrameReceived(QuicStreamId stream_id,
QuicByteCount payload_length) override {
if (output_) {
*output_ << "OnDataFrameReceived: " << stream_id << ", "
<< "received: " << payload_length << " bytes" << "\n";
}
}
void OnHeadersFrameReceived(
QuicStreamId stream_id,
QuicByteCount compressed_headers_length) override {
if (output_) {
*output_ << "OnHeadersFrameReceived: " << stream_id << ", "
<< "received: " << compressed_headers_length << " bytes" << "\n";
}
}
void OnHeadersDecoded(QuicStreamId stream_id,
QuicHeaderList headers) override {
if (output_) {
*output_ << "OnHeadersDecoded: " << stream_id << ", "
<< "received: " << headers.DebugString() << "\n";
}
}
void OnUnknownFrameReceived(QuicStreamId stream_id,
uint64_t frame_type,
QuicByteCount payload_length) override {
if (output_) {
*output_ << "OnUnknownFrameReceived: " << stream_id << ", "
<< "frame_type: " << frame_type << ","
<< "received: " << payload_length << "bytes " << "\n ";
}
}
void OnSettingsFrameSent(const SettingsFrame& frame) override {
if (output_) {
*output_ << "OnSettingsFrameSent: " << frame << "\n";
}
}
void OnSettingsFrameResumed(const SettingsFrame& frame) override {
if (output_) {
*output_ << "OnSettingsFrameResumed: " << frame << "\n";
}
}
void OnGoAwayFrameSent(QuicStreamId stream_id) override {
if (output_) {
*output_ << "OnGoAwayFrameSent: " << stream_id << "\n";
}
}
void OnPriorityUpdateFrameSent(const PriorityUpdateFrame& frame) override {
if (output_) {
*output_ << "OnPriorityUpdateFrameSent: " << frame << "\n";
}
}
void OnDataFrameSent(QuicStreamId stream_id,
QuicByteCount payload_length) override {
if (output_) {
*output_ << "OnDataFrameSent: " << stream_id << ", "
<< "sent: " << payload_length << " bytes" << "\n";
}
}
void OnHeadersFrameSent(
QuicStreamId stream_id,
const quiche::HttpHeaderBlock& header_block) override {
if (output_) {
*output_ << "OnHeadersFrameSent: " << stream_id << ", "
<< "sent: " << header_block.DebugString() << "\n";
}
}
private:
mutable raw_ptr<std::ostream> output_ = nullptr;
};
} // namespace
} // namespace quic
namespace net::test {
QuicSimpleServerSessionForTest::~QuicSimpleServerSessionForTest() = default;
// Always return true if CryptoStream is created, so that the pending stream can
// handle initial setting frames for tests.
bool QuicSimpleServerSessionForTest::IsEncryptionEstablished() const {
return GetCryptoStream() != nullptr;
}
QuicSocketDataProvider::Expectation::Expectation(
std::string name,
Type type,
int rv,
std::unique_ptr<quic::QuicEncryptedPacket> packet)
: name_(std::move(name)),
type_(type),
rv_(rv),
packet_(std::move(packet)) {}
QuicSocketDataProvider::Expectation::Expectation(
QuicSocketDataProvider::Expectation&&) = default;
QuicSocketDataProvider::Expectation::~Expectation() = default;
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::Expectation::After(
std::string name) {
after_.insert(std::move(name));
return *this;
}
std::string QuicSocketDataProvider::Expectation::TypeToString(
QuicSocketDataProvider::Expectation::Type type) {
switch (type) {
case Expectation::Type::READ:
return "READ";
case Expectation::Type::WRITE:
return "WRITE";
case Expectation::Type::PAUSE:
return "PAUSE";
}
NOTREACHED();
}
void QuicSocketDataProvider::Expectation::Consume() {
CHECK(!consumed_);
VLOG(1) << "Consuming " << TypeToString(type_) << " expectation " << name_;
consumed_ = true;
}
QuicSocketDataProvider::QuicSocketDataProvider(quic::ParsedQuicVersion version)
: printer_(version),
crypto_config_(quic::QuicCryptoServerConfig::TESTING,
quic::QuicRandom::GetInstance(),
quic::test::crypto_test_utils::ProofSourceForTesting(),
quic::KeyExchangeSource::Default()),
compressed_certs_cache_(
quic::QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) {
session_for_actual_ = GenSimpleServerSession();
session_for_expected_ = GenSimpleServerSession();
}
QuicSocketDataProvider::~QuicSocketDataProvider() = default;
std::unique_ptr<quic::QuicSimpleServerSession>
QuicSocketDataProvider::GenSimpleServerSession() {
quic::test::MockQuicConnection* connection =
new quic::test::MockQuicConnection( // IN-TEST
&helper_, &alarm_factory_, quic::Perspective::IS_SERVER);
connection->AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
connection->SetEncrypter(
quic::ENCRYPTION_FORWARD_SECURE,
std::make_unique<quic::NullEncrypter>(connection->perspective()));
std::unique_ptr<QuicSimpleServerSessionForTest> session =
std::make_unique<QuicSimpleServerSessionForTest>(
config_, quic::CurrentSupportedVersions(), connection, &owner_,
&stream_helper_, &crypto_config_, &compressed_certs_cache_,
&memory_cache_backend_);
session->Initialize();
return session;
}
std::string QuicSocketDataProvider::PrintWithQuicSession(
quic::QuicSimpleServerSession* session,
std::string data) {
std::ostringstream output;
quic::HttpStreamPrinter printer(&output);
session->set_debug_visitor(&printer);
std::string res = printer_.PrintWithQuicSession(data, output, session);
session->set_debug_visitor(nullptr);
return res;
}
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::AddRead(
std::string name,
std::unique_ptr<quic::QuicEncryptedPacket> packet) {
expectations_.push_back(Expectation(std::move(name), Expectation::Type::READ,
OK, std::move(packet)));
return expectations_.back();
}
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::AddRead(
std::string name,
std::unique_ptr<quic::QuicReceivedPacket> packet) {
uint8_t tos_byte = static_cast<uint8_t>(packet->ecn_codepoint());
return AddRead(std::move(name),
static_cast<std::unique_ptr<quic::QuicEncryptedPacket>>(
std::move(packet)))
.TosByte(tos_byte);
}
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::AddReadError(
std::string name,
int rv) {
CHECK_NE(rv, OK);
CHECK_NE(rv, ERR_IO_PENDING);
expectations_.push_back(
Expectation(std::move(name), Expectation::Type::READ, rv, nullptr));
return expectations_.back();
}
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::AddWrite(
std::string name,
std::unique_ptr<quic::QuicEncryptedPacket> packet,
int rv) {
expectations_.push_back(Expectation(std::move(name), Expectation::Type::WRITE,
rv, std::move(packet)));
return expectations_.back();
}
QuicSocketDataProvider::Expectation& QuicSocketDataProvider::AddWriteError(
std::string name,
int rv) {
CHECK_NE(rv, OK);
CHECK_NE(rv, ERR_IO_PENDING);
expectations_.push_back(
Expectation(std::move(name), Expectation::Type::WRITE, rv, nullptr));
return expectations_.back();
}
QuicSocketDataProvider::PausePoint QuicSocketDataProvider::AddPause(
std::string name) {
expectations_.push_back(
Expectation(std::move(name), Expectation::Type::PAUSE, OK, nullptr));
return expectations_.size() - 1;
}
bool QuicSocketDataProvider::AllDataConsumed() const {
return std::all_of(
expectations_.begin(), expectations_.end(),
[](const Expectation& expectation) { return expectation.consumed(); });
}
void QuicSocketDataProvider::RunUntilPause(
QuicSocketDataProvider::PausePoint pause_point) {
if (!paused_at_.has_value()) {
run_until_run_loop_ = std::make_unique<base::RunLoop>();
run_until_run_loop_->Run();
run_until_run_loop_.reset();
}
CHECK(paused_at_.has_value() && *paused_at_ == pause_point)
<< "Did not pause at '" << expectations_[pause_point].name() << "'.";
}
void QuicSocketDataProvider::Resume() {
CHECK(paused_at_.has_value());
VLOG(1) << "Resuming from pause point " << expectations_[*paused_at_].name();
expectations_[*paused_at_].Consume();
paused_at_ = std::nullopt;
ExpectationConsumed();
}
void QuicSocketDataProvider::RunUntilAllConsumed() {
if (!AllDataConsumed()) {
run_until_run_loop_ = std::make_unique<base::RunLoop>();
run_until_run_loop_->Run();
run_until_run_loop_.reset();
}
// If that run timed out, then there will still be un-consumed data.
if (!AllDataConsumed()) {
std::vector<size_t> unconsumed;
for (size_t i = 0; i < expectations_.size(); i++) {
if (!expectations_[i].consumed()) {
unconsumed.push_back(i);
}
}
FAIL() << "All expectations were not consumed; remaining: "
<< ExpectationList(unconsumed);
}
}
MockRead QuicSocketDataProvider::OnRead() {
CHECK(!read_pending_);
read_pending_ = true;
std::optional<MockRead> next_read = ConsumeNextRead();
if (!next_read.has_value()) {
return MockRead(ASYNC, ERR_IO_PENDING);
}
read_pending_ = false;
return *next_read;
}
MockWriteResult QuicSocketDataProvider::OnWrite(const std::string& data) {
CHECK(!write_pending_.has_value());
write_pending_ = data;
std::optional<MockWriteResult> next_write = ConsumeNextWrite();
if (!next_write.has_value()) {
// If Write() was called when no corresponding expectation exists, that's
// an error unless execution is currently paused, in which case it's just
// pending. This rarely occurs because the only other type of expectation
// that might be blocking a WRITE is a READ, and QUIC implementations
// typically eagerly consume READs.
if (paused_at_.has_value()) {
return MockWriteResult(ASYNC, ERR_IO_PENDING);
} else {
ADD_FAILURE() << "Write call when none is expected:\n"
<< printer_.PrintWrite(data);
return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
}
}
write_pending_ = std::nullopt;
return *next_write;
}
bool QuicSocketDataProvider::AllReadDataConsumed() const {
return AllDataConsumed();
}
bool QuicSocketDataProvider::AllWriteDataConsumed() const {
return AllDataConsumed();
}
void QuicSocketDataProvider::CancelPendingRead() {
read_pending_ = false;
}
void QuicSocketDataProvider::Reset() {
// Note that `Reset` is a parent-class method with a confusing name. It is
// used to initialize the socket data provider before it is used.
// Map names to index, and incidentally check for duplicate names.
std::map<std::string, size_t> names;
for (size_t i = 0; i < expectations_.size(); i++) {
Expectation& expectation = expectations_[i];
auto [_, inserted] = names.insert({expectation.name(), i});
CHECK(inserted) << "Another expectation named " << expectation.name()
<< " exists.";
}
// Calculate `dependencies_` mapping indices in `expectations_` to indices
// of the expectations they depend on.
dependencies_.clear();
for (size_t i = 0; i < expectations_.size(); i++) {
Expectation& expectation = expectations_[i];
if (expectation.after().empty()) {
// If no other dependencies are given, make the expectation depend on
// the previous expectation.
if (i > 0) {
dependencies_[i].insert(i - 1);
}
} else {
for (auto& after : expectation.after()) {
const auto dep = names.find(after);
CHECK(dep != names.end()) << "No expectation named " << after;
dependencies_[i].insert(dep->second);
}
}
}
pending_maybe_consume_expectations_ = false;
read_pending_ = false;
write_pending_ = std::nullopt;
MaybeConsumeExpectations();
}
std::optional<size_t> QuicSocketDataProvider::FindReadyExpectations(
Expectation::Type type) {
std::vector<size_t> matches;
for (size_t i = 0; i < expectations_.size(); i++) {
const Expectation& expectation = expectations_[i];
if (expectation.consumed() || expectation.type() != type) {
continue;
}
bool found_unconsumed = false;
for (auto dep : dependencies_[i]) {
if (!expectations_[dep].consumed_) {
found_unconsumed = true;
break;
}
}
if (!found_unconsumed) {
matches.push_back(i);
}
}
if (matches.size() > 1) {
std::string exp_type = Expectation::TypeToString(type);
std::string names = ExpectationList(matches);
CHECK(matches.size() <= 1)
<< "Multiple expectations of type " << exp_type
<< " are ready: " << names << ". Use .After() to disambiguate.";
}
return matches.empty() ? std::nullopt : std::make_optional(matches[0]);
}
std::optional<MockRead> QuicSocketDataProvider::ConsumeNextRead() {
CHECK(read_pending_);
std::optional<size_t> ready = FindReadyExpectations(Expectation::Type::READ);
if (!ready.has_value()) {
return std::nullopt;
}
// If there's exactly one matching expectation, return it.
Expectation& ready_expectation = expectations_[*ready];
MockRead read(ready_expectation.mode(), ready_expectation.rv());
if (ready_expectation.packet()) {
read.data = ready_expectation.packet()->AsStringPiece();
}
read.tos = ready_expectation.tos_byte();
ready_expectation.Consume();
ExpectationConsumed();
return read;
}
std::optional<MockWriteResult> QuicSocketDataProvider::ConsumeNextWrite() {
CHECK(write_pending_.has_value());
std::optional<size_t> ready = FindReadyExpectations(Expectation::Type::WRITE);
if (!ready.has_value()) {
return std::nullopt;
}
// If there's exactly one matching expectation, check if it matches the
// write and return it.
Expectation& ready_expectation = expectations_[*ready];
if (ready_expectation.packet()) {
if (!VerifyWriteData(ready_expectation)) {
return MockWriteResult(SYNCHRONOUS, ERR_UNEXPECTED);
}
}
MockWriteResult write(ready_expectation.mode(),
ready_expectation.packet()
? ready_expectation.packet()->length()
: ready_expectation.rv());
ready_expectation.Consume();
ExpectationConsumed();
return write;
}
void QuicSocketDataProvider::MaybeConsumeExpectations() {
pending_maybe_consume_expectations_ = false;
if (read_pending_) {
std::optional<MockRead> next_read = ConsumeNextRead();
if (next_read.has_value()) {
read_pending_ = false;
if (socket()) {
socket()->OnReadComplete(*next_read);
}
}
}
if (write_pending_.has_value()) {
std::optional<MockWriteResult> next_write = ConsumeNextWrite();
if (next_write.has_value()) {
write_pending_ = std::nullopt;
if (socket()) {
socket()->OnWriteComplete(next_write->result);
}
}
}
if (!paused_at_) {
std::optional<size_t> ready =
FindReadyExpectations(Expectation::Type::PAUSE);
if (ready.has_value()) {
VLOG(1) << "Pausing at " << expectations_[*ready].name();
paused_at_ = *ready;
if (run_until_run_loop_) {
run_until_run_loop_->Quit();
}
}
}
if (run_until_run_loop_ && AllDataConsumed()) {
run_until_run_loop_->Quit();
}
}
void QuicSocketDataProvider::ExpectationConsumed() {
if (pending_maybe_consume_expectations_) {
return;
}
pending_maybe_consume_expectations_ = true;
// Call `MaybeConsumeExpectations` in a task. That method may trigger
// consumption of other expectations, and that consumption must happen
// _after_ the current call to `Read` or `Write` has finished.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&QuicSocketDataProvider::MaybeConsumeExpectations,
weak_factory_.GetWeakPtr()));
}
bool QuicSocketDataProvider::VerifyWriteData(
QuicSocketDataProvider::Expectation& expectation) {
std::string expected_data(expectation.packet()->data(),
expectation.packet()->length());
std::string& actual_data = *write_pending_;
actual_log_.append(
PrintWithQuicSession(session_for_actual_.get(), actual_data));
expected_log_.append(
PrintWithQuicSession(session_for_expected_.get(), expected_data));
bool write_matches = actual_data == expected_data;
EXPECT_TRUE(write_matches)
<< "Expectation '" << expectation.name()
<< "' not met. Actual formatted write data:\n"
<< actual_log_ << "But expectation '" << expectation.name()
<< "' expected formatted write data:\n"
<< expected_log_ << "Actual raw write data:\n"
<< HexDump(actual_data) << "Expected raw write data:\n"
<< HexDump(expected_data);
return write_matches;
}
std::string QuicSocketDataProvider::ExpectationList(
const std::vector<size_t>& indices) {
std::ostringstream names;
bool first = true;
for (auto i : indices) {
names << (first ? "" : ", ") << expectations_[i].name();
first = false;
}
return names.str();
}
} // namespace net::test
|