ID
int64
0
2.65k
Language
stringclasses
1 value
Repository Name
stringclasses
14 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
16
116
Code
stringlengths
411
31.4k
Unit Test - (Ground Truth)
stringlengths
40
32.1k
200
cpp
google/quiche
quic_libevent
quiche/quic/bindings/quic_libevent.cc
quiche/quic/bindings/quic_libevent_test.cc
#ifndef QUICHE_QUIC_BINDINGS_QUIC_LIBEVENT_H_ #define QUICHE_QUIC_BINDINGS_QUIC_LIBEVENT_H_ #include <memory> #include <optional> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/container/node_hash_map.h" #include "event2/event.h" #include "event2/event_struct.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_udp_socket.h" namespace quic { struct QUICHE_NO_EXPORT LibeventEventDeleter { void operator()(event* ev) { event_free(ev); } }; class QUICHE_EXPORT LibeventQuicEventLoop : public QuicEventLoop { public: explicit LibeventQuicEventLoop(event_base* base, QuicClock* clock); ~LibeventQuicEventLoop() override; bool SupportsEdgeTriggered() const override { return edge_triggered_; } std::unique_ptr<QuicAlarmFactory> CreateAlarmFactory() override { return std::make_unique<AlarmFactory>(this); } bool RegisterSocket(QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) override; bool UnregisterSocket(QuicUdpSocketFd fd) override; bool RearmSocket(QuicUdpSocketFd fd, QuicSocketEventMask events) override; bool ArtificiallyNotifyEvent(QuicUdpSocketFd fd, QuicSocketEventMask events) override; void RunEventLoopOnce(QuicTime::Delta default_timeout) override; const QuicClock* GetClock() override { return clock_; } void WakeUp(); event_base* base() { return base_; } QuicClock* clock() const { return clock_; } private: void ActivateArtificialEvents(); class AlarmFactory : public QuicAlarmFactory { public: AlarmFactory(LibeventQuicEventLoop* loop) : loop_(loop) {} QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override; QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override; private: LibeventQuicEventLoop* loop_; }; class Registration { public: Registration(LibeventQuicEventLoop* loop, QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener); ~Registration(); void Rearm(QuicSocketEventMask events); void RecordArtificalEvents(QuicSocketEventMask events); void MaybeNotifyArtificalEvents(); private: LibeventQuicEventLoop* loop_; QuicSocketEventListener* listener_; event both_events_; event read_event_; event write_event_; QuicSocketEventMask artificial_events_ = 0; }; using RegistrationMap = absl::node_hash_map<QuicUdpSocketFd, Registration>; event_base* base_; const bool edge_triggered_; QuicClock* clock_; RegistrationMap registration_map_; std::unique_ptr<event, LibeventEventDeleter> artifical_event_timer_; absl::flat_hash_set<QuicUdpSocketFd> fds_with_artifical_events_; }; class QUICHE_EXPORT LibeventLoop { public: LibeventLoop(struct event_base* base) : event_base_(base) {} ~LibeventLoop() { event_base_free(event_base_); } struct event_base* event_base() { return event_base_; } private: struct event_base* event_base_; }; class QUICHE_EXPORT LibeventQuicEventLoopWithOwnership : public LibeventLoop, public LibeventQuicEventLoop { public: static std::unique_ptr<LibeventQuicEventLoopWithOwnership> Create( QuicClock* clock, bool force_level_triggered = false); explicit LibeventQuicEventLoopWithOwnership(struct event_base* base, QuicClock* clock) : LibeventLoop(base), LibeventQuicEventLoop(base, clock) {} }; class QUICHE_EXPORT QuicLibeventEventLoopFactory : public QuicEventLoopFactory { public: static QuicLibeventEventLoopFactory* Get() { static QuicLibeventEventLoopFactory* factory = new QuicLibeventEventLoopFactory(false); return factory; } static QuicLibeventEventLoopFactory* GetLevelTriggeredBackendForTests() { static QuicLibeventEventLoopFactory* factory = new QuicLibeventEventLoopFactory(true); return factory; } std::unique_ptr<QuicEventLoop> Create(QuicClock* clock) override { return LibeventQuicEventLoopWithOwnership::Create(clock, force_level_triggered_); } std::string GetName() const override { return name_; } private: explicit QuicLibeventEventLoopFactory(bool force_level_triggered); bool force_level_triggered_; std::string name_; }; } #endif #include "quiche/quic/bindings/quic_libevent.h" #include <memory> #include <utility> #include "absl/time/time.h" #include "event2/event.h" #include "event2/event_struct.h" #include "event2/thread.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_time.h" namespace quic { using LibeventEventMask = short; QuicSocketEventMask LibeventEventMaskToQuicEvents(int events) { return ((events & EV_READ) ? kSocketEventReadable : 0) | ((events & EV_WRITE) ? kSocketEventWritable : 0); } LibeventEventMask QuicEventsToLibeventEventMask(QuicSocketEventMask events) { return ((events & kSocketEventReadable) ? EV_READ : 0) | ((events & kSocketEventWritable) ? EV_WRITE : 0); } class LibeventAlarm : public QuicAlarm { public: LibeventAlarm(LibeventQuicEventLoop* loop, QuicArenaScopedPtr<QuicAlarm::Delegate> delegate) : QuicAlarm(std::move(delegate)), clock_(loop->clock()) { event_.reset(evtimer_new( loop->base(), [](evutil_socket_t, LibeventEventMask, void* arg) { LibeventAlarm* self = reinterpret_cast<LibeventAlarm*>(arg); self->Fire(); }, this)); } protected: void SetImpl() override { absl::Duration timeout = absl::Microseconds((deadline() - clock_->Now()).ToMicroseconds()); timeval unix_time = absl::ToTimeval(timeout); event_add(event_.get(), &unix_time); } void CancelImpl() override { event_del(event_.get()); } private: std::unique_ptr<event, LibeventEventDeleter> event_; QuicClock* clock_; }; LibeventQuicEventLoop::LibeventQuicEventLoop(event_base* base, QuicClock* clock) : base_(base), edge_triggered_(event_base_get_features(base) & EV_FEATURE_ET), clock_(clock), artifical_event_timer_(evtimer_new( base_, [](evutil_socket_t, LibeventEventMask, void* arg) { auto* self = reinterpret_cast<LibeventQuicEventLoop*>(arg); self->ActivateArtificialEvents(); }, this)) { QUICHE_CHECK_LE(sizeof(event), event_get_struct_event_size()) << "libevent ABI mismatch: sizeof(event) is bigger than the one QUICHE " "has been compiled with"; } LibeventQuicEventLoop::~LibeventQuicEventLoop() { event_del(artifical_event_timer_.get()); } bool LibeventQuicEventLoop::RegisterSocket(QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) { auto [it, success] = registration_map_.try_emplace(fd, this, fd, events, listener); return success; } bool LibeventQuicEventLoop::UnregisterSocket(QuicUdpSocketFd fd) { fds_with_artifical_events_.erase(fd); return registration_map_.erase(fd); } bool LibeventQuicEventLoop::RearmSocket(QuicUdpSocketFd fd, QuicSocketEventMask events) { if (edge_triggered_) { QUICHE_BUG(LibeventQuicEventLoop_RearmSocket_called_on_ET) << "RearmSocket() called on an edge-triggered event loop"; return false; } auto it = registration_map_.find(fd); if (it == registration_map_.end()) { return false; } it->second.Rearm(events); return true; } bool LibeventQuicEventLoop::ArtificiallyNotifyEvent( QuicUdpSocketFd fd, QuicSocketEventMask events) { auto it = registration_map_.find(fd); if (it == registration_map_.end()) { return false; } it->second.RecordArtificalEvents(events); fds_with_artifical_events_.insert(fd); if (!evtimer_pending(artifical_event_timer_.get(), nullptr)) { struct timeval tv = {0, 0}; evtimer_add(artifical_event_timer_.get(), &tv); } return true; } void LibeventQuicEventLoop::ActivateArtificialEvents() { absl::flat_hash_set<QuicUdpSocketFd> fds_with_artifical_events; { using std::swap; swap(fds_with_artifical_events_, fds_with_artifical_events); } for (QuicUdpSocketFd fd : fds_with_artifical_events) { auto it = registration_map_.find(fd); if (it == registration_map_.end()) { continue; } it->second.MaybeNotifyArtificalEvents(); } } void LibeventQuicEventLoop::RunEventLoopOnce(QuicTime::Delta default_timeout) { timeval timeout = absl::ToTimeval(absl::Microseconds(default_timeout.ToMicroseconds())); event_base_loopexit(base_, &timeout); event_base_loop(base_, EVLOOP_ONCE); } void LibeventQuicEventLoop::WakeUp() { timeval timeout = absl::ToTimeval(absl::ZeroDuration()); event_base_loopexit(base_, &timeout); } LibeventQuicEventLoop::Registration::Registration( LibeventQuicEventLoop* loop, QuicUdpSocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) : loop_(loop), listener_(listener) { event_callback_fn callback = [](evutil_socket_t fd, LibeventEventMask events, void* arg) { auto* self = reinterpret_cast<LibeventQuicEventLoop::Registration*>(arg); self->listener_->OnSocketEvent(self->loop_, fd, LibeventEventMaskToQuicEvents(events)); }; if (loop_->SupportsEdgeTriggered()) { LibeventEventMask mask = QuicEventsToLibeventEventMask(events) | EV_PERSIST | EV_ET; event_assign(&both_events_, loop_->base(), fd, mask, callback, this); event_add(&both_events_, nullptr); } else { event_assign(&read_event_, loop_->base(), fd, EV_READ, callback, this); event_assign(&write_event_, loop_->base(), fd, EV_WRITE, callback, this); Rearm(events); } } LibeventQuicEventLoop::Registration::~Registration() { if (loop_->SupportsEdgeTriggered()) { event_del(&both_events_); } else { event_del(&read_event_); event_del(&write_event_); } } void LibeventQuicEventLoop::Registration::RecordArtificalEvents( QuicSocketEventMask events) { artificial_events_ |= events; } void LibeventQuicEventLoop::Registration::MaybeNotifyArtificalEvents() { if (artificial_events_ == 0) { return; } QuicSocketEventMask events = artificial_events_; artificial_events_ = 0; if (loop_->SupportsEdgeTriggered()) { event_active(&both_events_, QuicEventsToLibeventEventMask(events), 0); return; } if (events & kSocketEventReadable) { event_active(&read_event_, EV_READ, 0); } if (events & kSocketEventWritable) { event_active(&write_event_, EV_WRITE, 0); } } void LibeventQuicEventLoop::Registration::Rearm(QuicSocketEventMask events) { QUICHE_DCHECK(!loop_->SupportsEdgeTriggered()); if (events & kSocketEventReadable) { event_add(&read_event_, nullptr); } if (events & kSocketEventWritable) { event_add(&write_event_, nullptr); } } QuicAlarm* LibeventQuicEventLoop::AlarmFactory::CreateAlarm( QuicAlarm::Delegate* delegate) { return new LibeventAlarm(loop_, QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)); } QuicArenaScopedPtr<QuicAlarm> LibeventQuicEventLoop::AlarmFactory::CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) { if (arena != nullptr) { return arena->New<LibeventAlarm>(loop_, std::move(delegate)); } return QuicArenaScopedPtr<QuicAlarm>( new LibeventAlarm(loop_, std::move(delegate))); } QuicLibeventEventLoopFactory::QuicLibeventEventLoopFactory( bool force_level_triggered) : force_level_triggered_(force_level_triggered) { std::unique_ptr<QuicEventLoop> event_loop = Create(QuicDefaultClock::Get()); name_ = absl::StrFormat( "libevent(%s)", event_base_get_method( static_cast<LibeventQuicEventLoopWithOwnership*>(event_loop.get()) ->base())); } struct LibeventConfigDeleter { void operator()(event_config* config) { event_config_free(config); } }; std::unique_ptr<LibeventQuicEventLoopWithOwnership> LibeventQuicEventLoopWithOwnership::Create(QuicClock* clock, bool force_level_triggered) { static int threads_initialized = []() { #ifdef _WIN32 return evthread_use_windows_threads(); #else return evthread_use_pthreads(); #endif }(); QUICHE_DCHECK_EQ(threads_initialized, 0); std::unique_ptr<event_config, LibeventConfigDeleter> config( event_config_new()); if (force_level_triggered) { event_config_avoid_method(config.get(), "epoll"); event_config_avoid_method(config.get(), "kqueue"); } return std::make_unique<LibeventQuicEventLoopWithOwnership>( event_base_new_with_config(config.get()), clock); } }
#include "quiche/quic/bindings/quic_libevent.h" #include <atomic> #include <memory> #include "absl/memory/memory.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_thread.h" namespace quic::test { namespace { class FailureAlarmDelegate : public QuicAlarm::Delegate { public: QuicConnectionContext* GetConnectionContext() override { return nullptr; } void OnAlarm() override { ADD_FAILURE() << "Test timed out"; } }; class LoopBreakThread : public QuicThread { public: LoopBreakThread(LibeventQuicEventLoop* loop) : QuicThread("LoopBreakThread"), loop_(loop) {} void Run() override { absl::SleepFor(absl::Milliseconds(250)); loop_broken_.store(true); loop_->WakeUp(); } std::atomic<int>& loop_broken() { return loop_broken_; } private: LibeventQuicEventLoop* loop_; std::atomic<int> loop_broken_ = 0; }; TEST(QuicLibeventTest, WakeUpFromAnotherThread) { QuicClock* clock = QuicDefaultClock::Get(); auto event_loop_owned = QuicLibeventEventLoopFactory::Get()->Create(clock); LibeventQuicEventLoop* event_loop = static_cast<LibeventQuicEventLoop*>(event_loop_owned.get()); std::unique_ptr<QuicAlarmFactory> alarm_factory = event_loop->CreateAlarmFactory(); std::unique_ptr<QuicAlarm> timeout_alarm = absl::WrapUnique(alarm_factory->CreateAlarm(new FailureAlarmDelegate())); const QuicTime kTimeoutAt = clock->Now() + QuicTime::Delta::FromSeconds(10); timeout_alarm->Set(kTimeoutAt); LoopBreakThread thread(event_loop); thread.Start(); event_loop->RunEventLoopOnce(QuicTime::Delta::FromSeconds(5 * 60)); EXPECT_TRUE(thread.loop_broken().load()); thread.Join(); } } }
201
cpp
google/quiche
quic_socket_address
quiche/quic/platform/api/quic_socket_address.cc
quiche/quic/platform/api/quic_socket_address_test.cc
#ifndef QUICHE_QUIC_PLATFORM_API_QUIC_SOCKET_ADDRESS_H_ #define QUICHE_QUIC_PLATFORM_API_QUIC_SOCKET_ADDRESS_H_ #include <string> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_ip_address.h" namespace quic { class QUIC_EXPORT_PRIVATE QuicSocketAddress { public: QuicSocketAddress() {} QuicSocketAddress(QuicIpAddress address, uint16_t port); explicit QuicSocketAddress(const struct sockaddr_storage& saddr); explicit QuicSocketAddress(const sockaddr* saddr, socklen_t len); QuicSocketAddress(const QuicSocketAddress& other) = default; QuicSocketAddress& operator=(const QuicSocketAddress& other) = default; QuicSocketAddress& operator=(QuicSocketAddress&& other) = default; QUIC_EXPORT_PRIVATE friend bool operator==(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs); QUIC_EXPORT_PRIVATE friend bool operator!=(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs); bool IsInitialized() const; std::string ToString() const; int FromSocket(int fd); QuicSocketAddress Normalized() const; QuicIpAddress host() const; uint16_t port() const; sockaddr_storage generic_address() const; uint32_t Hash() const; private: QuicIpAddress host_; uint16_t port_ = 0; }; inline std::ostream& operator<<(std::ostream& os, const QuicSocketAddress address) { os << address.ToString(); return os; } class QUIC_EXPORT_PRIVATE QuicSocketAddressHash { public: size_t operator()(QuicSocketAddress const& address) const noexcept { return address.Hash(); } }; } #endif #include "quiche/quic/platform/api/quic_socket_address.h" #include <cstring> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" namespace quic { namespace { uint32_t HashIP(const QuicIpAddress& ip) { if (ip.IsIPv4()) { return ip.GetIPv4().s_addr; } if (ip.IsIPv6()) { auto v6addr = ip.GetIPv6(); const uint32_t* v6_as_ints = reinterpret_cast<const uint32_t*>(&v6addr.s6_addr); return v6_as_ints[0] ^ v6_as_ints[1] ^ v6_as_ints[2] ^ v6_as_ints[3]; } return 0; } } QuicSocketAddress::QuicSocketAddress(QuicIpAddress address, uint16_t port) : host_(address), port_(port) {} QuicSocketAddress::QuicSocketAddress(const struct sockaddr_storage& saddr) { switch (saddr.ss_family) { case AF_INET: { const sockaddr_in* v4 = reinterpret_cast<const sockaddr_in*>(&saddr); host_ = QuicIpAddress(v4->sin_addr); port_ = ntohs(v4->sin_port); break; } case AF_INET6: { const sockaddr_in6* v6 = reinterpret_cast<const sockaddr_in6*>(&saddr); host_ = QuicIpAddress(v6->sin6_addr); port_ = ntohs(v6->sin6_port); break; } default: QUIC_BUG(quic_bug_10075_1) << "Unknown address family passed: " << saddr.ss_family; break; } } QuicSocketAddress::QuicSocketAddress(const sockaddr* saddr, socklen_t len) { sockaddr_storage storage; static_assert(std::numeric_limits<socklen_t>::max() >= sizeof(storage), "Cannot cast sizeof(storage) to socklen_t as it does not fit"); if (len < static_cast<socklen_t>(sizeof(sockaddr)) || (saddr->sa_family == AF_INET && len < static_cast<socklen_t>(sizeof(sockaddr_in))) || (saddr->sa_family == AF_INET6 && len < static_cast<socklen_t>(sizeof(sockaddr_in6))) || len > static_cast<socklen_t>(sizeof(storage))) { QUIC_BUG(quic_bug_10075_2) << "Socket address of invalid length provided"; return; } memcpy(&storage, saddr, len); *this = QuicSocketAddress(storage); } bool operator==(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) { return lhs.host_ == rhs.host_ && lhs.port_ == rhs.port_; } bool operator!=(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) { return !(lhs == rhs); } bool QuicSocketAddress::IsInitialized() const { return host_.IsInitialized(); } std::string QuicSocketAddress::ToString() const { switch (host_.address_family()) { case IpAddressFamily::IP_V4: return absl::StrCat(host_.ToString(), ":", port_); case IpAddressFamily::IP_V6: return absl::StrCat("[", host_.ToString(), "]:", port_); default: return ""; } } int QuicSocketAddress::FromSocket(int fd) { sockaddr_storage addr; socklen_t addr_len = sizeof(addr); int result = getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &addr_len); bool success = result == 0 && addr_len > 0 && static_cast<size_t>(addr_len) <= sizeof(addr); if (success) { *this = QuicSocketAddress(addr); return 0; } return -1; } QuicSocketAddress QuicSocketAddress::Normalized() const { return QuicSocketAddress(host_.Normalized(), port_); } QuicIpAddress QuicSocketAddress::host() const { return host_; } uint16_t QuicSocketAddress::port() const { return port_; } sockaddr_storage QuicSocketAddress::generic_address() const { union { sockaddr_storage storage; sockaddr_in v4; sockaddr_in6 v6; } result; memset(&result.storage, 0, sizeof(result.storage)); switch (host_.address_family()) { case IpAddressFamily::IP_V4: result.v4.sin_family = AF_INET; result.v4.sin_addr = host_.GetIPv4(); result.v4.sin_port = htons(port_); break; case IpAddressFamily::IP_V6: result.v6.sin6_family = AF_INET6; result.v6.sin6_addr = host_.GetIPv6(); result.v6.sin6_port = htons(port_); break; default: result.storage.ss_family = AF_UNSPEC; break; } return result.storage; } uint32_t QuicSocketAddress::Hash() const { uint32_t value = 0; value ^= HashIP(host_); value ^= port_ | (port_ << 16); return value; } }
#include "quiche/quic/platform/api/quic_socket_address.h" #include <memory> #include <sstream> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(QuicSocketAddress, Uninitialized) { QuicSocketAddress uninitialized; EXPECT_FALSE(uninitialized.IsInitialized()); } TEST(QuicSocketAddress, ExplicitConstruction) { QuicSocketAddress ipv4_address(QuicIpAddress::Loopback4(), 443); QuicSocketAddress ipv6_address(QuicIpAddress::Loopback6(), 443); EXPECT_TRUE(ipv4_address.IsInitialized()); EXPECT_EQ("127.0.0.1:443", ipv4_address.ToString()); EXPECT_EQ("[::1]:443", ipv6_address.ToString()); EXPECT_EQ(QuicIpAddress::Loopback4(), ipv4_address.host()); EXPECT_EQ(QuicIpAddress::Loopback6(), ipv6_address.host()); EXPECT_EQ(443, ipv4_address.port()); } TEST(QuicSocketAddress, OutputToStream) { QuicSocketAddress ipv4_address(QuicIpAddress::Loopback4(), 443); std::stringstream stream; stream << ipv4_address; EXPECT_EQ("127.0.0.1:443", stream.str()); } TEST(QuicSocketAddress, FromSockaddrIPv4) { union { sockaddr_storage storage; sockaddr addr; sockaddr_in v4; } address; memset(&address, 0, sizeof(address)); address.v4.sin_family = AF_INET; address.v4.sin_addr = QuicIpAddress::Loopback4().GetIPv4(); address.v4.sin_port = htons(443); EXPECT_EQ("127.0.0.1:443", QuicSocketAddress(&address.addr, sizeof(address.v4)).ToString()); EXPECT_EQ("127.0.0.1:443", QuicSocketAddress(address.storage).ToString()); } TEST(QuicSocketAddress, FromSockaddrIPv6) { union { sockaddr_storage storage; sockaddr addr; sockaddr_in6 v6; } address; memset(&address, 0, sizeof(address)); address.v6.sin6_family = AF_INET6; address.v6.sin6_addr = QuicIpAddress::Loopback6().GetIPv6(); address.v6.sin6_port = htons(443); EXPECT_EQ("[::1]:443", QuicSocketAddress(&address.addr, sizeof(address.v6)).ToString()); EXPECT_EQ("[::1]:443", QuicSocketAddress(address.storage).ToString()); } TEST(QuicSocketAddres, ToSockaddrIPv4) { union { sockaddr_storage storage; sockaddr_in v4; } address; address.storage = QuicSocketAddress(QuicIpAddress::Loopback4(), 443).generic_address(); ASSERT_EQ(AF_INET, address.v4.sin_family); EXPECT_EQ(QuicIpAddress::Loopback4(), QuicIpAddress(address.v4.sin_addr)); EXPECT_EQ(htons(443), address.v4.sin_port); } TEST(QuicSocketAddress, Normalize) { QuicIpAddress dual_stacked; ASSERT_TRUE(dual_stacked.FromString("::ffff:127.0.0.1")); ASSERT_TRUE(dual_stacked.IsIPv6()); QuicSocketAddress not_normalized(dual_stacked, 443); QuicSocketAddress normalized = not_normalized.Normalized(); EXPECT_EQ("[::ffff:127.0.0.1]:443", not_normalized.ToString()); EXPECT_EQ("127.0.0.1:443", normalized.ToString()); } #if defined(__linux__) && !defined(ANDROID) #include <errno.h> #include <sys/socket.h> #include <sys/types.h> TEST(QuicSocketAddress, FromSocket) { int fd; QuicSocketAddress address; bool bound = false; for (int port = 50000; port < 50400; port++) { fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); ASSERT_GT(fd, 0); address = QuicSocketAddress(QuicIpAddress::Loopback6(), port); sockaddr_storage raw_address = address.generic_address(); int bind_result = bind(fd, reinterpret_cast<const sockaddr*>(&raw_address), sizeof(sockaddr_in6)); if (bind_result < 0 && errno == EADDRINUSE) { close(fd); continue; } ASSERT_EQ(0, bind_result); bound = true; break; } ASSERT_TRUE(bound); QuicSocketAddress real_address; ASSERT_EQ(0, real_address.FromSocket(fd)); ASSERT_TRUE(real_address.IsInitialized()); EXPECT_EQ(real_address, address); close(fd); } #endif } }
202
cpp
google/quiche
connect_udp_tunnel
quiche/quic/tools/connect_udp_tunnel.cc
quiche/quic/tools/connect_udp_tunnel_test.cc
#ifndef QUICHE_QUIC_TOOLS_CONNECT_UDP_TUNNEL_H_ #define QUICHE_QUIC_TOOLS_CONNECT_UDP_TUNNEL_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { class ConnectUdpTunnel : public ConnectingClientSocket::AsyncVisitor, public QuicSpdyStream::Http3DatagramVisitor { public: ConnectUdpTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, std::string server_label, absl::flat_hash_set<QuicServerId> acceptable_targets); ~ConnectUdpTunnel(); ConnectUdpTunnel(const ConnectUdpTunnel&) = delete; ConnectUdpTunnel& operator=(const ConnectUdpTunnel&) = delete; void OpenTunnel(const spdy::Http2HeaderBlock& request_headers); bool IsTunnelOpenToTarget() const; void OnClientStreamClose(); void ConnectComplete(absl::Status status) override; void ReceiveComplete(absl::StatusOr<quiche::QuicheMemSlice> data) override; void SendComplete(absl::Status status) override; void OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) override; void OnUnknownCapsule(QuicStreamId , const quiche::UnknownCapsule& ) override {} private: void BeginAsyncReadFromTarget(); void OnDataReceivedFromTarget(bool success); void SendUdpPacketToTarget(absl::string_view packet); void SendConnectResponse(); void SendErrorResponse(absl::string_view status, absl::string_view proxy_status_error, absl::string_view error_details); void TerminateClientStream(absl::string_view error_description, QuicResetStreamError error_code); const absl::flat_hash_set<QuicServerId> acceptable_targets_; SocketFactory* const socket_factory_; const std::string server_label_; QuicSimpleServerBackend::RequestHandler* client_stream_request_handler_; std::unique_ptr<ConnectingClientSocket> target_socket_; bool receive_started_ = false; bool datagram_visitor_registered_ = false; }; } #endif #include "quiche/quic/tools/connect_udp_tunnel.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_name_lookup.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/masque/connect_udp_datagram_payload.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_url_utils.h" #include "quiche/common/structured_headers.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace structured_headers = quiche::structured_headers; namespace { constexpr size_t kReadSize = 4 * 1024; std::optional<QuicServerId> ValidateAndParseTargetFromPath( absl::string_view path) { std::string canonicalized_path_str; url::StdStringCanonOutput canon_output(&canonicalized_path_str); url::Component path_component; url::CanonicalizePath(path.data(), url::Component(0, path.size()), &canon_output, &path_component); if (!path_component.is_nonempty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with non-canonicalizable path: " << path; return std::nullopt; } canon_output.Complete(); absl::string_view canonicalized_path = absl::string_view(canonicalized_path_str) .substr(path_component.begin, path_component.len); std::vector<absl::string_view> path_split = absl::StrSplit(canonicalized_path, '/'); if (path_split.size() != 7 || !path_split[0].empty() || path_split[1] != ".well-known" || path_split[2] != "masque" || path_split[3] != "udp" || path_split[4].empty() || path_split[5].empty() || !path_split[6].empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with bad path: " << canonicalized_path; return std::nullopt; } std::optional<std::string> decoded_host = quiche::AsciiUrlDecode(path_split[4]); if (!decoded_host.has_value()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with undecodable host: " << path_split[4]; return std::nullopt; } QUICHE_DCHECK(!decoded_host->empty()); std::optional<std::string> decoded_port = quiche::AsciiUrlDecode(path_split[5]); if (!decoded_port.has_value()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with undecodable port: " << path_split[5]; return std::nullopt; } QUICHE_DCHECK(!decoded_port->empty()); int parsed_port_number = url::ParsePort( decoded_port->data(), url::Component(0, decoded_port->size())); if (parsed_port_number <= 0) { QUICHE_DVLOG(1) << "CONNECT-UDP request with bad port: " << *decoded_port; return std::nullopt; } QUICHE_DCHECK_LE(parsed_port_number, std::numeric_limits<uint16_t>::max()); return QuicServerId(*decoded_host, static_cast<uint16_t>(parsed_port_number)); } std::optional<QuicServerId> ValidateHeadersAndGetTarget( const spdy::Http2HeaderBlock& request_headers) { QUICHE_DCHECK(request_headers.contains(":method")); QUICHE_DCHECK(request_headers.find(":method")->second == "CONNECT"); QUICHE_DCHECK(request_headers.contains(":protocol")); QUICHE_DCHECK(request_headers.find(":protocol")->second == "connect-udp"); auto authority_it = request_headers.find(":authority"); if (authority_it == request_headers.end() || authority_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing authority"; return std::nullopt; } auto scheme_it = request_headers.find(":scheme"); if (scheme_it == request_headers.end() || scheme_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing scheme"; return std::nullopt; } else if (scheme_it->second != "https") { QUICHE_DVLOG(1) << "CONNECT-UDP request contains unexpected scheme: " << scheme_it->second; return std::nullopt; } auto path_it = request_headers.find(":path"); if (path_it == request_headers.end() || path_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing path"; return std::nullopt; } std::optional<QuicServerId> target_server_id = ValidateAndParseTargetFromPath(path_it->second); return target_server_id; } bool ValidateTarget( const QuicServerId& target, const absl::flat_hash_set<QuicServerId>& acceptable_targets) { if (acceptable_targets.contains(target)) { return true; } QUICHE_DVLOG(1) << "CONNECT-UDP request target is not an acceptable allow-listed target: " << target.ToHostPortString(); return false; } } ConnectUdpTunnel::ConnectUdpTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, std::string server_label, absl::flat_hash_set<QuicServerId> acceptable_targets) : acceptable_targets_(std::move(acceptable_targets)), socket_factory_(socket_factory), server_label_(std::move(server_label)), client_stream_request_handler_(client_stream_request_handler) { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(socket_factory_); QUICHE_DCHECK(!server_label_.empty()); } ConnectUdpTunnel::~ConnectUdpTunnel() { QUICHE_DCHECK(!IsTunnelOpenToTarget()); QUICHE_DCHECK(!receive_started_); QUICHE_DCHECK(!datagram_visitor_registered_); } void ConnectUdpTunnel::OpenTunnel( const spdy::Http2HeaderBlock& request_headers) { QUICHE_DCHECK(!IsTunnelOpenToTarget()); std::optional<QuicServerId> target = ValidateHeadersAndGetTarget(request_headers); if (!target.has_value()) { TerminateClientStream( "invalid request headers", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::MESSAGE_ERROR)); return; } if (!ValidateTarget(*target, acceptable_targets_)) { SendErrorResponse("403", "destination_ip_prohibited", "disallowed proxy target"); return; } QuicSocketAddress address = tools::LookupAddress(AF_UNSPEC, *target); if (!address.IsInitialized()) { SendErrorResponse("500", "dns_error", "host resolution error"); return; } target_socket_ = socket_factory_->CreateConnectingUdpClientSocket( address, 0, 0, this); QUICHE_DCHECK(target_socket_); absl::Status connect_result = target_socket_->ConnectBlocking(); if (!connect_result.ok()) { SendErrorResponse( "502", "destination_ip_unroutable", absl::StrCat("UDP socket error: ", connect_result.ToString())); return; } QUICHE_DVLOG(1) << "CONNECT-UDP tunnel opened from stream " << client_stream_request_handler_->stream_id() << " to " << target->ToHostPortString(); client_stream_request_handler_->GetStream()->RegisterHttp3DatagramVisitor( this); datagram_visitor_registered_ = true; SendConnectResponse(); BeginAsyncReadFromTarget(); } bool ConnectUdpTunnel::IsTunnelOpenToTarget() const { return !!target_socket_; } void ConnectUdpTunnel::OnClientStreamClose() { QUICHE_CHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT-UDP stream " << client_stream_request_handler_->stream_id() << " closed"; if (datagram_visitor_registered_) { client_stream_request_handler_->GetStream() ->UnregisterHttp3DatagramVisitor(); datagram_visitor_registered_ = false; } client_stream_request_handler_ = nullptr; if (IsTunnelOpenToTarget()) { target_socket_->Disconnect(); } target_socket_.reset(); } void ConnectUdpTunnel::ConnectComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectUdpTunnel::ReceiveComplete( absl::StatusOr<quiche::QuicheMemSlice> data) { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(receive_started_); receive_started_ = false; if (!data.ok()) { if (client_stream_request_handler_) { QUICHE_LOG(WARNING) << "Error receiving CONNECT-UDP data from target: " << data.status(); } else { QUICHE_DVLOG(1) << "Error receiving CONNECT-UDP data from target after " "stream already closed."; } return; } QUICHE_DCHECK(client_stream_request_handler_); quiche::ConnectUdpDatagramUdpPacketPayload payload(data->AsStringView()); client_stream_request_handler_->GetStream()->SendHttp3Datagram( payload.Serialize()); BeginAsyncReadFromTarget(); } void ConnectUdpTunnel::SendComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectUdpTunnel::OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK_EQ(stream_id, client_stream_request_handler_->stream_id()); QUICHE_DCHECK(!payload.empty()); std::unique_ptr<quiche::ConnectUdpDatagramPayload> parsed_payload = quiche::ConnectUdpDatagramPayload::Parse(payload); if (!parsed_payload) { QUICHE_DVLOG(1) << "Ignoring HTTP Datagram payload, due to inability to " "parse as CONNECT-UDP payload."; return; } switch (parsed_payload->GetType()) { case quiche::ConnectUdpDatagramPayload::Type::kUdpPacket: SendUdpPacketToTarget(parsed_payload->GetUdpProxyingPayload()); break; case quiche::ConnectUdpDatagramPayload::Type::kUnknown: QUICHE_DVLOG(1) << "Ignoring HTTP Datagram payload with unrecognized context ID."; } } void ConnectUdpTunnel::BeginAsyncReadFromTarget() { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(!receive_started_); receive_started_ = true; target_socket_->ReceiveAsync(kReadSize); } void ConnectUdpTunnel::SendUdpPacketToTarget(absl::string_view packet) { absl::Status send_result = target_socket_->SendBlocking(std::string(packet)); if (!send_result.ok()) { QUICHE_LOG(WARNING) << "Error sending CONNECT-UDP datagram to target: " << send_result; } } void ConnectUdpTunnel::SendConnectResponse() { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(client_stream_request_handler_); spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; std::optional<std::string> capsule_protocol_value = structured_headers::SerializeItem(structured_headers::Item(true)); QUICHE_CHECK(capsule_protocol_value.has_value()); response_headers["Capsule-Protocol"] = *capsule_protocol_value; QuicBackendResponse response; response.set_headers(std::move(response_headers)); response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectUdpTunnel::SendErrorResponse(absl::string_view status, absl::string_view proxy_status_error, absl::string_view error_details) { QUICHE_DCHECK(!status.empty()); QUICHE_DCHECK(!proxy_status_error.empty()); QUICHE_DCHECK(!error_details.empty()); QUICHE_DCHECK(client_stream_request_handler_); #ifndef NDEBUG int status_num = 0; bool is_num = absl::SimpleAtoi(status, &status_num); QUICHE_DCHECK(is_num); QUICHE_DCHECK_GE(status_num, 100); QUICHE_DCHECK_LT(status_num, 600); QUICHE_DCHECK(status_num < 200 || status_num >= 300); #endif spdy::Http2HeaderBlock headers; headers[":status"] = status; structured_headers::Item proxy_status_item(server_label_); structured_headers::Item proxy_status_error_item( std::string{proxy_status_error}); structured_headers::Item proxy_status_details_item( std::string{error_details}); structured_headers::ParameterizedMember proxy_status_member( std::move(proxy_status_item), {{"error", std::move(proxy_status_error_item)}, {"details", std::move(proxy_status_details_item)}}); std::optional<std::string> proxy_status_value = structured_headers::SerializeList({proxy_status_member}); QUICHE_CHECK(proxy_status_value.has_value()); headers["Proxy-Status"] = *proxy_status_value; QuicBackendResponse response; response.set_headers(std::move(headers)); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectUdpTunnel::TerminateClientStream( absl::string_view error_description, QuicResetStreamError error_code) { QUICHE_DCHECK(client_stream_request_handler_); std::string error_description_str = error_description.empty() ? "" : absl::StrCat(" due to ", error_description); QUICHE_DVLOG(1) << "Terminating CONNECT stream " << client_stream_request_handler_->stream_id() << " with error code " << error_code.ietf_application_code() << error_description_str; client_stream_request_handler_->TerminateStreamWithError(error_code); } }
#include "quiche/quic/tools/connect_udp_tunnel.h" #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/masque/connect_udp_datagram_payload.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_url_utils.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AnyOf; using ::testing::Eq; using ::testing::Ge; using ::testing::Gt; using ::testing::HasSubstr; using ::testing::InvokeWithoutArgs; using ::testing::IsEmpty; using ::testing::Matcher; using ::testing::NiceMock; using ::testing::Pair; using ::testing::Property; using ::testing::Return; using ::testing::StrictMock; using ::testing::UnorderedElementsAre; constexpr QuicStreamId kStreamId = 100; class MockStream : public QuicSpdyStream { public: explicit MockStream(QuicSpdySession* spdy_session) : QuicSpdyStream(kStreamId, spdy_session, BIDIRECTIONAL) {} void OnBodyAvailable() override {} MOCK_METHOD(MessageStatus, SendHttp3Datagram, (absl::string_view data), (override)); }; class MockRequestHandler : public QuicSimpleServerBackend::RequestHandler { public: QuicConnectionId connection_id() const override { return TestConnectionId(41212); } QuicStreamId stream_id() const override { return kStreamId; } std::string peer_host() const override { return "127.0.0.1"; } MOCK_METHOD(QuicSpdyStream*, GetStream, (), (override)); MOCK_METHOD(void, OnResponseBackendComplete, (const QuicBackendResponse* response), (override)); MOCK_METHOD(void, SendStreamData, (absl::string_view data, bool close_stream), (override)); MOCK_METHOD(void, TerminateStreamWithError, (QuicResetStreamError error), (override)); }; class MockSocketFactory : public SocketFactory { public: MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateTcpClientSocket, (const QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateConnectingUdpClientSocket, (const QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); }; class MockSocket : public ConnectingClientSocket { public: MOCK_METHOD(absl::Status, ConnectBlocking, (), (override)); MOCK_METHOD(void, ConnectAsync, (), (override)); MOCK_METHOD(void, Disconnect, (), (override)); MOCK_METHOD(absl::StatusOr<QuicSocketAddress>, GetLocalAddress, (), (override)); MOCK_METHOD(absl::StatusOr<quiche::QuicheMemSlice>, ReceiveBlocking, (QuicByteCount max_size), (override)); MOCK_METHOD(void, ReceiveAsync, (QuicByteCount max_size), (override)); MOCK_METHOD(absl::Status, SendBlocking, (std::string data), (override)); MOCK_METHOD(absl::Status, SendBlocking, (quiche::QuicheMemSlice data), (override)); MOCK_METHOD(void, SendAsync, (std::string data), (override)); MOCK_METHOD(void, SendAsync, (quiche::QuicheMemSlice data), (override)); }; class ConnectUdpTunnelTest : public quiche::test::QuicheTest { public: void SetUp() override { #if defined(_WIN32) WSADATA wsa_data; const WORD version_required = MAKEWORD(2, 2); ASSERT_EQ(WSAStartup(version_required, &wsa_data), 0); #endif auto socket = std::make_unique<StrictMock<MockSocket>>(); socket_ = socket.get(); ON_CALL(socket_factory_, CreateConnectingUdpClientSocket( AnyOf(QuicSocketAddress(TestLoopback4(), kAcceptablePort), QuicSocketAddress(TestLoopback6(), kAcceptablePort)), _, _, &tunnel_)) .WillByDefault(Return(ByMove(std::move(socket)))); EXPECT_CALL(request_handler_, GetStream()).WillRepeatedly(Return(&stream_)); } protected: static constexpr absl::string_view kAcceptableTarget = "localhost"; static constexpr uint16_t kAcceptablePort = 977; NiceMock<MockQuicConnectionHelper> connection_helper_; NiceMock<MockAlarmFactory> alarm_factory_; NiceMock<MockQuicSpdySession> session_{new NiceMock<MockQuicConnection>( &connection_helper_, &alarm_factory_, Perspective::IS_SERVER)}; StrictMock<MockStream> stream_{&session_}; StrictMock<MockRequestHandler> request_handler_; NiceMock<MockSocketFactory> socket_factory_; StrictMock<MockSocket>* socket_; ConnectUdpTunnel tunnel_{ &request_handler_, &socket_factory_, "server_label", {{std::string(kAcceptableTarget), kAcceptablePort}, {TestLoopback4().ToString(), kAcceptablePort}, {absl::StrCat("[", TestLoopback6().ToString(), "]"), kAcceptablePort}}}; }; TEST_F(ConnectUdpTunnelTest, OpenTunnel) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelToIpv4LiteralTarget) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat("/.well-known/masque/udp/", TestLoopback4().ToString(), "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelToIpv6LiteralTarget) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); std::string path; ASSERT_TRUE(quiche::ExpandURITemplate( "/.well-known/masque/udp/{target_host}/{target_port}/", {{"target_host", absl::StrCat("[", TestLoopback6().ToString(), "]")}, {"target_port", absl::StrCat(kAcceptablePort)}}, &path)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = path; tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelWithMalformedRequest) { EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR)))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, OpenTunnelWithUnacceptableTarget) { EXPECT_CALL(request_handler_, OnResponseBackendComplete(AllOf( Property(&QuicBackendResponse::response_type, QuicBackendResponse::REGULAR_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre( Pair(":status", "403"), Pair("Proxy-Status", HasSubstr("destination_ip_prohibited")))), Property(&QuicBackendResponse::trailers, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = "/.well-known/masque/udp/unacceptable.test/100/"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, ReceiveFromTarget) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Ge(kData.size()))).Times(2); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL( stream_, SendHttp3Datagram( quiche::ConnectUdpDatagramUdpPacketPayload(kData).Serialize())) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(MemSliceFromString(kData)); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, SendToTarget) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, SendBlocking(Matcher<std::string>(Eq(kData)))) .WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); tunnel_.OnHttp3Datagram( kStreamId, quiche::ConnectUdpDatagramUdpPacketPayload(kData).Serialize()); tunnel_.OnClientStreamClose(); } } }
203
cpp
google/quiche
quic_simple_server_stream
quiche/quic/tools/quic_simple_server_stream.cc
quiche/quic/tools/quic_simple_server_stream_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_SIMPLE_SERVER_STREAM_H_ #define QUICHE_QUIC_TOOLS_QUIC_SIMPLE_SERVER_STREAM_H_ #include <cstdint> #include <optional> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_server_stream_base.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_framer.h" namespace quic { class QuicSimpleServerStream : public QuicSpdyServerStreamBase, public QuicSimpleServerBackend::RequestHandler { public: QuicSimpleServerStream(QuicStreamId id, QuicSpdySession* session, StreamType type, QuicSimpleServerBackend* quic_simple_server_backend); QuicSimpleServerStream(PendingStream* pending, QuicSpdySession* session, QuicSimpleServerBackend* quic_simple_server_backend); QuicSimpleServerStream(const QuicSimpleServerStream&) = delete; QuicSimpleServerStream& operator=(const QuicSimpleServerStream&) = delete; ~QuicSimpleServerStream() override; void OnInitialHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list) override; void OnCanWrite() override; void OnBodyAvailable() override; void OnInvalidHeaders() override; static const char* const kErrorResponseBody; static const char* const kNotFoundResponseBody; QuicConnectionId connection_id() const override; QuicStreamId stream_id() const override; std::string peer_host() const override; QuicSpdyStream* GetStream() override; void OnResponseBackendComplete(const QuicBackendResponse* response) override; void SendStreamData(absl::string_view data, bool close_stream) override; void TerminateStreamWithError(QuicResetStreamError error) override; void Respond(const QuicBackendResponse* response); protected: void HandleRequestConnectData(bool fin_received); virtual void SendResponse(); virtual void SendErrorResponse(); virtual void SendErrorResponse(int resp_code); void SendNotFoundResponse(); void SendIncompleteResponse( std::optional<spdy::Http2HeaderBlock> response_headers, absl::string_view body); void SendHeadersAndBody(spdy::Http2HeaderBlock response_headers, absl::string_view body); void SendHeadersAndBodyAndTrailers( std::optional<spdy::Http2HeaderBlock> response_headers, absl::string_view body, spdy::Http2HeaderBlock response_trailers); spdy::Http2HeaderBlock* request_headers() { return &request_headers_; } bool IsConnectRequest() const; const std::string& body() { return body_; } void WriteGeneratedBytes(); void set_quic_simple_server_backend_for_test( QuicSimpleServerBackend* backend) { quic_simple_server_backend_ = backend; } bool response_sent() const { return response_sent_; } void set_response_sent() { response_sent_ = true; } spdy::Http2HeaderBlock request_headers_; int64_t content_length_; std::string body_; private: uint64_t generate_bytes_length_; bool response_sent_ = false; std::unique_ptr<QuicAlarm> delayed_response_alarm_; QuicSimpleServerBackend* quic_simple_server_backend_; }; } #endif #include "quiche/quic/tools/quic_simple_server_stream.h" #include <algorithm> #include <cstdint> #include <list> #include <optional> #include <string> #include <utility> #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/quic_simple_server_session.h" #include "quiche/spdy/core/spdy_protocol.h" using spdy::Http2HeaderBlock; namespace quic { QuicSimpleServerStream::QuicSimpleServerStream( QuicStreamId id, QuicSpdySession* session, StreamType type, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSpdyServerStreamBase(id, session, type), content_length_(-1), generate_bytes_length_(0), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); } QuicSimpleServerStream::QuicSimpleServerStream( PendingStream* pending, QuicSpdySession* session, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSpdyServerStreamBase(pending, session), content_length_(-1), generate_bytes_length_(0), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); } QuicSimpleServerStream::~QuicSimpleServerStream() { quic_simple_server_backend_->CloseBackendResponseStream(this); } void QuicSimpleServerStream::OnInitialHeadersComplete( bool fin, size_t frame_len, const QuicHeaderList& header_list) { QuicSpdyStream::OnInitialHeadersComplete(fin, frame_len, header_list); if (!response_sent_ && !SpdyUtils::CopyAndValidateHeaders(header_list, &content_length_, &request_headers_)) { QUIC_DVLOG(1) << "Invalid headers"; SendErrorResponse(); } ConsumeHeaderList(); if (!fin && !response_sent_ && IsConnectRequest()) { if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing on CONNECT headers."; SendErrorResponse(); return; } if (web_transport() != nullptr) { QuicSimpleServerBackend::WebTransportResponse response = quic_simple_server_backend_->ProcessWebTransportRequest( request_headers_, web_transport()); if (response.response_headers[":status"] == "200") { WriteHeaders(std::move(response.response_headers), false, nullptr); if (response.visitor != nullptr) { web_transport()->SetVisitor(std::move(response.visitor)); } web_transport()->HeadersReceived(request_headers_); } else { WriteHeaders(std::move(response.response_headers), true, nullptr); } return; } quic_simple_server_backend_->HandleConnectHeaders(request_headers_, this); } } void QuicSimpleServerStream::OnBodyAvailable() { while (HasBytesToRead()) { struct iovec iov; if (GetReadableRegions(&iov, 1) == 0) { break; } QUIC_DVLOG(1) << "Stream " << id() << " processed " << iov.iov_len << " bytes."; body_.append(static_cast<char*>(iov.iov_base), iov.iov_len); if (content_length_ >= 0 && body_.size() > static_cast<uint64_t>(content_length_)) { QUIC_DVLOG(1) << "Body size (" << body_.size() << ") > content length (" << content_length_ << ")."; SendErrorResponse(); return; } MarkConsumed(iov.iov_len); } if (!sequencer()->IsClosed()) { if (IsConnectRequest()) { HandleRequestConnectData(false); } sequencer()->SetUnblocked(); return; } OnFinRead(); if (write_side_closed() || fin_buffered()) { return; } if (IsConnectRequest()) { HandleRequestConnectData(true); } else { SendResponse(); } } void QuicSimpleServerStream::HandleRequestConnectData(bool fin_received) { QUICHE_DCHECK(IsConnectRequest()); if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing on CONNECT data."; ResetWriteSide( QuicResetStreamError::FromInternal(QUIC_STREAM_CONNECT_ERROR)); return; } std::string data = std::move(body_); body_.clear(); quic_simple_server_backend_->HandleConnectData(data, fin_received, this); } void QuicSimpleServerStream::SendResponse() { QUICHE_DCHECK(!IsConnectRequest()); if (request_headers_.empty()) { QUIC_DVLOG(1) << "Request headers empty."; SendErrorResponse(); return; } if (content_length_ > 0 && static_cast<uint64_t>(content_length_) != body_.size()) { QUIC_DVLOG(1) << "Content length (" << content_length_ << ") != body size (" << body_.size() << ")."; SendErrorResponse(); return; } if (!request_headers_.contains(":authority")) { QUIC_DVLOG(1) << "Request headers do not contain :authority."; SendErrorResponse(); return; } if (!request_headers_.contains(":path")) { QUIC_DVLOG(1) << "Request headers do not contain :path."; SendErrorResponse(); return; } if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing in SendResponse()."; SendErrorResponse(); return; } if (web_transport() != nullptr) { QuicSimpleServerBackend::WebTransportResponse response = quic_simple_server_backend_->ProcessWebTransportRequest( request_headers_, web_transport()); if (response.response_headers[":status"] == "200") { WriteHeaders(std::move(response.response_headers), false, nullptr); if (response.visitor != nullptr) { web_transport()->SetVisitor(std::move(response.visitor)); } web_transport()->HeadersReceived(request_headers_); } else { WriteHeaders(std::move(response.response_headers), true, nullptr); } return; } quic_simple_server_backend_->FetchResponseFromBackend(request_headers_, body_, this); } QuicConnectionId QuicSimpleServerStream::connection_id() const { return spdy_session()->connection_id(); } QuicStreamId QuicSimpleServerStream::stream_id() const { return id(); } std::string QuicSimpleServerStream::peer_host() const { return spdy_session()->peer_address().host().ToString(); } QuicSpdyStream* QuicSimpleServerStream::GetStream() { return this; } namespace { class DelayedResponseAlarm : public QuicAlarm::DelegateWithContext { public: DelayedResponseAlarm(QuicSimpleServerStream* stream, const QuicBackendResponse* response) : QuicAlarm::DelegateWithContext( stream->spdy_session()->connection()->context()), stream_(stream), response_(response) { stream_ = stream; response_ = response; } ~DelayedResponseAlarm() override = default; void OnAlarm() override { stream_->Respond(response_); } private: QuicSimpleServerStream* stream_; const QuicBackendResponse* response_; }; } void QuicSimpleServerStream::OnResponseBackendComplete( const QuicBackendResponse* response) { if (response == nullptr) { QUIC_DVLOG(1) << "Response not found in cache."; SendNotFoundResponse(); return; } auto delay = response->delay(); if (delay.IsZero()) { Respond(response); return; } auto* connection = session()->connection(); delayed_response_alarm_.reset(connection->alarm_factory()->CreateAlarm( new DelayedResponseAlarm(this, response))); delayed_response_alarm_->Set(connection->clock()->Now() + delay); } void QuicSimpleServerStream::Respond(const QuicBackendResponse* response) { for (const auto& headers : response->early_hints()) { QUIC_DVLOG(1) << "Stream " << id() << " sending an Early Hints response: " << headers.DebugString(); WriteHeaders(headers.Clone(), false, nullptr); } if (response->response_type() == QuicBackendResponse::CLOSE_CONNECTION) { QUIC_DVLOG(1) << "Special response: closing connection."; OnUnrecoverableError(QUIC_NO_ERROR, "Toy server forcing close"); return; } if (response->response_type() == QuicBackendResponse::IGNORE_REQUEST) { QUIC_DVLOG(1) << "Special response: ignoring request."; return; } if (response->response_type() == QuicBackendResponse::BACKEND_ERR_RESPONSE) { QUIC_DVLOG(1) << "Quic Proxy: Backend connection error."; SendErrorResponse(502); return; } std::string request_url = request_headers_[":authority"].as_string() + request_headers_[":path"].as_string(); int response_code; const Http2HeaderBlock& response_headers = response->headers(); if (!ParseHeaderStatusCode(response_headers, &response_code)) { auto status = response_headers.find(":status"); if (status == response_headers.end()) { QUIC_LOG(WARNING) << ":status not present in response from cache for request " << request_url; } else { QUIC_LOG(WARNING) << "Illegal (non-integer) response :status from cache: " << status->second << " for request " << request_url; } SendErrorResponse(); return; } if (response->response_type() == QuicBackendResponse::INCOMPLETE_RESPONSE) { QUIC_DVLOG(1) << "Stream " << id() << " sending an incomplete response, i.e. no trailer, no fin."; SendIncompleteResponse(response->headers().Clone(), response->body()); return; } if (response->response_type() == QuicBackendResponse::GENERATE_BYTES) { QUIC_DVLOG(1) << "Stream " << id() << " sending a generate bytes response."; std::string path = request_headers_[":path"].as_string().substr(1); if (!absl::SimpleAtoi(path, &generate_bytes_length_)) { QUIC_LOG(ERROR) << "Path is not a number."; SendNotFoundResponse(); return; } Http2HeaderBlock headers = response->headers().Clone(); headers["content-length"] = absl::StrCat(generate_bytes_length_); WriteHeaders(std::move(headers), false, nullptr); QUICHE_DCHECK(!response_sent_); response_sent_ = true; WriteGeneratedBytes(); return; } QUIC_DVLOG(1) << "Stream " << id() << " sending response."; SendHeadersAndBodyAndTrailers(response->headers().Clone(), response->body(), response->trailers().Clone()); } void QuicSimpleServerStream::SendStreamData(absl::string_view data, bool close_stream) { QUICHE_DCHECK(!data.empty() || close_stream); if (close_stream) { SendHeadersAndBodyAndTrailers( std::nullopt, data, spdy::Http2HeaderBlock()); } else { SendIncompleteResponse(std::nullopt, data); } } void QuicSimpleServerStream::TerminateStreamWithError( QuicResetStreamError error) { QUIC_DVLOG(1) << "Stream " << id() << " abruptly terminating with error " << error.internal_code(); ResetWriteSide(error); } void QuicSimpleServerStream::OnCanWrite() { QuicSpdyStream::OnCanWrite(); WriteGeneratedBytes(); } void QuicSimpleServerStream::WriteGeneratedBytes() { static size_t kChunkSize = 1024; while (!HasBufferedData() && generate_bytes_length_ > 0) { size_t len = std::min<size_t>(kChunkSize, generate_bytes_length_); std::string data(len, 'a'); generate_bytes_length_ -= len; bool fin = generate_bytes_length_ == 0; WriteOrBufferBody(data, fin); } } void QuicSimpleServerStream::SendNotFoundResponse() { QUIC_DVLOG(1) << "Stream " << id() << " sending not found response."; Http2HeaderBlock headers; headers[":status"] = "404"; headers["content-length"] = absl::StrCat(strlen(kNotFoundResponseBody)); SendHeadersAndBody(std::move(headers), kNotFoundResponseBody); } void QuicSimpleServerStream::SendErrorResponse() { SendErrorResponse(0); } void QuicSimpleServerStream::SendErrorResponse(int resp_code) { QUIC_DVLOG(1) << "Stream " << id() << " sending error response."; if (!reading_stopped()) { StopReading(); } Http2HeaderBlock headers; if (resp_code <= 0) { headers[":status"] = "500"; } else { headers[":status"] = absl::StrCat(resp_code); } headers["content-length"] = absl::StrCat(strlen(kErrorResponseBody)); SendHeadersAndBody(std::move(headers), kErrorResponseBody); } void QuicSimpleServerStream::SendIncompleteResponse( std::optional<Http2HeaderBlock> response_headers, absl::string_view body) { QUICHE_DCHECK_NE(response_headers.has_value(), response_sent_); if (response_headers.has_value()) { QUIC_DLOG(INFO) << "Stream " << id() << " writing headers (fin = false) : " << response_headers.value().DebugString(); int response_code; if (!ParseHeaderStatusCode(*response_headers, &response_code) || response_code != 100) { response_sent_ = true; } WriteHeaders(std::move(response_headers).value(), false, nullptr); } QUIC_DLOG(INFO) << "Stream " << id() << " writing body (fin = false) with size: " << body.size(); if (!body.empty()) { WriteOrBufferBody(body, false); } } void QuicSimpleServerStream::SendHeadersAndBody( Http2HeaderBlock response_headers, absl::string_view body) { SendHeadersAndBodyAndTrailers(std::move(response_headers), body, Http2HeaderBlock()); } void QuicSimpleServerStream::SendHeadersAndBodyAndTrailers( std::optional<Http2HeaderBlock> response_headers, absl::string_view body, Http2HeaderBlock response_trailers) { QUICHE_DCHECK_NE(response_headers.has_value(), response_sent_); if (response_headers.has_value()) { bool send_fin = (body.empty() && response_trailers.empty()); QUIC_DLOG(INFO) << "Stream " << id() << " writing headers (fin = " << send_fin << ") : " << response_headers.value().DebugString(); WriteHeaders(std::move(response_headers).value(), send_fin, nullptr); response_sent_ = true; if (send_fin) { return; } } bool send_fin = response_trailers.empty(); QUIC_DLOG(INFO) << "Stream " << id() << " writing body (fin = " << send_fin << ") with size: " << body.size(); if (!body.empty() || send_fin) { WriteOrBufferBody(body, send_fin); } if (send_fin) { return; } QUIC_DLOG(INFO) << "Stream " << id() << " writing trailers (fin = true): " << response_trailers.DebugString(); WriteTrailers(std::move(response_trailers), nullptr); } bool QuicSimpleServerStream::IsConnectRequest() const { auto method_it = request_headers_.find(":method"); return method_it != request_headers_.end() && method_it->second == "CONNECT"; } void QuicSimpleServerStream::OnInvalidHeaders() { QUIC_DVLOG(1) << "Invalid headers"; SendErrorResponse(400); } const char* const QuicSimpleServerStream::kErrorResponseBody = "bad"; const char* const QuicSimpleServerStream::kNotFoundResponseBody = "file not found"; }
#include "quiche/quic/tools/quic_simple_server_stream.h" #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/quic/tools/quic_simple_server_session.h" #include "quiche/common/simple_buffer_allocator.h" using testing::_; using testing::AnyNumber; using testing::InSequence; using testing::Invoke; using testing::StrictMock; namespace quic { namespace test { const size_t kFakeFrameLen = 60; const size_t kErrorLength = strlen(QuicSimpleServerStream::kErrorResponseBody); const size_t kDataFrameHeaderLength = 2; class TestStream : public QuicSimpleServerStream { public: TestStream(QuicStreamId stream_id, QuicSpdySession* session, StreamType type, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerStream(stream_id, session, type, quic_simple_server_backend) { EXPECT_CALL(*this, WriteOrBufferBody(_, _)) .Times(AnyNumber()) .WillRepeatedly([this](absl::string_view data, bool fin) { this->QuicSimpleServerStream::WriteOrBufferBody(data, fin); }); } ~TestStream() override = default; MOCK_METHOD(void, FireAlarmMock, (), ()); MOCK_METHOD(void, WriteHeadersMock, (bool fin), ()); MOCK_METHOD(void, WriteEarlyHintsHeadersMock, (bool fin), ()); MOCK_METHOD(void, WriteOrBufferBody, (absl::string_view data, bool fin), (override)); size_t WriteHeaders( spdy::Http2HeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ) override { if (header_block[":status"] == "103") { WriteEarlyHintsHeadersMock(fin); } else { WriteHeadersMock(fin); } return 0; } void DoSendResponse() { SendResponse(); } void DoSendErrorResponse() { QuicSimpleServerStream::SendErrorResponse(); } spdy::Http2HeaderBlock* mutable_headers() { return &request_headers_; } void set_body(std::string body) { body_ = std::move(body); } const std::string& body() const { return body_; } int content_length() const { return content_length_; } bool send_response_was_called() const { return send_response_was_called_; } bool send_error_response_was_called() const { return send_error_response_was_called_; } absl::string_view GetHeader(absl::string_view key) const { auto it = request_headers_.find(key); QUICHE_DCHECK(it != request_headers_.end()); return it->second; } void ReplaceBackend(QuicSimpleServerBackend* backend) { set_quic_simple_server_backend_for_test(backend); } protected: void SendResponse() override { send_response_was_called_ = true; QuicSimpleServerStream::SendResponse(); } void SendErrorResponse(int resp_code) override { send_error_response_was_called_ = true; QuicSimpleServerStream::SendErrorResponse(resp_code); } private: bool send_response_was_called_ = false; bool send_error_response_was_called_ = false; }; namespace { class MockQuicSimpleServerSession : public QuicSimpleServerSession { public: const size_t kMaxStreamsForTest = 100; MockQuicSimpleServerSession( QuicConnection* connection, MockQuicSessionVisitor* owner, MockQuicCryptoServerStreamHelper* helper, QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerSession(DefaultQuicConfig(), CurrentSupportedVersions(), connection, owner, helper, crypto_config, compressed_certs_cache, quic_simple_server_backend) { if (VersionHasIetfQuicFrames(connection->transport_version())) { QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams( this, kMaxStreamsForTest); QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams( this, kMaxStreamsForTest); } else { QuicSessionPeer::SetMaxOpenIncomingStreams(this, kMaxStreamsForTest); QuicSessionPeer::SetMaxOpenOutgoingStreams(this, kMaxStreamsForTest); } ON_CALL(*this, WritevData(_, _, _, _, _, _)) .WillByDefault(Invoke(this, &MockQuicSimpleServerSession::ConsumeData)); } MockQuicSimpleServerSession(const MockQuicSimpleServerSession&) = delete; MockQuicSimpleServerSession& operator=(const MockQuicSimpleServerSession&) = delete; ~MockQuicSimpleServerSession() override = default; MOCK_METHOD(void, OnConnectionClosed, (const QuicConnectionCloseFrame& frame, ConnectionCloseSource source), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id), (override)); MOCK_METHOD(QuicConsumedData, WritevData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level), (override)); MOCK_METHOD(void, OnStreamHeaderList, (QuicStreamId stream_id, bool fin, size_t frame_len, const QuicHeaderList& header_list), (override)); MOCK_METHOD(void, OnStreamHeadersPriority, (QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence), (override)); MOCK_METHOD(void, MaybeSendRstStreamFrame, (QuicStreamId stream_id, QuicResetStreamError error, QuicStreamOffset bytes_written), (override)); MOCK_METHOD(void, MaybeSendStopSendingFrame, (QuicStreamId stream_id, QuicResetStreamError error), (override)); using QuicSession::ActivateStream; QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType , std::optional<EncryptionLevel> ) { if (write_length > 0) { auto buf = std::make_unique<char[]>(write_length); QuicStream* stream = GetOrCreateStream(id); QUICHE_DCHECK(stream); QuicDataWriter writer(write_length, buf.get(), quiche::HOST_BYTE_ORDER); stream->WriteStreamData(offset, write_length, &writer); } else { QUICHE_DCHECK(state != NO_FIN); } return QuicConsumedData(write_length, state != NO_FIN); } spdy::Http2HeaderBlock original_request_headers_; }; class QuicSimpleServerStreamTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicSimpleServerStreamTest() : connection_(new StrictMock<MockQuicConnection>( &simulator_, simulator_.GetAlarmFactory(), Perspective::IS_SERVER, SupportedVersions(GetParam()))), crypto_config_(new QuicCryptoServerConfig( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default())), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), session_(connection_, &session_owner_, &session_helper_, crypto_config_.get(), &compressed_certs_cache_, &memory_cache_backend_), quic_response_(new QuicBackendResponse), body_("hello world") { connection_->set_visitor(&session_); header_list_.OnHeaderBlockStart(); header_list_.OnHeader(":authority", "www.google.com"); header_list_.OnHeader(":path", "/"); header_list_.OnHeader(":method", "POST"); header_list_.OnHeader(":scheme", "https"); header_list_.OnHeader("content-length", "11"); header_list_.OnHeaderBlockEnd(128, 128); session_.config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session_.config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); session_.Initialize(); connection_->SetEncrypter( quic::ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::NullEncrypter>(connection_->perspective())); if (connection_->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(connection_); } stream_ = new StrictMock<TestStream>( GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 0), &session_, BIDIRECTIONAL, &memory_cache_backend_); session_.ActivateStream(absl::WrapUnique(stream_)); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 10); session_.OnConfigNegotiated(); simulator_.RunFor(QuicTime::Delta::FromSeconds(1)); } const std::string& StreamBody() { return stream_->body(); } std::string StreamHeadersValue(const std::string& key) { return (*stream_->mutable_headers())[key].as_string(); } bool UsesHttp3() const { return VersionUsesHttp3(connection_->transport_version()); } void ReplaceBackend(std::unique_ptr<QuicSimpleServerBackend> backend) { replacement_backend_ = std::move(backend); stream_->ReplaceBackend(replacement_backend_.get()); } quic::simulator::Simulator simulator_; spdy::Http2HeaderBlock response_headers_; MockQuicConnectionHelper helper_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSessionVisitor> session_owner_; StrictMock<MockQuicCryptoServerStreamHelper> session_helper_; std::unique_ptr<QuicCryptoServerConfig> crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicMemoryCacheBackend memory_cache_backend_; std::unique_ptr<QuicSimpleServerBackend> replacement_backend_; StrictMock<MockQuicSimpleServerSession> session_; StrictMock<TestStream>* stream_; std::unique_ptr<QuicBackendResponse> quic_response_; std::string body_; QuicHeaderList header_list_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSimpleServerStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSimpleServerStreamTest, TestFraming) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); EXPECT_EQ(body_, StreamBody()); } TEST_P(QuicSimpleServerStreamTest, TestFramingOnePacket) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); EXPECT_EQ(body_, StreamBody()); } TEST_P(QuicSimpleServerStreamTest, SendQuicRstStreamNoErrorInStopReading) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); EXPECT_FALSE(stream_->fin_received()); EXPECT_FALSE(stream_->rst_received()); QuicStreamPeer::SetFinSent(stream_); stream_->CloseWriteSide(); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))) .Times(1); } else { EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_STREAM_NO_ERROR), _)) .Times(1); } stream_->StopReading(); } TEST_P(QuicSimpleServerStreamTest, TestFramingExtraData) { InSequence seq; std::string large_body = "hello world!!!!!!"; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, kDataFrameHeaderLength, _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); header = HttpEncoder::SerializeDataFrameHeader( large_body.length(), quiche::SimpleBufferAllocator::Get()); std::string data2 = UsesHttp3() ? absl::StrCat(header.AsStringView(), large_body) : large_body; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), true, data.size(), data2)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithIllegalResponseStatus) { spdy::Http2HeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200 OK"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithIllegalResponseStatus2) { spdy::Http2HeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "+200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithValidHeaders) { spdy::Http2HeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithEarlyHints) { std::string host = "www.google.com"; std::string request_path = "/foo"; std::string body = "Yummm"; spdy::Http2HeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = request_path; (*request_headers)[":authority"] = host; (*request_headers)[":method"] = "GET"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); std::vector<spdy::Http2HeaderBlock> early_hints; const size_t kNumEarlyHintsResponses = 2; for (size_t i = 0; i < kNumEarlyHintsResponses; ++i) { spdy::Http2HeaderBlock hints; hints["link"] = "</image.png>; rel=preload; as=image"; early_hints.push_back(std::move(hints)); } response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; memory_cache_backend_.AddResponseWithEarlyHints( host, request_path, std::move(response_headers_), body, early_hints); QuicStreamPeer::SetFinReceived(stream_); InSequence s; for (size_t i = 0; i < kNumEarlyHintsResponses; ++i) { EXPECT_CALL(*stream_, WriteEarlyHintsHeadersMock(false)); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } class AlarmTestDelegate : public QuicAlarm::DelegateWithoutContext { public: AlarmTestDelegate(TestStream* stream) : stream_(stream) {} void OnAlarm() override { stream_->FireAlarmMock(); } private: TestStream* stream_; }; TEST_P(QuicSimpleServerStreamTest, SendResponseWithDelay) { spdy::Http2HeaderBlock* request_headers = stream_->mutable_headers(); std::string host = "www.google.com"; std::string path = "/bar"; (*request_headers)[":path"] = path; (*request_headers)[":authority"] = host; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; QuicTime::Delta delay = QuicTime::Delta::FromMilliseconds(3000); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse(host, path, std::move(response_headers_), body); auto did_delay_succeed = memory_cache_backend_.SetResponseDelay(host, path, delay); EXPECT_TRUE(did_delay_succeed); auto did_invalid_delay_succeed = memory_cache_backend_.SetResponseDelay(host, "nonsense", delay); EXPECT_FALSE(did_invalid_delay_succeed); std::unique_ptr<QuicAlarm> alarm(connection_->alarm_factory()->CreateAlarm( new AlarmTestDelegate(stream_))); alarm->Set(connection_->clock()->Now() + delay); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, FireAlarmMock()); EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); simulator_.RunFor(delay); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, TestSendErrorResponse) { QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, kDataFrameHeaderLength, _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendErrorResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidMultipleContentLength) { spdy::Http2HeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("11\00012", 5)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(true, kFakeFrameLen, header_list_); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidLeadingNullContentLength) { spdy::Http2HeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("\00012", 3)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(true, kFakeFrameLen, header_list_); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidMultipleContentLengthII) { spdy::Http2HeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("11\00011", 5)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); } stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); if (session_.version().UsesHttp3()) { EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } else { EXPECT_EQ(11, stream_->content_length()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_FALSE(stream_->reading_stopped()); EXPECT_FALSE(stream_->write_side_closed()); } } TEST_P(QuicSimpleServerStreamTest, DoNotSendQuicRstStreamNoErrorWithRstReceived) { EXPECT_FALSE(stream_->reading_stopped()); if (VersionUsesHttp3(connection_->transport_version())) { auto* qpack_decoder_stream = QuicSpdySessionPeer::GetQpackDecoderSendStream(&session_); EXPECT_CALL(session_, WritevData(qpack_decoder_stream->id(), _, _, _, _, _)) .Times(AnyNumber()); } EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, session_.version().UsesHttp3() ? QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED) : QuicResetStreamError::FromInternal(QUIC_RST_ACKNOWLEDGEMENT), _)) .Times(1); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(connection_->transport_version())) { EXPECT_CALL(session_owner_, OnStopSendingReceived(_)); QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED); session_.OnStopSendingFrame(stop_sending); } EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidHeadersWithFin) { char arr[] = { 0x3a, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x3a, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x47, 0x45, 0x54, 0x00, 0x00, 0x00, 0x05, 0x3a, 0x70, 0x61, 0x74, 0x68, 0x00, 0x00, 0x00, 0x04, 0x2f, 0x66, 0x6f, 0x6f, 0x00, 0x00, 0x00, 0x07, 0x3a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x3a, 0x76, 0x65, 0x72, 0x73, '\x96', 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, }; absl::string_view data(arr, ABSL_ARRAYSIZE(arr)); QuicStreamFrame frame(stream_->id(), true, 0, data); stream_->OnStreamFrame(frame); } class TestQuicSimpleServerBackend : public QuicSimpleServerBackend { public: TestQuicSimpleServerBackend() = default; ~TestQuicSimpleServerBackend() override = default; bool InitializeBackend(const std::string& ) override { return true; } bool IsBackendInitialized() const override { return true; } MOCK_METHOD(void, FetchResponseFromBackend, (const spdy::Http2HeaderBlock&, const std::string&, RequestHandler*), (override)); MOCK_METHOD(void, HandleConnectHeaders, (const spdy::Http2HeaderBlock&, RequestHandler*), (override)); MOCK_METHOD(void, HandleConnectData, (absl::string_view, bool, RequestHandler*), (override)); void CloseBackendResponseStream( RequestHandler* ) override {} }; ACTION_P(SendHeadersResponse, response_ptr) { arg1->OnResponseBackendComplete(response_ptr); } ACTION_P(SendStreamData, data, close_stream) { arg2->SendStreamData(data, close_stream); } ACTION_P(TerminateStream, error) { arg1->TerminateStreamWithError(error); } TEST_P(QuicSimpleServerStreamTest, ConnectSendsIntermediateResponses) { auto test_backend = std::make_unique<TestQuicSimpleServerBackend>(); TestQuicSimpleServerBackend* test_backend_ptr = test_backend.get(); ReplaceBackend(std::move(test_backend)); constexpr absl::string_view kRequestBody = "\x11\x11"; spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; QuicBackendResponse headers_response; headers_response.set_headers(response_headers.Clone()); headers_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); constexpr absl::string_view kBody1 = "\x22\x22"; constexpr absl::string_view kBody2 = "\x33\x33"; InSequence s; EXPECT_CALL(*test_backend_ptr, HandleConnectHeaders(_, _)) .WillOnce(SendHeadersResponse(&headers_response)); EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(*test_backend_ptr, HandleConnectData(kRequestBody, false, _)) .WillOnce(SendStreamData(kBody1, false)); EXPECT_CALL(*stream_, WriteOrBufferBody(kBody1, false)); EXPECT_CALL(*test_backend_ptr, HandleConnectData(kRequestBody, true, _)) .WillOnce(SendStreamData(kBody2, true)); EXPECT_CALL(*stream_, WriteOrBufferBody(kBody2, true)); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list); quiche::QuicheBuffer h
204
cpp
google/quiche
quic_simple_server_session
quiche/quic/tools/quic_simple_server_session.cc
quiche/quic/tools/quic_simple_server_session_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_SIMPLE_SERVER_SESSION_H_ #define QUICHE_QUIC_TOOLS_QUIC_SIMPLE_SERVER_SESSION_H_ #include <stdint.h> #include <list> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/http/quic_server_session_base.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/quic/tools/quic_simple_server_stream.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace test { class QuicSimpleServerSessionPeer; } class QuicSimpleServerSession : public QuicServerSessionBase { public: QuicSimpleServerSession(const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend); QuicSimpleServerSession(const QuicSimpleServerSession&) = delete; QuicSimpleServerSession& operator=(const QuicSimpleServerSession&) = delete; ~QuicSimpleServerSession() override; void OnStreamFrame(const QuicStreamFrame& frame) override; protected: QuicSpdyStream* CreateIncomingStream(QuicStreamId id) override; QuicSpdyStream* CreateIncomingStream(PendingStream* pending) override; QuicSpdyStream* CreateOutgoingBidirectionalStream() override; QuicSimpleServerStream* CreateOutgoingUnidirectionalStream() override; std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) override; QuicStream* ProcessBidirectionalPendingStream( PendingStream* pending) override; QuicSimpleServerBackend* server_backend() { return quic_simple_server_backend_; } WebTransportHttp3VersionSet LocallySupportedWebTransportVersions() const override { return quic_simple_server_backend_->SupportsWebTransport() ? kDefaultSupportedWebTransportVersions : WebTransportHttp3VersionSet(); } HttpDatagramSupport LocalHttpDatagramSupport() override { if (ShouldNegotiateWebTransport()) { return HttpDatagramSupport::kRfcAndDraft04; } return QuicServerSessionBase::LocalHttpDatagramSupport(); } private: friend class test::QuicSimpleServerSessionPeer; QuicSimpleServerBackend* quic_simple_server_backend_; }; } #endif #include "quiche/quic/tools/quic_simple_server_session.h" #include <memory> #include <utility> #include "absl/memory/memory.h" #include "quiche/quic/core/http/quic_server_initiated_spdy_stream.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/quic_simple_server_stream.h" namespace quic { QuicSimpleServerSession::QuicSimpleServerSession( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicServerSessionBase(config, supported_versions, connection, visitor, helper, crypto_config, compressed_certs_cache), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); set_max_streams_accepted_per_loop(5u); } QuicSimpleServerSession::~QuicSimpleServerSession() { DeleteConnection(); } std::unique_ptr<QuicCryptoServerStreamBase> QuicSimpleServerSession::CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, stream_helper()); } void QuicSimpleServerSession::OnStreamFrame(const QuicStreamFrame& frame) { if (!IsIncomingStream(frame.stream_id) && !WillNegotiateWebTransport()) { QUIC_LOG(WARNING) << "Client shouldn't send data on server push stream"; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Client sent data on server push stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QuicSpdySession::OnStreamFrame(frame); } QuicSpdyStream* QuicSimpleServerSession::CreateIncomingStream(QuicStreamId id) { if (!ShouldCreateIncomingStream(id)) { return nullptr; } QuicSpdyStream* stream = new QuicSimpleServerStream( id, this, BIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* QuicSimpleServerSession::CreateIncomingStream( PendingStream* pending) { QuicSpdyStream* stream = new QuicSimpleServerStream(pending, this, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* QuicSimpleServerSession::CreateOutgoingBidirectionalStream() { if (!WillNegotiateWebTransport()) { QUIC_BUG(QuicSimpleServerSession CreateOutgoingBidirectionalStream without WebTransport support) << "QuicSimpleServerSession::CreateOutgoingBidirectionalStream called " "in a session without WebTransport support."; return nullptr; } if (!ShouldCreateOutgoingBidirectionalStream()) { return nullptr; } QuicServerInitiatedSpdyStream* stream = new QuicServerInitiatedSpdyStream( GetNextOutgoingBidirectionalStreamId(), this, BIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSimpleServerStream* QuicSimpleServerSession::CreateOutgoingUnidirectionalStream() { if (!ShouldCreateOutgoingUnidirectionalStream()) { return nullptr; } QuicSimpleServerStream* stream = new QuicSimpleServerStream( GetNextOutgoingUnidirectionalStreamId(), this, WRITE_UNIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicStream* QuicSimpleServerSession::ProcessBidirectionalPendingStream( PendingStream* pending) { QUICHE_DCHECK(IsEncryptionEstablished()); return CreateIncomingStream(pending); } }
#include "quiche/quic/tools/quic_simple_server_session.h" #include <algorithm> #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_crypto_server_stream.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_server_handshaker.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_sustained_bandwidth_recorder_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_server_stream.h" using testing::_; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { const char* const kStreamData = "\1z"; } class QuicSimpleServerSessionPeer { public: static void SetCryptoStream(QuicSimpleServerSession* s, QuicCryptoServerStreamBase* crypto_stream) { s->crypto_stream_.reset(crypto_stream); } static QuicSpdyStream* CreateIncomingStream(QuicSimpleServerSession* s, QuicStreamId id) { return s->CreateIncomingStream(id); } static QuicSimpleServerStream* CreateOutgoingUnidirectionalStream( QuicSimpleServerSession* s) { return s->CreateOutgoingUnidirectionalStream(); } }; namespace { const size_t kMaxStreamsForTest = 10; class MockQuicCryptoServerStream : public QuicCryptoServerStream { public: explicit MockQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSession* session, QuicCryptoServerStreamBase::Helper* helper) : QuicCryptoServerStream(crypto_config, compressed_certs_cache, session, helper) {} MockQuicCryptoServerStream(const MockQuicCryptoServerStream&) = delete; MockQuicCryptoServerStream& operator=(const MockQuicCryptoServerStream&) = delete; ~MockQuicCryptoServerStream() override {} MOCK_METHOD(void, SendServerConfigUpdate, (const CachedNetworkParameters*), (override)); bool encryption_established() const override { return true; } }; class MockTlsServerHandshaker : public TlsServerHandshaker { public: explicit MockTlsServerHandshaker(QuicSession* session, const QuicCryptoServerConfig* crypto_config) : TlsServerHandshaker(session, crypto_config) {} MockTlsServerHandshaker(const MockTlsServerHandshaker&) = delete; MockTlsServerHandshaker& operator=(const MockTlsServerHandshaker&) = delete; ~MockTlsServerHandshaker() override {} MOCK_METHOD(void, SendServerConfigUpdate, (const CachedNetworkParameters*), (override)); bool encryption_established() const override { return true; } }; class MockQuicConnectionWithSendStreamData : public MockQuicConnection { public: MockQuicConnectionWithSendStreamData( MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) : MockQuicConnection(helper, alarm_factory, perspective, supported_versions) { auto consume_all_data = [](QuicStreamId , size_t write_length, QuicStreamOffset , StreamSendingState state) { return QuicConsumedData(write_length, state != NO_FIN); }; ON_CALL(*this, SendStreamData(_, _, _, _)) .WillByDefault(Invoke(consume_all_data)); } MOCK_METHOD(QuicConsumedData, SendStreamData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state), (override)); }; class MockQuicSimpleServerSession : public QuicSimpleServerSession { public: MockQuicSimpleServerSession( const QuicConfig& config, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerSession( config, CurrentSupportedVersions(), connection, visitor, helper, crypto_config, compressed_certs_cache, quic_simple_server_backend) { } MOCK_METHOD(void, SendBlocked, (QuicStreamId, QuicStreamOffset), (override)); MOCK_METHOD(bool, WriteControlFrame, (const QuicFrame& frame, TransmissionType type), (override)); }; class QuicSimpleServerSessionTest : public QuicTestWithParam<ParsedQuicVersion> { public: bool ClearMaxStreamsControlFrame(const QuicFrame& frame) { if (frame.type == MAX_STREAMS_FRAME) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } return false; } protected: QuicSimpleServerSessionTest() : crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) { config_.SetMaxBidirectionalStreamsToSend(kMaxStreamsForTest); QuicConfigPeer::SetReceivedMaxBidirectionalStreams(&config_, kMaxStreamsForTest); config_.SetMaxUnidirectionalStreamsToSend(kMaxStreamsForTest); config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesUnidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (VersionUsesHttp3(transport_version())) { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( &config_, kMaxStreamsForTest + 3); } else { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(&config_, kMaxStreamsForTest); } ParsedQuicVersionVector supported_versions = SupportedVersions(version()); connection_ = new StrictMock<MockQuicConnectionWithSendStreamData>( &helper_, &alarm_factory_, Perspective::IS_SERVER, supported_versions); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); session_ = std::make_unique<MockQuicSimpleServerSession>( config_, connection_, &owner_, &stream_helper_, &crypto_config_, &compressed_certs_cache_, &memory_cache_backend_); MockClock clock; handshake_message_ = crypto_config_.AddDefaultConfig( QuicRandom::GetInstance(), &clock, QuicCryptoServerConfig::ConfigOptions()); session_->Initialize(); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); } session_->OnConfigNegotiated(); } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return GetNthClientInitiatedBidirectionalStreamId(transport_version(), n); } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return quic::test::GetNthServerInitiatedUnidirectionalStreamId( transport_version(), n); } ParsedQuicVersion version() const { return GetParam(); } QuicTransportVersion transport_version() const { return version().transport_version; } void InjectStopSending(QuicStreamId stream_id, QuicRstStreamErrorCode rst_stream_code) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } EXPECT_CALL(owner_, OnStopSendingReceived(_)).Times(1); QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_id, rst_stream_code); EXPECT_CALL(*connection_, OnStreamReset(stream_id, rst_stream_code)); session_->OnStopSendingFrame(stop_sending); } StrictMock<MockQuicSessionVisitor> owner_; StrictMock<MockQuicCryptoServerStreamHelper> stream_helper_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnectionWithSendStreamData>* connection_; QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicMemoryCacheBackend memory_cache_backend_; std::unique_ptr<MockQuicSimpleServerSession> session_; std::unique_ptr<CryptoHandshakeMessage> handshake_message_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSimpleServerSessionTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSimpleServerSessionTest, CloseStreamDueToReset) { QuicStreamFrame data1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); session_->OnStreamFrame(data1); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicRstStreamFrame rst1(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); EXPECT_CALL(*session_, WriteControlFrame(_, _)); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst1); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); session_->OnStreamFrame(data1); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicSimpleServerSessionTest, NeverOpenStreamDueToReset) { QuicRstStreamFrame rst1(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst1); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicStreamFrame data1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); session_->OnStreamFrame(data1); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicSimpleServerSessionTest, AcceptClosedStream) { QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(1), false, 0, kStreamData); session_->OnStreamFrame(frame1); session_->OnStreamFrame(frame2); EXPECT_EQ(2u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicRstStreamFrame rst(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); QuicStreamFrame frame3(GetNthClientInitiatedBidirectionalId(0), false, 2, kStreamData); QuicStreamFrame frame4(GetNthClientInitiatedBidirectionalId(1), false, 2, kStreamData); session_->OnStreamFrame(frame3); session_->OnStreamFrame(frame4); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicSimpleServerSessionTest, CreateIncomingStreamDisconnected) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); QuicConnectionPeer::TearDownLocalConnectionState(connection_); EXPECT_QUIC_BUG(QuicSimpleServerSessionPeer::CreateIncomingStream( session_.get(), GetNthClientInitiatedBidirectionalId(0)), "ShouldCreateIncomingStream called when disconnected"); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, CreateIncomingStream) { QuicSpdyStream* stream = QuicSimpleServerSessionPeer::CreateIncomingStream( session_.get(), GetNthClientInitiatedBidirectionalId(0)); EXPECT_NE(nullptr, stream); EXPECT_EQ(GetNthClientInitiatedBidirectionalId(0), stream->id()); } TEST_P(QuicSimpleServerSessionTest, CreateOutgoingDynamicStreamDisconnected) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); QuicConnectionPeer::TearDownLocalConnectionState(connection_); EXPECT_QUIC_BUG( QuicSimpleServerSessionPeer::CreateOutgoingUnidirectionalStream( session_.get()), "ShouldCreateOutgoingUnidirectionalStream called when disconnected"); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, CreateOutgoingDynamicStreamUnencrypted) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); EXPECT_QUIC_BUG( QuicSimpleServerSessionPeer::CreateOutgoingUnidirectionalStream( session_.get()), "Encryption not established so no outgoing stream created."); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, GetEvenIncomingError) { const size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); const QuicErrorCode expected_error = VersionUsesHttp3(transport_version()) ? QUIC_HTTP_STREAM_WRONG_DIRECTION : QUIC_INVALID_STREAM_ID; EXPECT_CALL(*connection_, CloseConnection(expected_error, "Data for nonexistent stream", _)); EXPECT_EQ(nullptr, QuicSessionPeer::GetOrCreateStream( session_.get(), GetNthServerInitiatedUnidirectionalId(3))); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } } } }
205
cpp
google/quiche
quic_default_client
quiche/quic/tools/quic_default_client.cc
quiche/quic/tools/quic_default_client_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_DEFAULT_CLIENT_H_ #define QUICHE_QUIC_TOOLS_QUIC_DEFAULT_CLIENT_H_ #include <cstdint> #include <memory> #include <string> #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/tools/quic_client_default_network_helper.h" #include "quiche/quic/tools/quic_spdy_client_base.h" namespace quic { class QuicServerId; namespace test { class QuicDefaultClientPeer; } class QuicDefaultClient : public QuicSpdyClientBase { public: QuicDefaultClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier); QuicDefaultClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache); QuicDefaultClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache); QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier); QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier); QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache); QuicDefaultClient(const QuicDefaultClient&) = delete; QuicDefaultClient& operator=(const QuicDefaultClient&) = delete; ~QuicDefaultClient() override; std::unique_ptr<QuicSession> CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) override; int GetLatestFD() const { return default_network_helper()->GetLatestFD(); } QuicClientDefaultNetworkHelper* default_network_helper(); const QuicClientDefaultNetworkHelper* default_network_helper() const; }; } #endif #include "quiche/quic/tools/quic_default_client.h" #include <memory> #include <utility> #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_simple_client_session.h" namespace quic { QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient( server_address, server_id, supported_versions, QuicConfig(), event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicDefaultClient( server_address, server_id, supported_versions, QuicConfig(), event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), std::move(session_cache)) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicDefaultClient( server_address, server_id, supported_versions, config, event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), std::move(session_cache)) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient(server_address, server_id, supported_versions, QuicConfig(), event_loop, std::move(network_helper), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient(server_address, server_id, supported_versions, config, event_loop, std::move(network_helper), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicSpdyClientBase(server_id, supported_versions, config, new QuicDefaultConnectionHelper(), event_loop->CreateAlarmFactory().release(), std::move(network_helper), std::move(proof_verifier), std::move(session_cache)) { set_server_address(server_address); } QuicDefaultClient::~QuicDefaultClient() = default; std::unique_ptr<QuicSession> QuicDefaultClient::CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) { return std::make_unique<QuicSimpleClientSession>( *config(), supported_versions, connection, this, network_helper(), server_id(), crypto_config(), drop_response_body(), enable_web_transport()); } QuicClientDefaultNetworkHelper* QuicDefaultClient::default_network_helper() { return static_cast<QuicClientDefaultNetworkHelper*>(network_helper()); } const QuicClientDefaultNetworkHelper* QuicDefaultClient::default_network_helper() const { return static_cast<const QuicClientDefaultNetworkHelper*>(network_helper()); } }
#if defined(__linux__) #include "quiche/quic/tools/quic_default_client.h" #include <dirent.h> #include <sys/types.h> #include <memory> #include <string> #include <utility> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace test { namespace { const char* kPathToFds = "/proc/self/fd"; std::string ReadLink(const std::string& path) { std::string result(PATH_MAX, '\0'); ssize_t result_size = readlink(path.c_str(), &result[0], result.size()); if (result_size < 0 && errno == ENOENT) { return ""; } QUICHE_CHECK(result_size > 0 && static_cast<size_t>(result_size) < result.size()) << "result_size:" << result_size << ", errno:" << errno << ", path:" << path; result.resize(result_size); return result; } size_t NumOpenSocketFDs() { size_t socket_count = 0; dirent* file; std::unique_ptr<DIR, int (*)(DIR*)> fd_directory(opendir(kPathToFds), closedir); while ((file = readdir(fd_directory.get())) != nullptr) { absl::string_view name(file->d_name); if (name == "." || name == "..") { continue; } std::string fd_path = ReadLink(absl::StrCat(kPathToFds, "/", name)); if (absl::StartsWith(fd_path, "socket:")) { socket_count++; } } return socket_count; } class QuicDefaultClientTest : public QuicTest { public: QuicDefaultClientTest() : event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())) { CreateAndInitializeQuicClient(); } std::unique_ptr<QuicDefaultClient> CreateAndInitializeQuicClient() { QuicSocketAddress server_address(QuicSocketAddress(TestLoopback(), 0)); QuicServerId server_id("hostname", server_address.port(), false); ParsedQuicVersionVector versions = AllSupportedVersions(); auto client = std::make_unique<QuicDefaultClient>( server_address, server_id, versions, event_loop_.get(), crypto_test_utils::ProofVerifierForTesting()); EXPECT_TRUE(client->Initialize()); return client; } private: std::unique_ptr<QuicEventLoop> event_loop_; }; TEST_F(QuicDefaultClientTest, DoNotLeakSocketFDs) { size_t number_of_open_fds = NumOpenSocketFDs(); const int kNumClients = 50; for (int i = 0; i < kNumClients; ++i) { EXPECT_EQ(number_of_open_fds, NumOpenSocketFDs()); std::unique_ptr<QuicDefaultClient> client(CreateAndInitializeQuicClient()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); } EXPECT_EQ(number_of_open_fds, NumOpenSocketFDs()); } TEST_F(QuicDefaultClientTest, CreateAndCleanUpUDPSockets) { size_t number_of_open_fds = NumOpenSocketFDs(); std::unique_ptr<QuicDefaultClient> client(CreateAndInitializeQuicClient()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); EXPECT_TRUE(client->default_network_helper()->CreateUDPSocketAndBind( client->server_address(), client->bind_to_address(), client->local_port())); EXPECT_EQ(number_of_open_fds + 2, NumOpenSocketFDs()); EXPECT_TRUE(client->default_network_helper()->CreateUDPSocketAndBind( client->server_address(), client->bind_to_address(), client->local_port())); EXPECT_EQ(number_of_open_fds + 3, NumOpenSocketFDs()); client->default_network_helper()->CleanUpUDPSocket(client->GetLatestFD()); EXPECT_EQ(number_of_open_fds + 2, NumOpenSocketFDs()); client->default_network_helper()->CleanUpUDPSocket(client->GetLatestFD()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); } } } } #endif
206
cpp
google/quiche
connect_tunnel
quiche/quic/tools/connect_tunnel.cc
quiche/quic/tools/connect_tunnel_test.cc
#ifndef QUICHE_QUIC_TOOLS_CONNECT_TUNNEL_H_ #define QUICHE_QUIC_TOOLS_CONNECT_TUNNEL_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { class ConnectTunnel : public ConnectingClientSocket::AsyncVisitor { public: ConnectTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, absl::flat_hash_set<QuicServerId> acceptable_destinations); ~ConnectTunnel(); ConnectTunnel(const ConnectTunnel&) = delete; ConnectTunnel& operator=(const ConnectTunnel&) = delete; void OpenTunnel(const spdy::Http2HeaderBlock& request_headers); bool IsConnectedToDestination() const; void SendDataToDestination(absl::string_view data); void OnClientStreamClose(); void ConnectComplete(absl::Status status) override; void ReceiveComplete(absl::StatusOr<quiche::QuicheMemSlice> data) override; void SendComplete(absl::Status status) override; private: void BeginAsyncReadFromDestination(); void OnDataReceivedFromDestination(bool success); void OnDestinationConnectionClosed(); void SendConnectResponse(); void TerminateClientStream( absl::string_view error_description, QuicResetStreamError error_code = QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::CONNECT_ERROR)); const absl::flat_hash_set<QuicServerId> acceptable_destinations_; SocketFactory* const socket_factory_; QuicSimpleServerBackend::RequestHandler* client_stream_request_handler_; std::unique_ptr<ConnectingClientSocket> destination_socket_; bool receive_started_ = false; }; } #endif #include "quiche/quic/tools/connect_tunnel.h" #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_name_lookup.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace { constexpr size_t kReadSize = 4 * 1024; std::optional<QuicServerId> ValidateHeadersAndGetAuthority( const spdy::Http2HeaderBlock& request_headers) { QUICHE_DCHECK(request_headers.contains(":method")); QUICHE_DCHECK(request_headers.find(":method")->second == "CONNECT"); QUICHE_DCHECK(!request_headers.contains(":protocol")); auto scheme_it = request_headers.find(":scheme"); if (scheme_it != request_headers.end()) { QUICHE_DVLOG(1) << "CONNECT request contains unexpected scheme: " << scheme_it->second; return std::nullopt; } auto path_it = request_headers.find(":path"); if (path_it != request_headers.end()) { QUICHE_DVLOG(1) << "CONNECT request contains unexpected path: " << path_it->second; return std::nullopt; } auto authority_it = request_headers.find(":authority"); if (authority_it == request_headers.end() || authority_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT request missing authority"; return std::nullopt; } std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString(authority_it->second); if (!server_id.has_value()) { QUICHE_DVLOG(1) << "CONNECT request authority is malformed: " << authority_it->second; return std::nullopt; } return server_id; } bool ValidateAuthority( const QuicServerId& authority, const absl::flat_hash_set<QuicServerId>& acceptable_destinations) { if (acceptable_destinations.contains(authority)) { return true; } QUICHE_DVLOG(1) << "CONNECT request authority: " << authority.ToHostPortString() << " is not an acceptable allow-listed destiation "; return false; } } ConnectTunnel::ConnectTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, absl::flat_hash_set<QuicServerId> acceptable_destinations) : acceptable_destinations_(std::move(acceptable_destinations)), socket_factory_(socket_factory), client_stream_request_handler_(client_stream_request_handler) { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(socket_factory_); } ConnectTunnel::~ConnectTunnel() { QUICHE_DCHECK_EQ(client_stream_request_handler_, nullptr); QUICHE_DCHECK(!IsConnectedToDestination()); QUICHE_DCHECK(!receive_started_); } void ConnectTunnel::OpenTunnel(const spdy::Http2HeaderBlock& request_headers) { QUICHE_DCHECK(!IsConnectedToDestination()); std::optional<QuicServerId> authority = ValidateHeadersAndGetAuthority(request_headers); if (!authority.has_value()) { TerminateClientStream( "invalid request headers", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::MESSAGE_ERROR)); return; } if (!ValidateAuthority(authority.value(), acceptable_destinations_)) { TerminateClientStream( "disallowed request authority", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::REQUEST_REJECTED)); return; } QuicSocketAddress address = tools::LookupAddress(AF_UNSPEC, authority.value()); if (!address.IsInitialized()) { TerminateClientStream("host resolution error"); return; } destination_socket_ = socket_factory_->CreateTcpClientSocket(address, 0, 0, this); QUICHE_DCHECK(destination_socket_); absl::Status connect_result = destination_socket_->ConnectBlocking(); if (!connect_result.ok()) { TerminateClientStream( "error connecting TCP socket to destination server: " + connect_result.ToString()); return; } QUICHE_DVLOG(1) << "CONNECT tunnel opened from stream " << client_stream_request_handler_->stream_id() << " to " << authority.value().ToHostPortString(); SendConnectResponse(); BeginAsyncReadFromDestination(); } bool ConnectTunnel::IsConnectedToDestination() const { return !!destination_socket_; } void ConnectTunnel::SendDataToDestination(absl::string_view data) { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(!data.empty()); absl::Status send_result = destination_socket_->SendBlocking(std::string(data)); if (!send_result.ok()) { TerminateClientStream("TCP error sending data to destination server: " + send_result.ToString()); } } void ConnectTunnel::OnClientStreamClose() { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT stream " << client_stream_request_handler_->stream_id() << " closed"; client_stream_request_handler_ = nullptr; if (IsConnectedToDestination()) { destination_socket_->Disconnect(); } destination_socket_.reset(); } void ConnectTunnel::ConnectComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectTunnel::ReceiveComplete( absl::StatusOr<quiche::QuicheMemSlice> data) { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(receive_started_); receive_started_ = false; if (!data.ok()) { if (client_stream_request_handler_) { TerminateClientStream("TCP error receiving data from destination server"); } else { QUICHE_DVLOG(1) << "TCP error receiving data from destination server " "after stream already closed."; } return; } else if (data.value().empty()) { OnDestinationConnectionClosed(); return; } QUICHE_DCHECK(client_stream_request_handler_); client_stream_request_handler_->SendStreamData(data.value().AsStringView(), false); BeginAsyncReadFromDestination(); } void ConnectTunnel::SendComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectTunnel::BeginAsyncReadFromDestination() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(!receive_started_); receive_started_ = true; destination_socket_->ReceiveAsync(kReadSize); } void ConnectTunnel::OnDestinationConnectionClosed() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT stream " << client_stream_request_handler_->stream_id() << " destination connection closed"; destination_socket_->Disconnect(); destination_socket_.reset(); QUICHE_DCHECK(client_stream_request_handler_); client_stream_request_handler_->SendStreamData("", true); } void ConnectTunnel::SendConnectResponse() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; QuicBackendResponse response; response.set_headers(std::move(response_headers)); response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectTunnel::TerminateClientStream(absl::string_view error_description, QuicResetStreamError error_code) { QUICHE_DCHECK(client_stream_request_handler_); std::string error_description_str = error_description.empty() ? "" : absl::StrCat(" due to ", error_description); QUICHE_DVLOG(1) << "Terminating CONNECT stream " << client_stream_request_handler_->stream_id() << " with error code " << error_code.ietf_application_code() << error_description_str; client_stream_request_handler_->TerminateStreamWithError(error_code); } }
#include "quiche/quic/tools/connect_tunnel.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AllOf; using ::testing::AnyOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Ge; using ::testing::Gt; using ::testing::InvokeWithoutArgs; using ::testing::IsEmpty; using ::testing::Matcher; using ::testing::NiceMock; using ::testing::Pair; using ::testing::Property; using ::testing::Return; using ::testing::StrictMock; class MockRequestHandler : public QuicSimpleServerBackend::RequestHandler { public: QuicConnectionId connection_id() const override { return TestConnectionId(41212); } QuicStreamId stream_id() const override { return 100; } std::string peer_host() const override { return "127.0.0.1"; } MOCK_METHOD(QuicSpdyStream*, GetStream, (), (override)); MOCK_METHOD(void, OnResponseBackendComplete, (const QuicBackendResponse* response), (override)); MOCK_METHOD(void, SendStreamData, (absl::string_view data, bool close_stream), (override)); MOCK_METHOD(void, TerminateStreamWithError, (QuicResetStreamError error), (override)); }; class MockSocketFactory : public SocketFactory { public: MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateTcpClientSocket, (const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateConnectingUdpClientSocket, (const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); }; class MockSocket : public ConnectingClientSocket { public: MOCK_METHOD(absl::Status, ConnectBlocking, (), (override)); MOCK_METHOD(void, ConnectAsync, (), (override)); MOCK_METHOD(void, Disconnect, (), (override)); MOCK_METHOD(absl::StatusOr<QuicSocketAddress>, GetLocalAddress, (), (override)); MOCK_METHOD(absl::StatusOr<quiche::QuicheMemSlice>, ReceiveBlocking, (QuicByteCount max_size), (override)); MOCK_METHOD(void, ReceiveAsync, (QuicByteCount max_size), (override)); MOCK_METHOD(absl::Status, SendBlocking, (std::string data), (override)); MOCK_METHOD(absl::Status, SendBlocking, (quiche::QuicheMemSlice data), (override)); MOCK_METHOD(void, SendAsync, (std::string data), (override)); MOCK_METHOD(void, SendAsync, (quiche::QuicheMemSlice data), (override)); }; class ConnectTunnelTest : public quiche::test::QuicheTest { public: void SetUp() override { #if defined(_WIN32) WSADATA wsa_data; const WORD version_required = MAKEWORD(2, 2); ASSERT_EQ(WSAStartup(version_required, &wsa_data), 0); #endif auto socket = std::make_unique<StrictMock<MockSocket>>(); socket_ = socket.get(); ON_CALL(socket_factory_, CreateTcpClientSocket( AnyOf(QuicSocketAddress(TestLoopback4(), kAcceptablePort), QuicSocketAddress(TestLoopback6(), kAcceptablePort)), _, _, &tunnel_)) .WillByDefault(Return(ByMove(std::move(socket)))); } protected: static constexpr absl::string_view kAcceptableDestination = "localhost"; static constexpr uint16_t kAcceptablePort = 977; StrictMock<MockRequestHandler> request_handler_; NiceMock<MockSocketFactory> socket_factory_; StrictMock<MockSocket>* socket_; ConnectTunnel tunnel_{ &request_handler_, &socket_factory_, {{std::string(kAcceptableDestination), kAcceptablePort}, {TestLoopback4().ToString(), kAcceptablePort}, {absl::StrCat("[", TestLoopback6().ToString(), "]"), kAcceptablePort}}}; }; TEST_F(ConnectTunnelTest, OpenTunnel) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); spdy::Http2HeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelToIpv4LiteralDestination) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); spdy::Http2HeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(TestLoopback4().ToString(), ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelToIpv6LiteralDestination) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); spdy::Http2HeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat("[", TestLoopback6().ToString(), "]:", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelWithMalformedRequest) { EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR)))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, OpenTunnelWithUnacceptableDestination) { EXPECT_CALL( request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED)))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = "unacceptable.test:100"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, ReceiveFromDestination) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Ge(kData.size()))).Times(2); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, SendStreamData(kData, false)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(MemSliceFromString(kData)); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, SendToDestination) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, SendBlocking(Matcher<std::string>(Eq(kData)))) .WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.SendDataToDestination(kData); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, DestinationDisconnect) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, SendStreamData("", true)); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(quiche::QuicheMemSlice()); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, DestinationTcpConnectionError) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR)))); spdy::Http2HeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(absl::UnknownError("error")); tunnel_.OnClientStreamClose(); } } }
207
cpp
google/quiche
quic_server
quiche/quic/tools/quic_server.cc
quiche/quic/tools/quic_server_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_SERVER_H_ #define QUICHE_QUIC_TOOLS_QUIC_SERVER_H_ #include <memory> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/deterministic_connection_id_generator.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_udp_socket.h" #include "quiche/quic/core/quic_version_manager.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/quic/tools/quic_spdy_server_base.h" namespace quic { namespace test { class QuicServerPeer; } class QuicDispatcher; class QuicPacketReader; class QuicServer : public QuicSpdyServerBase, public QuicSocketEventListener { public: QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend); QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend, const ParsedQuicVersionVector& supported_versions); QuicServer(std::unique_ptr<ProofSource> proof_source, const QuicConfig& config, const QuicCryptoServerConfig::ConfigOptions& crypto_config_options, const ParsedQuicVersionVector& supported_versions, QuicSimpleServerBackend* quic_simple_server_backend, uint8_t expected_server_connection_id_length); QuicServer(const QuicServer&) = delete; QuicServer& operator=(const QuicServer&) = delete; ~QuicServer() override; bool CreateUDPSocketAndListen(const QuicSocketAddress& address) override; void HandleEventsForever() override; void WaitForEvents(); virtual void Shutdown(); void OnSocketEvent(QuicEventLoop* event_loop, QuicUdpSocketFd fd, QuicSocketEventMask events) override; void SetChloMultiplier(size_t multiplier) { crypto_config_.set_chlo_multiplier(multiplier); } void SetPreSharedKey(absl::string_view key) { crypto_config_.set_pre_shared_key(key); } bool overflow_supported() { return overflow_supported_; } QuicPacketCount packets_dropped() { return packets_dropped_; } int port() { return port_; } QuicEventLoop* event_loop() { return event_loop_.get(); } protected: virtual QuicPacketWriter* CreateWriter(int fd); virtual QuicDispatcher* CreateQuicDispatcher(); virtual std::unique_ptr<QuicEventLoop> CreateEventLoop(); const QuicConfig& config() const { return config_; } const QuicCryptoServerConfig& crypto_config() const { return crypto_config_; } QuicDispatcher* dispatcher() { return dispatcher_.get(); } QuicVersionManager* version_manager() { return &version_manager_; } QuicSimpleServerBackend* server_backend() { return quic_simple_server_backend_; } void set_silent_close(bool value) { silent_close_ = value; } uint8_t expected_server_connection_id_length() { return expected_server_connection_id_length_; } ConnectionIdGeneratorInterface& connection_id_generator() { return connection_id_generator_; } private: friend class quic::test::QuicServerPeer; void Initialize(); std::unique_ptr<QuicEventLoop> event_loop_; std::unique_ptr<SocketFactory> socket_factory_; std::unique_ptr<QuicDispatcher> dispatcher_; int port_; QuicUdpSocketFd fd_; QuicPacketCount packets_dropped_; bool overflow_supported_; bool silent_close_; QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCryptoServerConfig::ConfigOptions crypto_config_options_; QuicVersionManager version_manager_; std::unique_ptr<QuicPacketReader> packet_reader_; QuicSimpleServerBackend* quic_simple_server_backend_; uint8_t expected_server_connection_id_length_; DeterministicConnectionIdGenerator connection_id_generator_; }; } #endif #include "quiche/quic/tools/quic_server.h" #include <cstdint> #include <memory> #include <utility> #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/io/event_loop_socket_factory.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_default_packet_writer.h" #include "quiche/quic/core/quic_dispatcher.h" #include "quiche/quic/core/quic_packet_reader.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" #include "quiche/quic/tools/quic_simple_dispatcher.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace { const char kSourceAddressTokenSecret[] = "secret"; } const size_t kNumSessionsToCreatePerSocketEvent = 16; QuicServer::QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend) : QuicServer(std::move(proof_source), quic_simple_server_backend, AllSupportedVersions()) {} QuicServer::QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend, const ParsedQuicVersionVector& supported_versions) : QuicServer(std::move(proof_source), QuicConfig(), QuicCryptoServerConfig::ConfigOptions(), supported_versions, quic_simple_server_backend, kQuicDefaultConnectionIdLength) {} QuicServer::QuicServer( std::unique_ptr<ProofSource> proof_source, const QuicConfig& config, const QuicCryptoServerConfig::ConfigOptions& crypto_config_options, const ParsedQuicVersionVector& supported_versions, QuicSimpleServerBackend* quic_simple_server_backend, uint8_t expected_server_connection_id_length) : port_(0), fd_(-1), packets_dropped_(0), overflow_supported_(false), silent_close_(false), config_(config), crypto_config_(kSourceAddressTokenSecret, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), crypto_config_options_(crypto_config_options), version_manager_(supported_versions), packet_reader_(new QuicPacketReader()), quic_simple_server_backend_(quic_simple_server_backend), expected_server_connection_id_length_( expected_server_connection_id_length), connection_id_generator_(expected_server_connection_id_length) { QUICHE_DCHECK(quic_simple_server_backend_); Initialize(); } void QuicServer::Initialize() { const uint32_t kInitialSessionFlowControlWindow = 1 * 1024 * 1024; const uint32_t kInitialStreamFlowControlWindow = 64 * 1024; if (config_.GetInitialStreamFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindow); } if (config_.GetInitialSessionFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindow); } std::unique_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( QuicRandom::GetInstance(), QuicDefaultClock::Get(), crypto_config_options_)); } QuicServer::~QuicServer() { if (event_loop_ != nullptr) { if (!event_loop_->UnregisterSocket(fd_)) { QUIC_LOG(ERROR) << "Failed to unregister socket: " << fd_; } } (void)socket_api::Close(fd_); fd_ = kInvalidSocketFd; quic_simple_server_backend_->SetSocketFactory(nullptr); } bool QuicServer::CreateUDPSocketAndListen(const QuicSocketAddress& address) { event_loop_ = CreateEventLoop(); socket_factory_ = std::make_unique<EventLoopSocketFactory>( event_loop_.get(), quiche::SimpleBufferAllocator::Get()); quic_simple_server_backend_->SetSocketFactory(socket_factory_.get()); QuicUdpSocketApi socket_api; fd_ = socket_api.Create(address.host().AddressFamilyToInt(), kDefaultSocketReceiveBuffer, kDefaultSocketReceiveBuffer); if (fd_ == kQuicInvalidSocketFd) { QUIC_LOG(ERROR) << "CreateSocket() failed: " << strerror(errno); return false; } overflow_supported_ = socket_api.EnableDroppedPacketCount(fd_); socket_api.EnableReceiveTimestamp(fd_); bool success = socket_api.Bind(fd_, address); if (!success) { QUIC_LOG(ERROR) << "Bind failed: " << strerror(errno); return false; } QUIC_LOG(INFO) << "Listening on " << address.ToString(); port_ = address.port(); if (port_ == 0) { QuicSocketAddress self_address; if (self_address.FromSocket(fd_) != 0) { QUIC_LOG(ERROR) << "Unable to get self address. Error: " << strerror(errno); } port_ = self_address.port(); } bool register_result = event_loop_->RegisterSocket( fd_, kSocketEventReadable | kSocketEventWritable, this); if (!register_result) { return false; } dispatcher_.reset(CreateQuicDispatcher()); dispatcher_->InitializeWithWriter(CreateWriter(fd_)); return true; } QuicPacketWriter* QuicServer::CreateWriter(int fd) { return new QuicDefaultPacketWriter(fd); } QuicDispatcher* QuicServer::CreateQuicDispatcher() { return new QuicSimpleDispatcher( &config_, &crypto_config_, &version_manager_, std::make_unique<QuicDefaultConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), event_loop_->CreateAlarmFactory(), quic_simple_server_backend_, expected_server_connection_id_length_, connection_id_generator_); } std::unique_ptr<QuicEventLoop> QuicServer::CreateEventLoop() { return GetDefaultEventLoop()->Create(QuicDefaultClock::Get()); } void QuicServer::HandleEventsForever() { while (true) { WaitForEvents(); } } void QuicServer::WaitForEvents() { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(50)); } void QuicServer::Shutdown() { if (!silent_close_) { dispatcher_->Shutdown(); } dispatcher_.reset(); event_loop_.reset(); } void QuicServer::OnSocketEvent(QuicEventLoop* , QuicUdpSocketFd fd, QuicSocketEventMask events) { QUICHE_DCHECK_EQ(fd, fd_); if (events & kSocketEventReadable) { QUIC_DVLOG(1) << "EPOLLIN"; dispatcher_->ProcessBufferedChlos(kNumSessionsToCreatePerSocketEvent); bool more_to_read = true; while (more_to_read) { more_to_read = packet_reader_->ReadAndDispatchPackets( fd_, port_, *QuicDefaultClock::Get(), dispatcher_.get(), overflow_supported_ ? &packets_dropped_ : nullptr); } if (dispatcher_->HasChlosBuffered()) { bool success = event_loop_->ArtificiallyNotifyEvent(fd_, kSocketEventReadable); QUICHE_DCHECK(success); } if (!event_loop_->SupportsEdgeTriggered()) { bool success = event_loop_->RearmSocket(fd_, kSocketEventReadable); QUICHE_DCHECK(success); } } if (events & kSocketEventWritable) { dispatcher_->OnCanWrite(); if (!event_loop_->SupportsEdgeTriggered() && dispatcher_->HasPendingWrites()) { bool success = event_loop_->RearmSocket(fd_, kSocketEventWritable); QUICHE_DCHECK(success); } } } }
#include "quiche/quic/tools/quic_server.h" #include <memory> #include <string> #include <utility> #include "absl/base/macros.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/deterministic_connection_id_generator.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_default_packet_writer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_quic_dispatcher.h" #include "quiche/quic/test_tools/quic_server_peer.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" namespace quic { namespace test { using ::testing::_; namespace { class MockQuicSimpleDispatcher : public QuicSimpleDispatcher { public: MockQuicSimpleDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, QuicSimpleServerBackend* quic_simple_server_backend, ConnectionIdGeneratorInterface& generator) : QuicSimpleDispatcher(config, crypto_config, version_manager, std::move(helper), std::move(session_helper), std::move(alarm_factory), quic_simple_server_backend, kQuicDefaultConnectionIdLength, generator) {} ~MockQuicSimpleDispatcher() override = default; MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, HasPendingWrites, (), (const, override)); MOCK_METHOD(bool, HasChlosBuffered, (), (const, override)); MOCK_METHOD(void, ProcessBufferedChlos, (size_t), (override)); }; class TestQuicServer : public QuicServer { public: explicit TestQuicServer(QuicEventLoopFactory* event_loop_factory, QuicMemoryCacheBackend* quic_simple_server_backend) : QuicServer(crypto_test_utils::ProofSourceForTesting(), quic_simple_server_backend), quic_simple_server_backend_(quic_simple_server_backend), event_loop_factory_(event_loop_factory) {} ~TestQuicServer() override = default; MockQuicSimpleDispatcher* mock_dispatcher() { return mock_dispatcher_; } protected: QuicDispatcher* CreateQuicDispatcher() override { mock_dispatcher_ = new MockQuicSimpleDispatcher( &config(), &crypto_config(), version_manager(), std::make_unique<QuicDefaultConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), event_loop()->CreateAlarmFactory(), quic_simple_server_backend_, connection_id_generator()); return mock_dispatcher_; } std::unique_ptr<QuicEventLoop> CreateEventLoop() override { return event_loop_factory_->Create(QuicDefaultClock::Get()); } MockQuicSimpleDispatcher* mock_dispatcher_ = nullptr; QuicMemoryCacheBackend* quic_simple_server_backend_; QuicEventLoopFactory* event_loop_factory_; }; class QuicServerEpollInTest : public QuicTestWithParam<QuicEventLoopFactory*> { public: QuicServerEpollInTest() : server_address_(TestLoopback(), 0), server_(GetParam(), &quic_simple_server_backend_) {} void StartListening() { server_.CreateUDPSocketAndListen(server_address_); server_address_ = QuicSocketAddress(server_address_.host(), server_.port()); ASSERT_TRUE(QuicServerPeer::SetSmallSocket(&server_)); if (!server_.overflow_supported()) { QUIC_LOG(WARNING) << "Overflow not supported. Not testing."; return; } } protected: QuicSocketAddress server_address_; QuicMemoryCacheBackend quic_simple_server_backend_; TestQuicServer server_; }; std::string GetTestParamName( ::testing::TestParamInfo<QuicEventLoopFactory*> info) { return EscapeTestParamName(info.param->GetName()); } INSTANTIATE_TEST_SUITE_P(QuicServerEpollInTests, QuicServerEpollInTest, ::testing::ValuesIn(GetAllSupportedEventLoops()), GetTestParamName); TEST_P(QuicServerEpollInTest, ProcessBufferedCHLOsOnEpollin) { StartListening(); bool more_chlos = true; MockQuicSimpleDispatcher* dispatcher_ = server_.mock_dispatcher(); QUICHE_DCHECK(dispatcher_ != nullptr); EXPECT_CALL(*dispatcher_, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*dispatcher_, ProcessBufferedChlos(_)).Times(2); EXPECT_CALL(*dispatcher_, HasPendingWrites()).Times(testing::AnyNumber()); EXPECT_CALL(*dispatcher_, HasChlosBuffered()) .WillOnce(testing::Return(true)) .WillOnce( DoAll(testing::Assign(&more_chlos, false), testing::Return(false))); QuicUdpSocketApi socket_api; SocketFd fd = socket_api.Create(server_address_.host().AddressFamilyToInt(), kDefaultSocketReceiveBuffer, kDefaultSocketReceiveBuffer); ASSERT_NE(fd, kQuicInvalidSocketFd); char buf[1024]; memset(buf, 0, ABSL_ARRAYSIZE(buf)); QuicUdpPacketInfo packet_info; packet_info.SetPeerAddress(server_address_); WriteResult result = socket_api.WritePacket(fd, buf, sizeof(buf), packet_info); if (result.status != WRITE_STATUS_OK) { QUIC_LOG(ERROR) << "Write error for UDP packet: " << result.error_code; } while (more_chlos) { server_.WaitForEvents(); } } class QuicServerDispatchPacketTest : public QuicTest { public: QuicServerDispatchPacketTest() : crypto_config_("blah", QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), version_manager_(AllSupportedVersions()), event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())), connection_id_generator_(kQuicDefaultConnectionIdLength), dispatcher_(&config_, &crypto_config_, &version_manager_, std::make_unique<QuicDefaultConnectionHelper>(), std::make_unique<QuicSimpleCryptoServerStreamHelper>(), event_loop_->CreateAlarmFactory(), &quic_simple_server_backend_, connection_id_generator_) { dispatcher_.InitializeWithWriter(new QuicDefaultPacketWriter(1234)); } void DispatchPacket(const QuicReceivedPacket& packet) { QuicSocketAddress client_addr, server_addr; dispatcher_.ProcessPacket(server_addr, client_addr, packet); } protected: QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicVersionManager version_manager_; std::unique_ptr<QuicEventLoop> event_loop_; QuicMemoryCacheBackend quic_simple_server_backend_; DeterministicConnectionIdGenerator connection_id_generator_; MockQuicDispatcher dispatcher_; }; TEST_F(QuicServerDispatchPacketTest, DispatchPacket) { unsigned char valid_packet[] = { 0x3C, 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, 0x00 }; QuicReceivedPacket encrypted_valid_packet( reinterpret_cast<char*>(valid_packet), ABSL_ARRAYSIZE(valid_packet), QuicTime::Zero(), false); EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1); DispatchPacket(encrypted_valid_packet); } } } }
208
cpp
google/quiche
quic_url
quiche/quic/tools/quic_url.cc
quiche/quic/tools/quic_url_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_URL_H_ #define QUICHE_QUIC_TOOLS_QUIC_URL_H_ #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_googleurl.h" namespace quic { class QuicUrl { public: QuicUrl() = default; explicit QuicUrl(absl::string_view url); QuicUrl(absl::string_view url, absl::string_view default_scheme); bool IsValid() const; std::string ToString() const; std::string HostPort() const; std::string PathParamsQuery() const; std::string scheme() const; std::string host() const; std::string path() const; uint16_t port() const; private: GURL url_; }; } #endif #include "quiche/quic/tools/quic_url.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace quic { static constexpr size_t kMaxHostNameLength = 256; QuicUrl::QuicUrl(absl::string_view url) : url_(static_cast<std::string>(url)) {} QuicUrl::QuicUrl(absl::string_view url, absl::string_view default_scheme) : QuicUrl(url) { if (url_.has_scheme()) { return; } url_ = GURL(absl::StrCat(default_scheme, ": } std::string QuicUrl::ToString() const { if (IsValid()) { return url_.spec(); } return ""; } bool QuicUrl::IsValid() const { if (!url_.is_valid() || !url_.has_scheme()) { return false; } if (url_.has_host() && url_.host().length() > kMaxHostNameLength) { return false; } return true; } std::string QuicUrl::HostPort() const { if (!IsValid() || !url_.has_host()) { return ""; } std::string host = url_.host(); int port = url_.IntPort(); if (port == url::PORT_UNSPECIFIED) { return host; } return absl::StrCat(host, ":", port); } std::string QuicUrl::PathParamsQuery() const { if (!IsValid() || !url_.has_path()) { return "/"; } return url_.PathForRequest(); } std::string QuicUrl::scheme() const { if (!IsValid()) { return ""; } return url_.scheme(); } std::string QuicUrl::host() const { if (!IsValid()) { return ""; } return url_.HostNoBrackets(); } std::string QuicUrl::path() const { if (!IsValid()) { return ""; } return url_.path(); } uint16_t QuicUrl::port() const { if (!IsValid()) { return 0; } int port = url_.EffectiveIntPort(); if (port == url::PORT_UNSPECIFIED) { return 0; } return port; } }
#include "quiche/quic/tools/quic_url.h" #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicUrlTest : public QuicTest {}; TEST_F(QuicUrlTest, Basic) { std::string url_str = "www.example.com"; QuicUrl url(url_str); EXPECT_FALSE(url.IsValid()); url_str = "http: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ(80u, url.port()); url_str = "https: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("https: url.ToString()); EXPECT_EQ("https", url.scheme()); EXPECT_EQ("www.example.com:12345", url.HostPort()); EXPECT_EQ("/path/to/resource?a=1&campaign=2", url.PathParamsQuery()); EXPECT_EQ(12345u, url.port()); url_str = "ftp: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("ftp: EXPECT_EQ("ftp", url.scheme()); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ(21u, url.port()); } TEST_F(QuicUrlTest, DefaultScheme) { std::string url_str = "www.example.com"; QuicUrl url(url_str, "http"); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); url_str = "http: url = QuicUrl(url_str, "https"); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); url_str = "www.example.com"; url = QuicUrl(url_str, "ftp"); EXPECT_EQ("ftp: EXPECT_EQ("ftp", url.scheme()); } TEST_F(QuicUrlTest, IsValid) { std::string url_str = "ftp: EXPECT_TRUE(QuicUrl(url_str).IsValid()); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); url_str = "%http: EXPECT_FALSE(QuicUrl(url_str).IsValid()); std::string host(1024, 'a'); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); } TEST_F(QuicUrlTest, HostPort) { std::string url_str = "http: QuicUrl url(url_str); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("www.example.com:81", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(81u, url.port()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("192.168.1.1", url.HostPort()); EXPECT_EQ("192.168.1.1", url.host()); EXPECT_EQ(443u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("[2001::1]", url.HostPort()); EXPECT_EQ("2001::1", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("[2001::1]:81", url.HostPort()); EXPECT_EQ("2001::1", url.host()); EXPECT_EQ(81u, url.port()); } TEST_F(QuicUrlTest, PathParamsQuery) { std::string url_str = "https: QuicUrl url(url_str); EXPECT_EQ("/path/to/resource?a=1&campaign=2", url.PathParamsQuery()); EXPECT_EQ("/path/to/resource", url.path()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("/?", url.PathParamsQuery()); EXPECT_EQ("/", url.path()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ("/", url.path()); } } } }
209
cpp
google/quiche
quic_tcp_like_trace_converter
quiche/quic/tools/quic_tcp_like_trace_converter.cc
quiche/quic/tools/quic_tcp_like_trace_converter_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_TCP_LIKE_TRACE_CONVERTER_H_ #define QUICHE_QUIC_TOOLS_QUIC_TCP_LIKE_TRACE_CONVERTER_H_ #include <vector> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/core/quic_interval_set.h" #include "quiche/quic/core/quic_types.h" namespace quic { class QuicTcpLikeTraceConverter { public: struct StreamOffsetSegment { StreamOffsetSegment(); StreamOffsetSegment(QuicStreamOffset stream_offset, uint64_t connection_offset, QuicByteCount data_length); QuicInterval<QuicStreamOffset> stream_data; uint64_t connection_offset; }; QuicTcpLikeTraceConverter(); QuicTcpLikeTraceConverter(const QuicTcpLikeTraceConverter& other) = delete; QuicTcpLikeTraceConverter(QuicTcpLikeTraceConverter&& other) = delete; ~QuicTcpLikeTraceConverter() {} QuicIntervalSet<uint64_t> OnCryptoFrameSent(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length); QuicIntervalSet<uint64_t> OnStreamFrameSent(QuicStreamId stream_id, QuicStreamOffset offset, QuicByteCount data_length, bool fin); QuicInterval<uint64_t> OnControlFrameSent(QuicControlFrameId control_frame_id, QuicByteCount control_frame_length); private: struct StreamInfo { StreamInfo(); std::vector<StreamOffsetSegment> segments; bool fin; }; QuicIntervalSet<uint64_t> OnFrameSent(QuicStreamOffset offset, QuicByteCount data_length, bool fin, StreamInfo* info); StreamInfo crypto_frames_info_[NUM_ENCRYPTION_LEVELS]; absl::flat_hash_map<QuicStreamId, StreamInfo> streams_info_; absl::flat_hash_map<QuicControlFrameId, QuicInterval<uint64_t>> control_frames_info_; QuicControlFrameId largest_observed_control_frame_id_; uint64_t connection_offset_; }; } #endif #include "quiche/quic/tools/quic_tcp_like_trace_converter.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { QuicTcpLikeTraceConverter::QuicTcpLikeTraceConverter() : largest_observed_control_frame_id_(kInvalidControlFrameId), connection_offset_(0) {} QuicTcpLikeTraceConverter::StreamOffsetSegment::StreamOffsetSegment() : connection_offset(0) {} QuicTcpLikeTraceConverter::StreamOffsetSegment::StreamOffsetSegment( QuicStreamOffset stream_offset, uint64_t connection_offset, QuicByteCount data_length) : stream_data(stream_offset, stream_offset + data_length), connection_offset(connection_offset) {} QuicTcpLikeTraceConverter::StreamInfo::StreamInfo() : fin(false) {} QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnCryptoFrameSent( EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length) { if (level >= NUM_ENCRYPTION_LEVELS) { QUIC_BUG(quic_bug_10907_1) << "Invalid encryption level"; return {}; } return OnFrameSent(offset, data_length, false, &crypto_frames_info_[level]); } QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnStreamFrameSent( QuicStreamId stream_id, QuicStreamOffset offset, QuicByteCount data_length, bool fin) { return OnFrameSent( offset, data_length, fin, &streams_info_.emplace(stream_id, StreamInfo()).first->second); } QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnFrameSent( QuicStreamOffset offset, QuicByteCount data_length, bool fin, StreamInfo* info) { QuicIntervalSet<uint64_t> connection_offsets; if (fin) { ++data_length; } for (const auto& segment : info->segments) { QuicInterval<QuicStreamOffset> retransmission(offset, offset + data_length); retransmission.IntersectWith(segment.stream_data); if (retransmission.Empty()) { continue; } const uint64_t connection_offset = segment.connection_offset + retransmission.min() - segment.stream_data.min(); connection_offsets.Add(connection_offset, connection_offset + retransmission.Length()); } if (info->fin) { return connection_offsets; } QuicStreamOffset least_unsent_offset = info->segments.empty() ? 0 : info->segments.back().stream_data.max(); if (least_unsent_offset >= offset + data_length) { return connection_offsets; } QuicStreamOffset new_data_offset = std::max(least_unsent_offset, offset); QuicByteCount new_data_length = offset + data_length - new_data_offset; connection_offsets.Add(connection_offset_, connection_offset_ + new_data_length); if (!info->segments.empty() && new_data_offset == least_unsent_offset && connection_offset_ == info->segments.back().connection_offset + info->segments.back().stream_data.Length()) { info->segments.back().stream_data.SetMax(new_data_offset + new_data_length); } else { info->segments.emplace_back(new_data_offset, connection_offset_, new_data_length); } info->fin = fin; connection_offset_ += new_data_length; return connection_offsets; } QuicInterval<uint64_t> QuicTcpLikeTraceConverter::OnControlFrameSent( QuicControlFrameId control_frame_id, QuicByteCount control_frame_length) { if (control_frame_id > largest_observed_control_frame_id_) { QuicInterval<uint64_t> connection_offset = QuicInterval<uint64_t>( connection_offset_, connection_offset_ + control_frame_length); connection_offset_ += control_frame_length; control_frames_info_[control_frame_id] = connection_offset; largest_observed_control_frame_id_ = control_frame_id; return connection_offset; } const auto iter = control_frames_info_.find(control_frame_id); if (iter == control_frames_info_.end()) { return {}; } return iter->second; } }
#include "quiche/quic/tools/quic_tcp_like_trace_converter.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { TEST(QuicTcpLikeTraceConverterTest, BasicTest) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnStreamFrameSent(1, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 200), converter.OnStreamFrameSent(3, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(200, 300), converter.OnStreamFrameSent(3, 100, 100, false)); EXPECT_EQ(QuicInterval<uint64_t>(300, 450), converter.OnControlFrameSent(2, 150)); EXPECT_EQ(QuicIntervalSet<uint64_t>(450, 550), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicInterval<uint64_t>(550, 650), converter.OnControlFrameSent(3, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(650, 850), converter.OnStreamFrameSent(3, 200, 200, false)); EXPECT_EQ(QuicInterval<uint64_t>(850, 1050), converter.OnControlFrameSent(4, 200)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1050, 1100), converter.OnStreamFrameSent(1, 200, 50, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1100, 1150), converter.OnStreamFrameSent(1, 250, 50, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1150, 1350), converter.OnStreamFrameSent(3, 400, 200, false)); QuicIntervalSet<uint64_t> expected; expected.Add(50, 100); expected.Add(450, 550); expected.Add(1050, 1150); expected.Add(1350, 1401); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 50, 300, true)); expected.Clear(); expected.Add(250, 300); expected.Add(650, 850); expected.Add(1150, 1250); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 150, 350, false)); expected.Clear(); expected.Add(750, 850); expected.Add(1150, 1350); expected.Add(1401, 1602); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 300, 500, true)); expected.Clear(); expected.Add(1601, 1602); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 800, 0, true)); QuicInterval<uint64_t> expected2; EXPECT_EQ(expected2, converter.OnControlFrameSent(1, 100)); expected2 = {300, 450}; EXPECT_EQ(expected2, converter.OnControlFrameSent(2, 200)); expected2 = {1602, 1702}; EXPECT_EQ(expected2, converter.OnControlFrameSent(10, 100)); } TEST(QuicTcpLikeTraceConverterTest, FuzzerTest) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 300), converter.OnStreamFrameSent(3, 200, 200, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(300, 400), converter.OnStreamFrameSent(1, 300, 100, false)); QuicIntervalSet<uint64_t> expected; expected.Add(0, 100); expected.Add(300, 501); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 0, 500, true)); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 50, 600, false)); } TEST(QuicTcpLikeTraceConverterTest, OnCryptoFrameSent) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnCryptoFrameSent(ENCRYPTION_INITIAL, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 200), converter.OnStreamFrameSent(1, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(200, 300), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(300, 400), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(400, 500), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 100, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnCryptoFrameSent(ENCRYPTION_INITIAL, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(400, 500), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 100, 100)); } } } }
210
cpp
google/quiche
simple_ticket_crypter
quiche/quic/tools/simple_ticket_crypter.cc
quiche/quic/tools/simple_ticket_crypter_test.cc
#ifndef QUICHE_QUIC_TOOLS_SIMPLE_TICKET_CRYPTER_H_ #define QUICHE_QUIC_TOOLS_SIMPLE_TICKET_CRYPTER_H_ #include "openssl/aead.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_time.h" namespace quic { class QUIC_NO_EXPORT SimpleTicketCrypter : public quic::ProofSource::TicketCrypter { public: explicit SimpleTicketCrypter(QuicClock* clock); ~SimpleTicketCrypter() override; size_t MaxOverhead() override; std::vector<uint8_t> Encrypt(absl::string_view in, absl::string_view encryption_key) override; void Decrypt( absl::string_view in, std::shared_ptr<quic::ProofSource::DecryptCallback> callback) override; private: std::vector<uint8_t> Decrypt(absl::string_view in); void MaybeRotateKeys(); static constexpr size_t kKeySize = 16; struct Key { uint8_t key[kKeySize]; bssl::ScopedEVP_AEAD_CTX aead_ctx; QuicTime expiration = QuicTime::Zero(); }; std::unique_ptr<Key> NewKey(); std::unique_ptr<Key> current_key_; std::unique_ptr<Key> previous_key_; uint8_t key_epoch_ = 0; QuicClock* clock_; }; } #endif #include "quiche/quic/tools/simple_ticket_crypter.h" #include <memory> #include <utility> #include <vector> #include "openssl/aead.h" #include "openssl/rand.h" namespace quic { namespace { constexpr QuicTime::Delta kTicketKeyLifetime = QuicTime::Delta::FromSeconds(60 * 60 * 24 * 7); constexpr size_t kEpochSize = 1; constexpr size_t kIVSize = 16; constexpr size_t kAuthTagSize = 16; constexpr size_t kIVOffset = kEpochSize; constexpr size_t kMessageOffset = kIVOffset + kIVSize; } SimpleTicketCrypter::SimpleTicketCrypter(QuicClock* clock) : clock_(clock) { RAND_bytes(&key_epoch_, 1); current_key_ = NewKey(); } SimpleTicketCrypter::~SimpleTicketCrypter() = default; size_t SimpleTicketCrypter::MaxOverhead() { return kEpochSize + kIVSize + kAuthTagSize; } std::vector<uint8_t> SimpleTicketCrypter::Encrypt( absl::string_view in, absl::string_view encryption_key) { QUICHE_DCHECK(encryption_key.empty()); MaybeRotateKeys(); std::vector<uint8_t> out(in.size() + MaxOverhead()); out[0] = key_epoch_; RAND_bytes(out.data() + kIVOffset, kIVSize); size_t out_len; const EVP_AEAD_CTX* ctx = current_key_->aead_ctx.get(); if (!EVP_AEAD_CTX_seal(ctx, out.data() + kMessageOffset, &out_len, out.size() - kMessageOffset, out.data() + kIVOffset, kIVSize, reinterpret_cast<const uint8_t*>(in.data()), in.size(), nullptr, 0)) { return std::vector<uint8_t>(); } out.resize(out_len + kMessageOffset); return out; } std::vector<uint8_t> SimpleTicketCrypter::Decrypt(absl::string_view in) { MaybeRotateKeys(); if (in.size() < kMessageOffset) { return std::vector<uint8_t>(); } const uint8_t* input = reinterpret_cast<const uint8_t*>(in.data()); std::vector<uint8_t> out(in.size() - kMessageOffset); size_t out_len; const EVP_AEAD_CTX* ctx = current_key_->aead_ctx.get(); if (input[0] != key_epoch_) { if (input[0] == static_cast<uint8_t>(key_epoch_ - 1) && previous_key_) { ctx = previous_key_->aead_ctx.get(); } else { return std::vector<uint8_t>(); } } if (!EVP_AEAD_CTX_open(ctx, out.data(), &out_len, out.size(), input + kIVOffset, kIVSize, input + kMessageOffset, in.size() - kMessageOffset, nullptr, 0)) { return std::vector<uint8_t>(); } out.resize(out_len); return out; } void SimpleTicketCrypter::Decrypt( absl::string_view in, std::shared_ptr<quic::ProofSource::DecryptCallback> callback) { callback->Run(Decrypt(in)); } void SimpleTicketCrypter::MaybeRotateKeys() { QuicTime now = clock_->ApproximateNow(); if (current_key_->expiration < now) { previous_key_ = std::move(current_key_); current_key_ = NewKey(); key_epoch_++; } } std::unique_ptr<SimpleTicketCrypter::Key> SimpleTicketCrypter::NewKey() { auto key = std::make_unique<SimpleTicketCrypter::Key>(); RAND_bytes(key->key, kKeySize); EVP_AEAD_CTX_init(key->aead_ctx.get(), EVP_aead_aes_128_gcm(), key->key, kKeySize, EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr); key->expiration = clock_->ApproximateNow() + kTicketKeyLifetime; return key; } }
#include "quiche/quic/tools/simple_ticket_crypter.h" #include <memory> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { namespace { constexpr QuicTime::Delta kOneDay = QuicTime::Delta::FromSeconds(60 * 60 * 24); } class DecryptCallback : public quic::ProofSource::DecryptCallback { public: explicit DecryptCallback(std::vector<uint8_t>* out) : out_(out) {} void Run(std::vector<uint8_t> plaintext) override { *out_ = plaintext; } private: std::vector<uint8_t>* out_; }; absl::string_view StringPiece(const std::vector<uint8_t>& in) { return absl::string_view(reinterpret_cast<const char*>(in.data()), in.size()); } class SimpleTicketCrypterTest : public QuicTest { public: SimpleTicketCrypterTest() : ticket_crypter_(&mock_clock_) {} protected: MockClock mock_clock_; SimpleTicketCrypter ticket_crypter_; }; TEST_F(SimpleTicketCrypterTest, EncryptDecrypt) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(plaintext, ciphertext); std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_EQ(out_plaintext, plaintext); } TEST_F(SimpleTicketCrypterTest, CiphertextsDiffer) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext1 = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); std::vector<uint8_t> ciphertext2 = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(ciphertext1, ciphertext2); } TEST_F(SimpleTicketCrypterTest, DecryptionFailureWithModifiedCiphertext) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(plaintext, ciphertext); for (size_t i = 0; i < ciphertext.size(); i++) { SCOPED_TRACE(i); std::vector<uint8_t> munged_ciphertext = ciphertext; munged_ciphertext[i] ^= 1; std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(munged_ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } } TEST_F(SimpleTicketCrypterTest, DecryptionFailureWithEmptyCiphertext) { std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(absl::string_view(), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } TEST_F(SimpleTicketCrypterTest, KeyRotation) { std::vector<uint8_t> plaintext = {1, 2, 3}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_FALSE(ciphertext.empty()); mock_clock_.AdvanceTime(kOneDay * 8); std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_EQ(out_plaintext, plaintext); mock_clock_.AdvanceTime(kOneDay * 8); ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } } }
211
cpp
google/quiche
quic_memory_cache_backend
quiche/quic/tools/quic_memory_cache_backend.cc
quiche/quic/tools/quic_memory_cache_backend_test.cc
#ifndef QUICHE_QUIC_TOOLS_QUIC_MEMORY_CACHE_BACKEND_H_ #define QUICHE_QUIC_TOOLS_QUIC_MEMORY_CACHE_BACKEND_H_ #include <list> #include <map> #include <memory> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_framer.h" namespace quic { class QuicMemoryCacheBackend : public QuicSimpleServerBackend { public: class ResourceFile { public: explicit ResourceFile(const std::string& file_name); ResourceFile(const ResourceFile&) = delete; ResourceFile& operator=(const ResourceFile&) = delete; virtual ~ResourceFile(); void Read(); void SetHostPathFromBase(absl::string_view base); const std::string& file_name() { return file_name_; } absl::string_view host() { return host_; } absl::string_view path() { return path_; } const spdy::Http2HeaderBlock& spdy_headers() { return spdy_headers_; } absl::string_view body() { return body_; } const std::vector<absl::string_view>& push_urls() { return push_urls_; } private: void HandleXOriginalUrl(); absl::string_view RemoveScheme(absl::string_view url); std::string file_name_; std::string file_contents_; absl::string_view body_; spdy::Http2HeaderBlock spdy_headers_; absl::string_view x_original_url_; std::vector<absl::string_view> push_urls_; std::string host_; std::string path_; }; QuicMemoryCacheBackend(); QuicMemoryCacheBackend(const QuicMemoryCacheBackend&) = delete; QuicMemoryCacheBackend& operator=(const QuicMemoryCacheBackend&) = delete; ~QuicMemoryCacheBackend() override; const QuicBackendResponse* GetResponse(absl::string_view host, absl::string_view path) const; void AddSimpleResponse(absl::string_view host, absl::string_view path, int response_code, absl::string_view body); void AddResponse(absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body); void AddResponse(absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, spdy::Http2HeaderBlock response_trailers); void AddResponseWithEarlyHints( absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, const std::vector<spdy::Http2HeaderBlock>& early_hints); void AddSpecialResponse( absl::string_view host, absl::string_view path, QuicBackendResponse::SpecialResponseType response_type); void AddSpecialResponse( absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, QuicBackendResponse::SpecialResponseType response_type); bool SetResponseDelay(absl::string_view host, absl::string_view path, QuicTime::Delta delay); void AddDefaultResponse(QuicBackendResponse* response); void GenerateDynamicResponses(); void EnableWebTransport(); bool InitializeBackend(const std::string& cache_directory) override; bool IsBackendInitialized() const override; void FetchResponseFromBackend( const spdy::Http2HeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* quic_stream) override; void CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* quic_stream) override; WebTransportResponse ProcessWebTransportRequest( const spdy::Http2HeaderBlock& request_headers, WebTransportSession* session) override; bool SupportsWebTransport() override { return enable_webtransport_; } private: void AddResponseImpl(absl::string_view host, absl::string_view path, QuicBackendResponse::SpecialResponseType response_type, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, spdy::Http2HeaderBlock response_trailers, const std::vector<spdy::Http2HeaderBlock>& early_hints); std::string GetKey(absl::string_view host, absl::string_view path) const; absl::flat_hash_map<std::string, std::unique_ptr<QuicBackendResponse>> responses_ QUIC_GUARDED_BY(response_mutex_); std::unique_ptr<QuicBackendResponse> default_response_ QUIC_GUARDED_BY(response_mutex_); std::unique_ptr<QuicBackendResponse> generate_bytes_response_ QUIC_GUARDED_BY(response_mutex_); mutable QuicMutex response_mutex_; bool cache_initialized_; bool enable_webtransport_ = false; }; } #endif #include "quiche/quic/tools/quic_memory_cache_backend.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/web_transport_test_visitors.h" #include "quiche/common/platform/api/quiche_file_utils.h" #include "quiche/common/quiche_text_utils.h" using spdy::Http2HeaderBlock; using spdy::kV3LowestPriority; namespace quic { QuicMemoryCacheBackend::ResourceFile::ResourceFile(const std::string& file_name) : file_name_(file_name) {} QuicMemoryCacheBackend::ResourceFile::~ResourceFile() = default; void QuicMemoryCacheBackend::ResourceFile::Read() { std::optional<std::string> maybe_file_contents = quiche::ReadFileContents(file_name_); if (!maybe_file_contents) { QUIC_LOG(DFATAL) << "Failed to read file for the memory cache backend: " << file_name_; return; } file_contents_ = *maybe_file_contents; for (size_t start = 0; start < file_contents_.length();) { size_t pos = file_contents_.find('\n', start); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } size_t len = pos - start; if (file_contents_[pos - 1] == '\r') { len -= 1; } absl::string_view line(file_contents_.data() + start, len); start = pos + 1; if (line.empty()) { body_ = absl::string_view(file_contents_.data() + start, file_contents_.size() - start); break; } if (line.substr(0, 4) == "HTTP") { pos = line.find(' '); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } spdy_headers_[":status"] = line.substr(pos + 1, 3); continue; } pos = line.find(": "); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } spdy_headers_.AppendValueOrAddHeader( quiche::QuicheTextUtils::ToLower(line.substr(0, pos)), line.substr(pos + 2)); } spdy_headers_.erase("connection"); if (auto it = spdy_headers_.find("x-original-url"); it != spdy_headers_.end()) { x_original_url_ = it->second; HandleXOriginalUrl(); } } void QuicMemoryCacheBackend::ResourceFile::SetHostPathFromBase( absl::string_view base) { QUICHE_DCHECK(base[0] != '/') << base; size_t path_start = base.find_first_of('/'); if (path_start == absl::string_view::npos) { host_ = std::string(base); path_ = ""; return; } host_ = std::string(base.substr(0, path_start)); size_t query_start = base.find_first_of(','); if (query_start > 0) { path_ = std::string(base.substr(path_start, query_start - 1)); } else { path_ = std::string(base.substr(path_start)); } } absl::string_view QuicMemoryCacheBackend::ResourceFile::RemoveScheme( absl::string_view url) { if (absl::StartsWith(url, "https: url.remove_prefix(8); } else if (absl::StartsWith(url, "http: url.remove_prefix(7); } return url; } void QuicMemoryCacheBackend::ResourceFile::HandleXOriginalUrl() { absl::string_view url(x_original_url_); SetHostPathFromBase(RemoveScheme(url)); } const QuicBackendResponse* QuicMemoryCacheBackend::GetResponse( absl::string_view host, absl::string_view path) const { QuicWriterMutexLock lock(&response_mutex_); auto it = responses_.find(GetKey(host, path)); if (it == responses_.end()) { uint64_t ignored = 0; if (generate_bytes_response_) { if (absl::SimpleAtoi(absl::string_view(path.data() + 1, path.size() - 1), &ignored)) { return generate_bytes_response_.get(); } } QUIC_DVLOG(1) << "Get response for resource failed: host " << host << " path " << path; if (default_response_) { return default_response_.get(); } return nullptr; } return it->second.get(); } using SpecialResponseType = QuicBackendResponse::SpecialResponseType; void QuicMemoryCacheBackend::AddSimpleResponse(absl::string_view host, absl::string_view path, int response_code, absl::string_view body) { Http2HeaderBlock response_headers; response_headers[":status"] = absl::StrCat(response_code); response_headers["content-length"] = absl::StrCat(body.length()); AddResponse(host, path, std::move(response_headers), body); } void QuicMemoryCacheBackend::AddDefaultResponse(QuicBackendResponse* response) { QuicWriterMutexLock lock(&response_mutex_); default_response_.reset(response); } void QuicMemoryCacheBackend::AddResponse(absl::string_view host, absl::string_view path, Http2HeaderBlock response_headers, absl::string_view response_body) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, Http2HeaderBlock(), std::vector<spdy::Http2HeaderBlock>()); } void QuicMemoryCacheBackend::AddResponse(absl::string_view host, absl::string_view path, Http2HeaderBlock response_headers, absl::string_view response_body, Http2HeaderBlock response_trailers) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, std::move(response_trailers), std::vector<spdy::Http2HeaderBlock>()); } bool QuicMemoryCacheBackend::SetResponseDelay(absl::string_view host, absl::string_view path, QuicTime::Delta delay) { QuicWriterMutexLock lock(&response_mutex_); auto it = responses_.find(GetKey(host, path)); if (it == responses_.end()) return false; it->second->set_delay(delay); return true; } void QuicMemoryCacheBackend::AddResponseWithEarlyHints( absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, const std::vector<spdy::Http2HeaderBlock>& early_hints) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, Http2HeaderBlock(), early_hints); } void QuicMemoryCacheBackend::AddSpecialResponse( absl::string_view host, absl::string_view path, SpecialResponseType response_type) { AddResponseImpl(host, path, response_type, Http2HeaderBlock(), "", Http2HeaderBlock(), std::vector<spdy::Http2HeaderBlock>()); } void QuicMemoryCacheBackend::AddSpecialResponse( absl::string_view host, absl::string_view path, spdy::Http2HeaderBlock response_headers, absl::string_view response_body, SpecialResponseType response_type) { AddResponseImpl(host, path, response_type, std::move(response_headers), response_body, Http2HeaderBlock(), std::vector<spdy::Http2HeaderBlock>()); } QuicMemoryCacheBackend::QuicMemoryCacheBackend() : cache_initialized_(false) {} bool QuicMemoryCacheBackend::InitializeBackend( const std::string& cache_directory) { if (cache_directory.empty()) { QUIC_BUG(quic_bug_10932_1) << "cache_directory must not be empty."; return false; } QUIC_LOG(INFO) << "Attempting to initialize QuicMemoryCacheBackend from directory: " << cache_directory; std::vector<std::string> files; if (!quiche::EnumerateDirectoryRecursively(cache_directory, files)) { QUIC_BUG(QuicMemoryCacheBackend unreadable directory) << "Can't read QuicMemoryCacheBackend directory: " << cache_directory; return false; } for (const auto& filename : files) { std::unique_ptr<ResourceFile> resource_file(new ResourceFile(filename)); std::string base(resource_file->file_name()); for (size_t i = 0; i < base.length(); ++i) { if (base[i] == '\\') { base[i] = '/'; } } base.erase(0, cache_directory.length()); if (base[0] == '/') { base.erase(0, 1); } resource_file->SetHostPathFromBase(base); resource_file->Read(); AddResponse(resource_file->host(), resource_file->path(), resource_file->spdy_headers().Clone(), resource_file->body()); } cache_initialized_ = true; return true; } void QuicMemoryCacheBackend::GenerateDynamicResponses() { QuicWriterMutexLock lock(&response_mutex_); spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; generate_bytes_response_ = std::make_unique<QuicBackendResponse>(); generate_bytes_response_->set_headers(std::move(response_headers)); generate_bytes_response_->set_response_type( QuicBackendResponse::GENERATE_BYTES); } void QuicMemoryCacheBackend::EnableWebTransport() { enable_webtransport_ = true; } bool QuicMemoryCacheBackend::IsBackendInitialized() const { return cache_initialized_; } void QuicMemoryCacheBackend::FetchResponseFromBackend( const Http2HeaderBlock& request_headers, const std::string& , QuicSimpleServerBackend::RequestHandler* quic_stream) { const QuicBackendResponse* quic_response = nullptr; auto authority = request_headers.find(":authority"); auto path = request_headers.find(":path"); if (authority != request_headers.end() && path != request_headers.end()) { quic_response = GetResponse(authority->second, path->second); } std::string request_url; if (authority != request_headers.end()) { request_url = std::string(authority->second); } if (path != request_headers.end()) { request_url += std::string(path->second); } QUIC_DVLOG(1) << "Fetching QUIC response from backend in-memory cache for url " << request_url; quic_stream->OnResponseBackendComplete(quic_response); } void QuicMemoryCacheBackend::CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* ) {} QuicMemoryCacheBackend::WebTransportResponse QuicMemoryCacheBackend::ProcessWebTransportRequest( const spdy::Http2HeaderBlock& request_headers, WebTransportSession* session) { if (!SupportsWebTransport()) { return QuicSimpleServerBackend::ProcessWebTransportRequest(request_headers, session); } auto path_it = request_headers.find(":path"); if (path_it == request_headers.end()) { WebTransportResponse response; response.response_headers[":status"] = "400"; return response; } absl::string_view path = path_it->second; if (path == "/echo") { WebTransportResponse response; response.response_headers[":status"] = "200"; response.visitor = std::make_unique<EchoWebTransportSessionVisitor>(session); return response; } WebTransportResponse response; response.response_headers[":status"] = "404"; return response; } QuicMemoryCacheBackend::~QuicMemoryCacheBackend() { { QuicWriterMutexLock lock(&response_mutex_); responses_.clear(); } } void QuicMemoryCacheBackend::AddResponseImpl( absl::string_view host, absl::string_view path, SpecialResponseType response_type, Http2HeaderBlock response_headers, absl::string_view response_body, Http2HeaderBlock response_trailers, const std::vector<spdy::Http2HeaderBlock>& early_hints) { QuicWriterMutexLock lock(&response_mutex_); QUICHE_DCHECK(!host.empty()) << "Host must be populated, e.g. \"www.google.com\""; std::string key = GetKey(host, path); if (responses_.contains(key)) { QUIC_BUG(quic_bug_10932_3) << "Response for '" << key << "' already exists!"; return; } auto new_response = std::make_unique<QuicBackendResponse>(); new_response->set_response_type(response_type); new_response->set_headers(std::move(response_headers)); new_response->set_body(response_body); new_response->set_trailers(std::move(response_trailers)); for (auto& headers : early_hints) { new_response->AddEarlyHints(headers); } QUIC_DVLOG(1) << "Add response with key " << key; responses_[key] = std::move(new_response); } std::string QuicMemoryCacheBackend::GetKey(absl::string_view host, absl::string_view path) const { std::string host_string = std::string(host); size_t port = host_string.find(':'); if (port != std::string::npos) host_string = std::string(host_string.c_str(), port); return host_string + std::string(path); } }
#include "quiche/quic/tools/quic_memory_cache_backend.h" #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/common/platform/api/quiche_file_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic { namespace test { namespace { using Response = QuicBackendResponse; } class QuicMemoryCacheBackendTest : public QuicTest { protected: void CreateRequest(std::string host, std::string path, spdy::Http2HeaderBlock* headers) { (*headers)[":method"] = "GET"; (*headers)[":path"] = path; (*headers)[":authority"] = host; (*headers)[":scheme"] = "https"; } std::string CacheDirectory() { return quiche::test::QuicheGetTestMemoryCachePath(); } QuicMemoryCacheBackend cache_; }; TEST_F(QuicMemoryCacheBackendTest, GetResponseNoMatch) { const Response* response = cache_.GetResponse("mail.google.com", "/index.html"); ASSERT_FALSE(response); } TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseGetResponse) { std::string response_body("hello response"); cache_.AddSimpleResponse("www.google.com", "/", 200, response_body); spdy::Http2HeaderBlock request_headers; CreateRequest("www.google.com", "/", &request_headers); const Response* response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_EQ(response_body.size(), response->body().length()); } TEST_F(QuicMemoryCacheBackendTest, AddResponse) { const std::string kRequestHost = "www.foo.com"; const std::string kRequestPath = "/"; const std::string kResponseBody("hello response"); spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; response_headers["content-length"] = absl::StrCat(kResponseBody.size()); spdy::Http2HeaderBlock response_trailers; response_trailers["key-1"] = "value-1"; response_trailers["key-2"] = "value-2"; response_trailers["key-3"] = "value-3"; cache_.AddResponse(kRequestHost, "/", response_headers.Clone(), kResponseBody, response_trailers.Clone()); const Response* response = cache_.GetResponse(kRequestHost, kRequestPath); EXPECT_EQ(response->headers(), response_headers); EXPECT_EQ(response->body(), kResponseBody); EXPECT_EQ(response->trailers(), response_trailers); } #if defined(OS_IOS) #define MAYBE_ReadsCacheDir DISABLED_ReadsCacheDir #else #define MAYBE_ReadsCacheDir ReadsCacheDir #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_ReadsCacheDir) { cache_.InitializeBackend(CacheDirectory()); const Response* response = cache_.GetResponse("test.example.com", "/index.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } #if defined(OS_IOS) #define MAYBE_UsesOriginalUrl DISABLED_UsesOriginalUrl #else #define MAYBE_UsesOriginalUrl UsesOriginalUrl #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrl) { cache_.InitializeBackend(CacheDirectory()); const Response* response = cache_.GetResponse("test.example.com", "/site_map.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } #if defined(OS_IOS) #define MAYBE_UsesOriginalUrlOnly DISABLED_UsesOriginalUrlOnly #else #define MAYBE_UsesOriginalUrlOnly UsesOriginalUrlOnly #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrlOnly) { std::string dir; std::string path = "map.html"; std::vector<std::string> files; ASSERT_TRUE(quiche::EnumerateDirectoryRecursively(CacheDirectory(), files)); for (const std::string& file : files) { if (absl::EndsWithIgnoreCase(file, "map.html")) { dir = file; dir.erase(dir.length() - path.length() - 1); break; } } ASSERT_NE("", dir); cache_.InitializeBackend(dir); const Response* response = cache_.GetResponse("test.example.com", "/site_map.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } TEST_F(QuicMemoryCacheBackendTest, DefaultResponse) { const Response* response = cache_.GetResponse("www.google.com", "/"); ASSERT_FALSE(response); spdy::Http2HeaderBlock response_headers; response_headers[":status"] = "200"; response_headers["content-length"] = "0"; Response* default_response = new Response; default_response->set_headers(std::move(response_headers)); cache_.AddDefaultResponse(default_response); response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); cache_.AddSimpleResponse("www.google.com", "/", 302, ""); response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("302", response->headers().find(":status")->second); response = cache_.GetResponse("www.google.com", "/asd"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); } } }
212
cpp
google/quiche
qbone_stream
quiche/quic/qbone/qbone_stream.cc
quiche/quic/qbone/qbone_stream_test.cc
#ifndef QUICHE_QUIC_QBONE_QBONE_STREAM_H_ #define QUICHE_QUIC_QBONE_QBONE_STREAM_H_ #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QboneSessionBase; class QUIC_EXPORT_PRIVATE QboneWriteOnlyStream : public QuicStream { public: QboneWriteOnlyStream(QuicStreamId id, QuicSession* session); void OnDataAvailable() override {} void WritePacketToQuicStream(absl::string_view packet); }; class QUIC_EXPORT_PRIVATE QboneReadOnlyStream : public QuicStream { public: QboneReadOnlyStream(QuicStreamId id, QboneSessionBase* session); ~QboneReadOnlyStream() override = default; void OnDataAvailable() override; private: std::string buffer_; QboneSessionBase* session_; }; } #endif #include "quiche/quic/qbone/qbone_stream.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/quic/qbone/qbone_session_base.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" DEFINE_QUICHE_COMMAND_LINE_FLAG(int, qbone_stream_ttl_secs, 3, "The QBONE Stream TTL in seconds."); namespace quic { QboneWriteOnlyStream::QboneWriteOnlyStream(QuicStreamId id, QuicSession* session) : QuicStream(id, session, false, WRITE_UNIDIRECTIONAL) { MaybeSetTtl(QuicTime::Delta::FromSeconds( quiche::GetQuicheCommandLineFlag(FLAGS_qbone_stream_ttl_secs))); } void QboneWriteOnlyStream::WritePacketToQuicStream(absl::string_view packet) { WriteOrBufferData(packet, true, nullptr); } QboneReadOnlyStream::QboneReadOnlyStream(QuicStreamId id, QboneSessionBase* session) : QuicStream(id, session, false, READ_UNIDIRECTIONAL), session_(session) { MaybeSetTtl(QuicTime::Delta::FromSeconds( quiche::GetQuicheCommandLineFlag(FLAGS_qbone_stream_ttl_secs))); } void QboneReadOnlyStream::OnDataAvailable() { sequencer()->Read(&buffer_); if (sequencer()->IsClosed()) { session_->ProcessPacketFromPeer(buffer_); OnFinRead(); return; } if (buffer_.size() > QboneConstants::kMaxQbonePacketBytes) { if (!rst_sent()) { Reset(QUIC_BAD_APPLICATION_PAYLOAD); } StopReading(); } } }
#include "quiche/quic/qbone/qbone_stream.h" #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/quic/qbone/qbone_session_base.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace { using ::testing::_; using ::testing::StrictMock; class MockQuicSession : public QboneSessionBase { public: MockQuicSession(QuicConnection* connection, const QuicConfig& config) : QboneSessionBase(connection, nullptr , config, CurrentSupportedVersions(), nullptr ) {} ~MockQuicSession() override {} QuicConsumedData WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) override { if (!writable_) { return QuicConsumedData(0, false); } return QuicConsumedData(write_length, state != StreamSendingState::NO_FIN); } QboneReadOnlyStream* CreateIncomingStream(QuicStreamId id) override { return nullptr; } MOCK_METHOD(void, MaybeSendRstStreamFrame, (QuicStreamId stream_id, QuicResetStreamError error, QuicStreamOffset bytes_written), (override)); MOCK_METHOD(void, MaybeSendStopSendingFrame, (QuicStreamId stream_id, QuicResetStreamError error), (override)); void set_writable(bool writable) { writable_ = writable; } void RegisterReliableStream(QuicStreamId stream_id) { write_blocked_streams()->RegisterStream(stream_id, false, QuicStreamPriority()); } void ActivateReliableStream(std::unique_ptr<QuicStream> stream) { ActivateStream(std::move(stream)); } std::unique_ptr<QuicCryptoStream> CreateCryptoStream() override { return std::make_unique<test::MockQuicCryptoStream>(this); } MOCK_METHOD(void, ProcessPacketFromPeer, (absl::string_view), (override)); MOCK_METHOD(void, ProcessPacketFromNetwork, (absl::string_view), (override)); private: bool writable_ = true; }; class DummyPacketWriter : public QuicPacketWriter { public: DummyPacketWriter() {} WriteResult WritePacket(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, PerPacketOptions* options, const QuicPacketWriterParams& params) override { return WriteResult(WRITE_STATUS_ERROR, 0); } bool IsWriteBlocked() const override { return false; }; void SetWritable() override {} std::optional<int> MessageTooBigErrorCode() const override { return std::nullopt; } QuicByteCount GetMaxPacketSize( const QuicSocketAddress& peer_address) const override { return 0; } bool SupportsReleaseTime() const override { return false; } bool IsBatchMode() const override { return false; } bool SupportsEcn() const override { return false; } QuicPacketBuffer GetNextWriteLocation( const QuicIpAddress& self_address, const QuicSocketAddress& peer_address) override { return {nullptr, nullptr}; } WriteResult Flush() override { return WriteResult(WRITE_STATUS_OK, 0); } }; class QboneReadOnlyStreamTest : public ::testing::Test, public QuicConnectionHelperInterface { public: void CreateReliableQuicStream() { Perspective perspective = Perspective::IS_SERVER; bool owns_writer = true; alarm_factory_ = std::make_unique<test::MockAlarmFactory>(); connection_.reset(new QuicConnection( test::TestConnectionId(0), QuicSocketAddress(TestLoopback(), 0), QuicSocketAddress(TestLoopback(), 0), this , alarm_factory_.get(), new DummyPacketWriter(), owns_writer, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0), connection_id_generator_)); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_.get(), QuicConfig()); session_->Initialize(); stream_ = new QboneReadOnlyStream(kStreamId, session_.get()); session_->ActivateReliableStream( std::unique_ptr<QboneReadOnlyStream>(stream_)); } ~QboneReadOnlyStreamTest() override {} const QuicClock* GetClock() const override { return &clock_; } QuicRandom* GetRandomGenerator() override { return QuicRandom::GetInstance(); } quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override { return &buffer_allocator_; } protected: QboneReadOnlyStream* stream_; std::unique_ptr<StrictMock<MockQuicSession>> session_; std::unique_ptr<QuicAlarmFactory> alarm_factory_; std::unique_ptr<QuicConnection> connection_; quiche::SimpleBufferAllocator buffer_allocator_; MockClock clock_; const QuicStreamId kStreamId = QuicUtils::GetFirstUnidirectionalStreamId( CurrentSupportedVersions()[0].transport_version, Perspective::IS_CLIENT); quic::test::MockConnectionIdGenerator connection_id_generator_; }; TEST_F(QboneReadOnlyStreamTest, ReadDataWhole) { std::string packet = "Stuff"; CreateReliableQuicStream(); QuicStreamFrame frame(kStreamId, true, 0, packet); EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); stream_->OnStreamFrame(frame); } TEST_F(QboneReadOnlyStreamTest, ReadBuffered) { CreateReliableQuicStream(); std::string packet = "Stuf"; { QuicStreamFrame frame(kStreamId, false, 0, packet); stream_->OnStreamFrame(frame); } packet = "f"; EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); { QuicStreamFrame frame(kStreamId, true, 4, packet); stream_->OnStreamFrame(frame); } } TEST_F(QboneReadOnlyStreamTest, ReadOutOfOrder) { CreateReliableQuicStream(); std::string packet = "f"; { QuicStreamFrame frame(kStreamId, true, 4, packet); stream_->OnStreamFrame(frame); } packet = "S"; { QuicStreamFrame frame(kStreamId, false, 0, packet); stream_->OnStreamFrame(frame); } packet = "tuf"; EXPECT_CALL(*session_, ProcessPacketFromPeer("Stuff")); { QuicStreamFrame frame(kStreamId, false, 1, packet); stream_->OnStreamFrame(frame); } } TEST_F(QboneReadOnlyStreamTest, ReadBufferedTooLarge) { CreateReliableQuicStream(); std::string packet = "0123456789"; int iterations = (QboneConstants::kMaxQbonePacketBytes / packet.size()) + 2; EXPECT_CALL(*session_, MaybeSendStopSendingFrame( kStreamId, QuicResetStreamError::FromInternal( QUIC_BAD_APPLICATION_PAYLOAD))); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( kStreamId, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); for (int i = 0; i < iterations; ++i) { QuicStreamFrame frame(kStreamId, i == (iterations - 1), i * packet.size(), packet); if (!stream_->reading_stopped()) { stream_->OnStreamFrame(frame); } } EXPECT_TRUE(stream_->reading_stopped()); } } }
213
cpp
google/quiche
qbone_client
quiche/quic/qbone/qbone_client.cc
quiche/quic/qbone/qbone_client_test.cc
#ifndef QUICHE_QUIC_QBONE_QBONE_CLIENT_H_ #define QUICHE_QUIC_QBONE_QBONE_CLIENT_H_ #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/qbone/qbone_client_interface.h" #include "quiche/quic/qbone/qbone_client_session.h" #include "quiche/quic/qbone/qbone_packet_writer.h" #include "quiche/quic/tools/quic_client_base.h" namespace quic { class QboneClient : public QuicClientBase, public QboneClientInterface { public: QboneClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicSession::Visitor* session_owner, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, QbonePacketWriter* qbone_writer, QboneClientControlStream::Handler* qbone_handler); ~QboneClient() override; QboneClientSession* qbone_session(); void ProcessPacketFromNetwork(absl::string_view packet) override; bool EarlyDataAccepted() override; bool ReceivedInchoateReject() override; void set_max_pacing_rate(QuicBandwidth max_pacing_rate) { max_pacing_rate_ = max_pacing_rate; } QuicBandwidth max_pacing_rate() const { return max_pacing_rate_; } bool use_quarantine_mode() const; void set_use_quarantine_mode(bool use_quarantine_mode); protected: int GetNumSentClientHellosFromSession() override; int GetNumReceivedServerConfigUpdatesFromSession() override; void ResendSavedData() override; void ClearDataToResend() override; std::unique_ptr<QuicSession> CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) override; QbonePacketWriter* qbone_writer() { return qbone_writer_; } QboneClientControlStream::Handler* qbone_control_handler() { return qbone_handler_; } QuicSession::Visitor* session_owner() { return session_owner_; } bool HasActiveRequests() override; private: QbonePacketWriter* qbone_writer_; QboneClientControlStream::Handler* qbone_handler_; QuicSession::Visitor* session_owner_; QuicBandwidth max_pacing_rate_; bool use_quarantine_mode_ = false; }; } #endif #include "quiche/quic/qbone/qbone_client.h" #include <memory> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/platform/api/quic_testvalue.h" #include "quiche/quic/tools/quic_client_default_network_helper.h" namespace quic { namespace { std::unique_ptr<QuicClientBase::NetworkHelper> CreateNetworkHelper( QuicEventLoop* event_loop, QboneClient* client) { std::unique_ptr<QuicClientBase::NetworkHelper> helper = std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, client); quic::AdjustTestValue("QboneClient/network_helper", &helper); return helper; } } QboneClient::QboneClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicSession::Visitor* session_owner, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, QbonePacketWriter* qbone_writer, QboneClientControlStream::Handler* qbone_handler) : QuicClientBase(server_id, supported_versions, config, new QuicDefaultConnectionHelper(), event_loop->CreateAlarmFactory().release(), CreateNetworkHelper(event_loop, this), std::move(proof_verifier), nullptr), qbone_writer_(qbone_writer), qbone_handler_(qbone_handler), session_owner_(session_owner), max_pacing_rate_(QuicBandwidth::Zero()) { set_server_address(server_address); crypto_config()->set_alpn("qbone"); } QboneClient::~QboneClient() { ResetSession(); } QboneClientSession* QboneClient::qbone_session() { return static_cast<QboneClientSession*>(QuicClientBase::session()); } void QboneClient::ProcessPacketFromNetwork(absl::string_view packet) { qbone_session()->ProcessPacketFromNetwork(packet); } bool QboneClient::EarlyDataAccepted() { return qbone_session()->EarlyDataAccepted(); } bool QboneClient::ReceivedInchoateReject() { return qbone_session()->ReceivedInchoateReject(); } int QboneClient::GetNumSentClientHellosFromSession() { return qbone_session()->GetNumSentClientHellos(); } int QboneClient::GetNumReceivedServerConfigUpdatesFromSession() { return qbone_session()->GetNumReceivedServerConfigUpdates(); } void QboneClient::ResendSavedData() { } void QboneClient::ClearDataToResend() { } bool QboneClient::HasActiveRequests() { return qbone_session()->HasActiveRequests(); } class QboneClientSessionWithConnection : public QboneClientSession { public: using QboneClientSession::QboneClientSession; ~QboneClientSessionWithConnection() override { DeleteConnection(); } }; std::unique_ptr<QuicSession> QboneClient::CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) { if (max_pacing_rate() > quic::QuicBandwidth::Zero()) { QUIC_LOG(INFO) << "Setting max pacing rate to " << max_pacing_rate(); connection->SetMaxPacingRate(max_pacing_rate()); } return std::make_unique<QboneClientSessionWithConnection>( connection, crypto_config(), session_owner(), *config(), supported_versions, server_id(), qbone_writer_, qbone_handler_); } bool QboneClient::use_quarantine_mode() const { return use_quarantine_mode_; } void QboneClient::set_use_quarantine_mode(bool use_quarantine_mode) { use_quarantine_mode_ = use_quarantine_mode; } }
#include "quiche/quic/qbone/qbone_client.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_dispatcher.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/qbone/qbone_packet_processor_test_tools.h" #include "quiche/quic/qbone/qbone_server_session.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_dispatcher_peer.h" #include "quiche/quic/test_tools/quic_server_peer.h" #include "quiche/quic/test_tools/server_thread.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_server.h" namespace quic { namespace test { namespace { using ::testing::ElementsAre; ParsedQuicVersionVector GetTestParams() { ParsedQuicVersionVector test_versions; SetQuicReloadableFlag(quic_disable_version_q046, false); return CurrentSupportedVersionsWithQuicCrypto(); } std::string TestPacketIn(const std::string& body) { return PrependIPv6HeaderForTest(body, 5); } std::string TestPacketOut(const std::string& body) { return PrependIPv6HeaderForTest(body, 4); } class DataSavingQbonePacketWriter : public QbonePacketWriter { public: void WritePacketToNetwork(const char* packet, size_t size) override { QuicWriterMutexLock lock(&mu_); data_.push_back(std::string(packet, size)); } std::vector<std::string> data() { QuicWriterMutexLock lock(&mu_); return data_; } private: QuicMutex mu_; std::vector<std::string> data_; }; class ConnectionOwningQboneServerSession : public QboneServerSession { public: ConnectionOwningQboneServerSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, Visitor* owner, const QuicConfig& config, const QuicCryptoServerConfig* quic_crypto_server_config, QuicCompressedCertsCache* compressed_certs_cache, QbonePacketWriter* writer) : QboneServerSession(supported_versions, connection, owner, config, quic_crypto_server_config, compressed_certs_cache, writer, TestLoopback6(), TestLoopback6(), 64, nullptr), connection_(connection) {} private: std::unique_ptr<QuicConnection> connection_; }; class QuicQboneDispatcher : public QuicDispatcher { public: QuicQboneDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, QbonePacketWriter* writer, ConnectionIdGeneratorInterface& generator) : QuicDispatcher(config, crypto_config, version_manager, std::move(helper), std::move(session_helper), std::move(alarm_factory), kQuicDefaultConnectionIdLength, generator), writer_(writer) {} std::unique_ptr<QuicSession> CreateQuicSession( QuicConnectionId id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, absl::string_view alpn, const ParsedQuicVersion& version, const ParsedClientHello& , ConnectionIdGeneratorInterface& connection_id_generator) override { QUICHE_CHECK_EQ(alpn, "qbone"); QuicConnection* connection = new QuicConnection( id, self_address, peer_address, helper(), alarm_factory(), writer(), false, Perspective::IS_SERVER, ParsedQuicVersionVector{version}, connection_id_generator); auto session = std::make_unique<ConnectionOwningQboneServerSession>( GetSupportedVersions(), connection, this, config(), crypto_config(), compressed_certs_cache(), writer_); session->Initialize(); return session; } private: QbonePacketWriter* writer_; }; class QboneTestServer : public QuicServer { public: explicit QboneTestServer(std::unique_ptr<ProofSource> proof_source, quic::QuicMemoryCacheBackend* response_cache) : QuicServer(std::move(proof_source), response_cache) {} QuicDispatcher* CreateQuicDispatcher() override { return new QuicQboneDispatcher( &config(), &crypto_config(), version_manager(), std::make_unique<QuicDefaultConnectionHelper>(), std::make_unique<QboneCryptoServerStreamHelper>(), event_loop()->CreateAlarmFactory(), &writer_, connection_id_generator()); } std::vector<std::string> data() { return writer_.data(); } private: DataSavingQbonePacketWriter writer_; }; class QboneTestClient : public QboneClient { public: QboneTestClient(QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier) : QboneClient(server_address, server_id, supported_versions, nullptr, QuicConfig(), event_loop, std::move(proof_verifier), &qbone_writer_, nullptr) {} ~QboneTestClient() override {} void SendData(const std::string& data) { qbone_session()->ProcessPacketFromNetwork(data); } void WaitForWriteToFlush() { while (connected() && session()->HasDataToWrite()) { WaitForEvents(); } } bool WaitForDataSize(int n, QuicTime::Delta timeout) { const QuicClock* clock = quic::test::QuicConnectionPeer::GetHelper(session()->connection()) ->GetClock(); const QuicTime deadline = clock->Now() + timeout; while (data().size() < n) { if (clock->Now() > deadline) { return false; } WaitForEvents(); } return true; } std::vector<std::string> data() { return qbone_writer_.data(); } private: DataSavingQbonePacketWriter qbone_writer_; }; class QboneClientTest : public QuicTestWithParam<ParsedQuicVersion> {}; INSTANTIATE_TEST_SUITE_P(Tests, QboneClientTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QboneClientTest, SendDataFromClient) { quic::QuicMemoryCacheBackend server_backend; auto server = std::make_unique<QboneTestServer>( crypto_test_utils::ProofSourceForTesting(), &server_backend); QboneTestServer* server_ptr = server.get(); QuicSocketAddress server_address(TestLoopback(), 0); ServerThread server_thread(std::move(server), server_address); server_thread.Initialize(); server_address = QuicSocketAddress(server_address.host(), server_thread.GetPort()); server_thread.Start(); std::unique_ptr<QuicEventLoop> event_loop = GetDefaultEventLoop()->Create(quic::QuicDefaultClock::Get()); QboneTestClient client( server_address, QuicServerId("test.example.com", server_address.port(), false), ParsedQuicVersionVector{GetParam()}, event_loop.get(), crypto_test_utils::ProofVerifierForTesting()); ASSERT_TRUE(client.Initialize()); ASSERT_TRUE(client.Connect()); ASSERT_TRUE(client.WaitForOneRttKeysAvailable()); client.SendData(TestPacketIn("hello")); client.SendData(TestPacketIn("world")); client.WaitForWriteToFlush(); ASSERT_TRUE( server_thread.WaitUntil([&] { return server_ptr->data().size() >= 2; }, QuicTime::Delta::FromSeconds(5))); std::string long_data(1000, 'A'); server_thread.Schedule([server_ptr, &long_data]() { EXPECT_THAT(server_ptr->data(), ElementsAre(TestPacketOut("hello"), TestPacketOut("world"))); auto server_session = static_cast<QboneServerSession*>( QuicDispatcherPeer::GetFirstSessionIfAny( QuicServerPeer::GetDispatcher(server_ptr))); server_session->ProcessPacketFromNetwork( TestPacketIn("Somethingsomething")); server_session->ProcessPacketFromNetwork(TestPacketIn(long_data)); server_session->ProcessPacketFromNetwork(TestPacketIn(long_data)); }); EXPECT_TRUE(client.WaitForDataSize(3, QuicTime::Delta::FromSeconds(5))); EXPECT_THAT(client.data(), ElementsAre(TestPacketOut("Somethingsomething"), TestPacketOut(long_data), TestPacketOut(long_data))); client.Disconnect(); server_thread.Quit(); server_thread.Join(); } } } }
214
cpp
google/quiche
qbone_packet_processor
quiche/quic/qbone/qbone_packet_processor.cc
quiche/quic/qbone/qbone_packet_processor_test.cc
#ifndef QUICHE_QUIC_QBONE_QBONE_PACKET_PROCESSOR_H_ #define QUICHE_QUIC_QBONE_QBONE_PACKET_PROCESSOR_H_ #include <netinet/icmp6.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_ip_address.h" namespace quic { enum : size_t { kIPv6HeaderSize = 40, kICMPv6HeaderSize = sizeof(icmp6_hdr), kTotalICMPv6HeaderSize = kIPv6HeaderSize + kICMPv6HeaderSize, }; class QbonePacketProcessor { public: enum class Direction { FROM_OFF_NETWORK = 0, FROM_NETWORK = 1 }; enum class ProcessingResult { OK = 0, SILENT_DROP = 1, ICMP = 2, ICMP_AND_TCP_RESET = 4, TCP_RESET = 5, }; class OutputInterface { public: virtual ~OutputInterface(); virtual void SendPacketToClient(absl::string_view packet) = 0; virtual void SendPacketToNetwork(absl::string_view packet) = 0; }; class StatsInterface { public: virtual ~StatsInterface(); virtual void OnPacketForwarded(Direction direction, uint8_t traffic_class) = 0; virtual void OnPacketDroppedSilently(Direction direction, uint8_t traffic_class) = 0; virtual void OnPacketDroppedWithIcmp(Direction direction, uint8_t traffic_class) = 0; virtual void OnPacketDroppedWithTcpReset(Direction direction, uint8_t traffic_class) = 0; virtual void RecordThroughput(size_t bytes, Direction direction, uint8_t traffic_class) = 0; }; class Filter { public: virtual ~Filter(); virtual ProcessingResult FilterPacket(Direction direction, absl::string_view full_packet, absl::string_view payload, icmp6_hdr* icmp_header); protected: uint8_t TransportProtocolFromHeader(absl::string_view ipv6_header) { return ipv6_header[6]; } QuicIpAddress SourceIpFromHeader(absl::string_view ipv6_header) { QuicIpAddress address; address.FromPackedString(&ipv6_header[8], QuicIpAddress::kIPv6AddressSize); return address; } QuicIpAddress DestinationIpFromHeader(absl::string_view ipv6_header) { QuicIpAddress address; address.FromPackedString(&ipv6_header[24], QuicIpAddress::kIPv6AddressSize); return address; } }; QbonePacketProcessor(QuicIpAddress self_ip, QuicIpAddress client_ip, size_t client_ip_subnet_length, OutputInterface* output, StatsInterface* stats); QbonePacketProcessor(const QbonePacketProcessor&) = delete; QbonePacketProcessor& operator=(const QbonePacketProcessor&) = delete; void ProcessPacket(std::string* packet, Direction direction); void set_filter(std::unique_ptr<Filter> filter) { filter_ = std::move(filter); } void set_client_ip(QuicIpAddress client_ip) { client_ip_ = client_ip; } void set_client_ip_subnet_length(size_t client_ip_subnet_length) { client_ip_subnet_length_ = client_ip_subnet_length; } static const QuicIpAddress kInvalidIpAddress; static uint8_t TrafficClassFromHeader(absl::string_view ipv6_header); protected: ProcessingResult ProcessIPv6HeaderAndFilter(std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header); void SendIcmpResponse(in6_addr dst, icmp6_hdr* icmp_header, absl::string_view payload, Direction original_direction); void SendTcpReset(absl::string_view original_packet, Direction original_direction); bool IsValid() const { return client_ip_ != kInvalidIpAddress; } in6_addr self_ip_; QuicIpAddress client_ip_; size_t client_ip_subnet_length_; OutputInterface* output_; StatsInterface* stats_; std::unique_ptr<Filter> filter_; private: ProcessingResult ProcessIPv6Header(std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header); void SendResponse(Direction original_direction, absl::string_view packet); in6_addr GetDestinationFromPacket(absl::string_view packet); }; } #endif #include "quiche/quic/qbone/qbone_packet_processor.h" #include <netinet/icmp6.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <cstdint> #include <cstring> #include <string> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/quic/qbone/platform/tcp_packet.h" #include "quiche/common/quiche_endian.h" namespace { constexpr size_t kIPv6AddressSize = 16; constexpr size_t kIPv6MinPacketSize = 1280; constexpr size_t kIcmpTtl = 64; constexpr size_t kICMPv6DestinationUnreachableDueToSourcePolicy = 5; constexpr size_t kIPv6DestinationOffset = 8; } namespace quic { const QuicIpAddress QbonePacketProcessor::kInvalidIpAddress = QuicIpAddress::Any6(); QbonePacketProcessor::QbonePacketProcessor(QuicIpAddress self_ip, QuicIpAddress client_ip, size_t client_ip_subnet_length, OutputInterface* output, StatsInterface* stats) : client_ip_(client_ip), output_(output), stats_(stats), filter_(new Filter) { memcpy(self_ip_.s6_addr, self_ip.ToPackedString().data(), kIPv6AddressSize); QUICHE_DCHECK_LE(client_ip_subnet_length, kIPv6AddressSize * 8); client_ip_subnet_length_ = client_ip_subnet_length; QUICHE_DCHECK(IpAddressFamily::IP_V6 == self_ip.address_family()); QUICHE_DCHECK(IpAddressFamily::IP_V6 == client_ip.address_family()); QUICHE_DCHECK(self_ip != kInvalidIpAddress); } QbonePacketProcessor::OutputInterface::~OutputInterface() {} QbonePacketProcessor::StatsInterface::~StatsInterface() {} QbonePacketProcessor::Filter::~Filter() {} QbonePacketProcessor::ProcessingResult QbonePacketProcessor::Filter::FilterPacket(Direction direction, absl::string_view full_packet, absl::string_view payload, icmp6_hdr* icmp_header) { return ProcessingResult::OK; } void QbonePacketProcessor::ProcessPacket(std::string* packet, Direction direction) { uint8_t traffic_class = TrafficClassFromHeader(*packet); if (ABSL_PREDICT_FALSE(!IsValid())) { QUIC_BUG(quic_bug_11024_1) << "QuicPacketProcessor is invoked in an invalid state."; stats_->OnPacketDroppedSilently(direction, traffic_class); return; } stats_->RecordThroughput(packet->size(), direction, traffic_class); uint8_t transport_protocol; char* transport_data; icmp6_hdr icmp_header; memset(&icmp_header, 0, sizeof(icmp_header)); ProcessingResult result = ProcessIPv6HeaderAndFilter( packet, direction, &transport_protocol, &transport_data, &icmp_header); in6_addr dst; memcpy(&dst, &packet->data()[kIPv6DestinationOffset], kIPv6AddressSize); switch (result) { case ProcessingResult::OK: switch (direction) { case Direction::FROM_OFF_NETWORK: output_->SendPacketToNetwork(*packet); break; case Direction::FROM_NETWORK: output_->SendPacketToClient(*packet); break; } stats_->OnPacketForwarded(direction, traffic_class); break; case ProcessingResult::SILENT_DROP: stats_->OnPacketDroppedSilently(direction, traffic_class); break; case ProcessingResult::ICMP: if (icmp_header.icmp6_type == ICMP6_ECHO_REPLY) { auto icmp_body = absl::string_view(*packet).substr(sizeof(ip6_hdr) + sizeof(icmp6_hdr)); SendIcmpResponse(dst, &icmp_header, icmp_body, direction); } else { SendIcmpResponse(dst, &icmp_header, *packet, direction); } stats_->OnPacketDroppedWithIcmp(direction, traffic_class); break; case ProcessingResult::ICMP_AND_TCP_RESET: SendIcmpResponse(dst, &icmp_header, *packet, direction); stats_->OnPacketDroppedWithIcmp(direction, traffic_class); SendTcpReset(*packet, direction); stats_->OnPacketDroppedWithTcpReset(direction, traffic_class); break; case ProcessingResult::TCP_RESET: SendTcpReset(*packet, direction); stats_->OnPacketDroppedWithTcpReset(direction, traffic_class); break; } } QbonePacketProcessor::ProcessingResult QbonePacketProcessor::ProcessIPv6HeaderAndFilter(std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header) { ProcessingResult result = ProcessIPv6Header( packet, direction, transport_protocol, transport_data, icmp_header); if (result == ProcessingResult::OK) { char* packet_data = &*packet->begin(); size_t header_size = *transport_data - packet_data; if (packet_data >= *transport_data || header_size > packet->size() || header_size < kIPv6HeaderSize) { QUIC_BUG(quic_bug_11024_2) << "Invalid pointers encountered in " "QbonePacketProcessor::ProcessPacket. Dropping the packet"; return ProcessingResult::SILENT_DROP; } result = filter_->FilterPacket( direction, *packet, absl::string_view(*transport_data, packet->size() - header_size), icmp_header); } if (result == ProcessingResult::ICMP) { const uint8_t* header = reinterpret_cast<const uint8_t*>(packet->data()); constexpr size_t kIPv6NextHeaderOffset = 6; constexpr size_t kIcmpMessageTypeOffset = kIPv6HeaderSize + 0; constexpr size_t kIcmpMessageTypeMaxError = 127; if ( packet->size() >= (kIPv6HeaderSize + kICMPv6HeaderSize) && header[kIPv6NextHeaderOffset] == IPPROTO_ICMPV6 && header[kIcmpMessageTypeOffset] < kIcmpMessageTypeMaxError) { result = ProcessingResult::SILENT_DROP; } } return result; } QbonePacketProcessor::ProcessingResult QbonePacketProcessor::ProcessIPv6Header( std::string* packet, Direction direction, uint8_t* transport_protocol, char** transport_data, icmp6_hdr* icmp_header) { if (packet->size() < kIPv6HeaderSize) { QUIC_DVLOG(1) << "Dropped malformed packet: IPv6 header too short"; return ProcessingResult::SILENT_DROP; } ip6_hdr* header = reinterpret_cast<ip6_hdr*>(&*packet->begin()); if (header->ip6_vfc >> 4 != 6) { QUIC_DVLOG(1) << "Dropped malformed packet: IP version is not IPv6"; return ProcessingResult::SILENT_DROP; } const size_t declared_payload_size = quiche::QuicheEndian::NetToHost16(header->ip6_plen); const size_t actual_payload_size = packet->size() - kIPv6HeaderSize; if (declared_payload_size != actual_payload_size) { QUIC_DVLOG(1) << "Dropped malformed packet: incorrect packet length specified"; return ProcessingResult::SILENT_DROP; } QuicIpAddress address_to_check; uint8_t address_reject_code; bool ip_parse_result; switch (direction) { case Direction::FROM_OFF_NETWORK: ip_parse_result = address_to_check.FromPackedString( reinterpret_cast<const char*>(&header->ip6_src), sizeof(header->ip6_src)); address_reject_code = kICMPv6DestinationUnreachableDueToSourcePolicy; break; case Direction::FROM_NETWORK: ip_parse_result = address_to_check.FromPackedString( reinterpret_cast<const char*>(&header->ip6_dst), sizeof(header->ip6_src)); address_reject_code = ICMP6_DST_UNREACH_NOROUTE; break; } QUICHE_DCHECK(ip_parse_result); if (!client_ip_.InSameSubnet(address_to_check, client_ip_subnet_length_)) { QUIC_DVLOG(1) << "Dropped packet: source/destination address is not client's"; icmp_header->icmp6_type = ICMP6_DST_UNREACH; icmp_header->icmp6_code = address_reject_code; return ProcessingResult::ICMP; } if (header->ip6_hops <= 1) { icmp_header->icmp6_type = ICMP6_TIME_EXCEEDED; icmp_header->icmp6_code = ICMP6_TIME_EXCEED_TRANSIT; return ProcessingResult::ICMP; } header->ip6_hops--; switch (header->ip6_nxt) { case IPPROTO_TCP: case IPPROTO_UDP: case IPPROTO_ICMPV6: *transport_protocol = header->ip6_nxt; *transport_data = (&*packet->begin()) + kIPv6HeaderSize; break; default: icmp_header->icmp6_type = ICMP6_PARAM_PROB; icmp_header->icmp6_code = ICMP6_PARAMPROB_NEXTHEADER; return ProcessingResult::ICMP; } return ProcessingResult::OK; } void QbonePacketProcessor::SendIcmpResponse(in6_addr dst, icmp6_hdr* icmp_header, absl::string_view payload, Direction original_direction) { CreateIcmpPacket(self_ip_, dst, *icmp_header, payload, [this, original_direction](absl::string_view packet) { SendResponse(original_direction, packet); }); } void QbonePacketProcessor::SendTcpReset(absl::string_view original_packet, Direction original_direction) { CreateTcpResetPacket(original_packet, [this, original_direction](absl::string_view packet) { SendResponse(original_direction, packet); }); } void QbonePacketProcessor::SendResponse(Direction original_direction, absl::string_view packet) { switch (original_direction) { case Direction::FROM_OFF_NETWORK: output_->SendPacketToClient(packet); break; case Direction::FROM_NETWORK: output_->SendPacketToNetwork(packet); break; } } uint8_t QbonePacketProcessor::TrafficClassFromHeader( absl::string_view ipv6_header) { if (ipv6_header.length() < 2) { return 0; } return ipv6_header[0] << 4 | ipv6_header[1] >> 4; } }
#include "quiche/quic/qbone/qbone_packet_processor.h" #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/qbone_packet_processor_test_tools.h" #include "quiche/common/quiche_text_utils.h" namespace quic::test { namespace { using Direction = QbonePacketProcessor::Direction; using ProcessingResult = QbonePacketProcessor::ProcessingResult; using OutputInterface = QbonePacketProcessor::OutputInterface; using ::testing::_; using ::testing::Eq; using ::testing::Invoke; using ::testing::Return; using ::testing::WithArgs; static const char kReferenceClientPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF4[] = { 0x68, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF3[] = { 0x66, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF2[] = { 0x64, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientPacketDataAF1[] = { 0x62, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceNetworkPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0xbb, 0x30, 0x39, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceClientSubnetPacketData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x08, 17, 50, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x30, 0x39, 0x01, 0xbb, 0x00, 0x00, 0x00, 0x00, }; static const char kReferenceEchoRequestData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 64, 58, 127, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x62, 0x6f, 0x6e, 0x6f, 128, 0, 0x00, 0x00, 0xca, 0xfe, 0x00, 0x01, 0x67, 0x37, 0x8a, 0x63, 0x00, 0x00, 0x00, 0x00, 0x96, 0x58, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, }; static const char kReferenceEchoReplyData[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 64, 58, 255, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 129, 0, 0x66, 0xb6, 0xca, 0xfe, 0x00, 0x01, 0x67, 0x37, 0x8a, 0x63, 0x00, 0x00, 0x00, 0x00, 0x96, 0x58, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, }; static const absl::string_view kReferenceClientPacket( kReferenceClientPacketData, ABSL_ARRAYSIZE(kReferenceClientPacketData)); static const absl::string_view kReferenceClientPacketAF4( kReferenceClientPacketDataAF4, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF4)); static const absl::string_view kReferenceClientPacketAF3( kReferenceClientPacketDataAF3, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF3)); static const absl::string_view kReferenceClientPacketAF2( kReferenceClientPacketDataAF2, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF2)); static const absl::string_view kReferenceClientPacketAF1( kReferenceClientPacketDataAF1, ABSL_ARRAYSIZE(kReferenceClientPacketDataAF1)); static const absl::string_view kReferenceNetworkPacket( kReferenceNetworkPacketData, ABSL_ARRAYSIZE(kReferenceNetworkPacketData)); static const absl::string_view kReferenceClientSubnetPacket( kReferenceClientSubnetPacketData, ABSL_ARRAYSIZE(kReferenceClientSubnetPacketData)); static const absl::string_view kReferenceEchoRequest( kReferenceEchoRequestData, ABSL_ARRAYSIZE(kReferenceEchoRequestData)); MATCHER_P(IsIcmpMessage, icmp_type, "Checks whether the argument is an ICMP message of supplied type") { if (arg.size() < kTotalICMPv6HeaderSize) { return false; } return arg[40] == icmp_type; } class MockPacketFilter : public QbonePacketProcessor::Filter { public: MOCK_METHOD(ProcessingResult, FilterPacket, (Direction, absl::string_view, absl::string_view, icmp6_hdr*), (override)); }; class QbonePacketProcessorTest : public QuicTest { protected: QbonePacketProcessorTest() { QUICHE_CHECK(client_ip_.FromString("fd00:0:0:1::1")); QUICHE_CHECK(self_ip_.FromString("fd00:0:0:4::1")); QUICHE_CHECK(network_ip_.FromString("fd00:0:0:5::1")); processor_ = std::make_unique<QbonePacketProcessor>( self_ip_, client_ip_, 62, &output_, &stats_); EXPECT_CALL(stats_, RecordThroughput(_, _, _)).WillRepeatedly(Return()); } void SendPacketFromClient(absl::string_view packet) { std::string packet_buffer(packet.data(), packet.size()); processor_->ProcessPacket(&packet_buffer, Direction::FROM_OFF_NETWORK); } void SendPacketFromNetwork(absl::string_view packet) { std::string packet_buffer(packet.data(), packet.size()); processor_->ProcessPacket(&packet_buffer, Direction::FROM_NETWORK); } QuicIpAddress client_ip_; QuicIpAddress self_ip_; QuicIpAddress network_ip_; std::unique_ptr<QbonePacketProcessor> processor_; testing::StrictMock<MockPacketProcessorOutput> output_; testing::StrictMock<MockPacketProcessorStats> stats_; }; TEST_F(QbonePacketProcessorTest, EmptyPacket) { EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(stats_, RecordThroughput(0, Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(""); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_NETWORK, _)); EXPECT_CALL(stats_, RecordThroughput(0, Direction::FROM_NETWORK, _)); SendPacketFromNetwork(""); } TEST_F(QbonePacketProcessorTest, RandomGarbage) { EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(std::string(1280, 'a')); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_NETWORK, _)); SendPacketFromNetwork(std::string(1280, 'a')); } TEST_F(QbonePacketProcessorTest, RandomGarbageWithCorrectLengthFields) { std::string packet(40, 'a'); packet[4] = 0; packet[5] = 0; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(IsIcmpMessage(ICMP6_DST_UNREACH))); SendPacketFromClient(packet); } TEST_F(QbonePacketProcessorTest, GoodPacketFromClient) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(_)); SendPacketFromClient(kReferenceClientPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromClientSubnet) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(_)); SendPacketFromClient(kReferenceClientSubnetPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromNetwork) { EXPECT_CALL(stats_, OnPacketForwarded(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(_)); SendPacketFromNetwork(kReferenceNetworkPacket); } TEST_F(QbonePacketProcessorTest, GoodPacketFromNetworkWrongDirection) { EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(IsIcmpMessage(ICMP6_DST_UNREACH))); SendPacketFromClient(kReferenceNetworkPacket); } TEST_F(QbonePacketProcessorTest, TtlExpired) { std::string packet(kReferenceNetworkPacket); packet[7] = 1; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(IsIcmpMessage(ICMP6_TIME_EXCEEDED))); SendPacketFromNetwork(packet); } TEST_F(QbonePacketProcessorTest, UnknownProtocol) { std::string packet(kReferenceNetworkPacket); packet[6] = IPPROTO_SCTP; EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_NETWORK, _)); EXPECT_CALL(output_, SendPacketToNetwork(IsIcmpMessage(ICMP6_PARAM_PROB))); SendPacketFromNetwork(packet); } TEST_F(QbonePacketProcessorTest, FilterFromClient) { auto filter = std::make_unique<MockPacketFilter>(); EXPECT_CALL(*filter, FilterPacket(_, _, _, _)) .WillRepeatedly(Return(ProcessingResult::SILENT_DROP)); processor_->set_filter(std::move(filter)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(kReferenceClientPacket); } class TestFilter : public QbonePacketProcessor::Filter { public: TestFilter(QuicIpAddress client_ip, QuicIpAddress network_ip) : client_ip_(client_ip), network_ip_(network_ip) {} ProcessingResult FilterPacket(Direction direction, absl::string_view full_packet, absl::string_view payload, icmp6_hdr* icmp_header) override { EXPECT_EQ(kIPv6HeaderSize, full_packet.size() - payload.size()); EXPECT_EQ(IPPROTO_UDP, TransportProtocolFromHeader(full_packet)); EXPECT_EQ(client_ip_, SourceIpFromHeader(full_packet)); EXPECT_EQ(network_ip_, DestinationIpFromHeader(full_packet)); last_tos_ = QbonePacketProcessor::TrafficClassFromHeader(full_packet); called_++; return ProcessingResult::SILENT_DROP; } int called() const { return called_; } uint8_t last_tos() const { return last_tos_; } private: int called_ = 0; uint8_t last_tos_ = 0; QuicIpAddress client_ip_; QuicIpAddress network_ip_; }; TEST_F(QbonePacketProcessorTest, FilterHelperFunctions) { auto filter_owned = std::make_unique<TestFilter>(client_ip_, network_ip_); TestFilter* filter = filter_owned.get(); processor_->set_filter(std::move(filter_owned)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)); SendPacketFromClient(kReferenceClientPacket); ASSERT_EQ(1, filter->called()); } TEST_F(QbonePacketProcessorTest, FilterHelperFunctionsTOS) { auto filter_owned = std::make_unique<TestFilter>(client_ip_, network_ip_); processor_->set_filter(std::move(filter_owned)); EXPECT_CALL(stats_, OnPacketDroppedSilently(Direction::FROM_OFF_NETWORK, _)) .Times(testing::AnyNumber()); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacket.size(), Direction::FROM_OFF_NETWORK, 0)); SendPacketFromClient(kReferenceClientPacket); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF4.size(), Direction::FROM_OFF_NETWORK, 0x80)); SendPacketFromClient(kReferenceClientPacketAF4); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF3.size(), Direction::FROM_OFF_NETWORK, 0x60)); SendPacketFromClient(kReferenceClientPacketAF3); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF2.size(), Direction::FROM_OFF_NETWORK, 0x40)); SendPacketFromClient(kReferenceClientPacketAF2); EXPECT_CALL(stats_, RecordThroughput(kReferenceClientPacketAF1.size(), Direction::FROM_OFF_NETWORK, 0x20)); SendPacketFromClient(kReferenceClientPacketAF1); } TEST_F(QbonePacketProcessorTest, Icmp6EchoResponseHasRightPayload) { auto filter = std::make_unique<MockPacketFilter>(); EXPECT_CALL(*filter, FilterPacket(_, _, _, _)) .WillOnce(WithArgs<2, 3>( Invoke([](absl::string_view payload, icmp6_hdr* icmp_header) { icmp_header->icmp6_type = ICMP6_ECHO_REPLY; icmp_header->icmp6_code = 0; auto* request_header = reinterpret_cast<const icmp6_hdr*>(payload.data()); icmp_header->icmp6_id = request_header->icmp6_id; icmp_header->icmp6_seq = request_header->icmp6_seq; return ProcessingResult::ICMP; }))); processor_->set_filter(std::move(filter)); EXPECT_CALL(stats_, OnPacketDroppedWithIcmp(Direction::FROM_OFF_NETWORK, _)); EXPECT_CALL(output_, SendPacketToClient(_)) .WillOnce(Invoke([](absl::string_view packet) { absl::string_view expected = absl::string_view( kReferenceEchoReplyData, sizeof(kReferenceEchoReplyData)); EXPECT_THAT(packet, Eq(expected)); QUIC_LOG(INFO) << "ICMP response:\n" << quiche::QuicheTextUtils::HexDump(packet); })); SendPacketFromClient(kReferenceEchoRequest); } } }
215
cpp
google/quiche
qbone_packet_exchanger
quiche/quic/qbone/qbone_packet_exchanger.cc
quiche/quic/qbone/qbone_packet_exchanger_test.cc
#ifndef QUICHE_QUIC_QBONE_QBONE_PACKET_EXCHANGER_H_ #define QUICHE_QUIC_QBONE_QBONE_PACKET_EXCHANGER_H_ #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/qbone/qbone_client_interface.h" #include "quiche/quic/qbone/qbone_packet_writer.h" namespace quic { class QbonePacketExchanger : public QbonePacketWriter { public: class Visitor { public: virtual ~Visitor() {} virtual void OnReadError(const std::string& error) {} virtual void OnWriteError(const std::string& error) {} }; QbonePacketExchanger(Visitor* visitor, size_t max_pending_packets) : visitor_(visitor), max_pending_packets_(max_pending_packets) {} QbonePacketExchanger(const QbonePacketExchanger&) = delete; QbonePacketExchanger& operator=(const QbonePacketExchanger&) = delete; QbonePacketExchanger(QbonePacketExchanger&&) = delete; QbonePacketExchanger& operator=(QbonePacketExchanger&&) = delete; ~QbonePacketExchanger() = default; bool ReadAndDeliverPacket(QboneClientInterface* qbone_client); void WritePacketToNetwork(const char* packet, size_t size) override; void SetWritable(); private: virtual std::unique_ptr<QuicData> ReadPacket(bool* blocked, std::string* error) = 0; virtual bool WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) = 0; std::list<std::unique_ptr<QuicData>> packet_queue_; Visitor* visitor_; size_t max_pending_packets_; bool write_blocked_ = false; }; } #endif #include "quiche/quic/qbone/qbone_packet_exchanger.h" #include <memory> #include <string> #include <utility> namespace quic { bool QbonePacketExchanger::ReadAndDeliverPacket( QboneClientInterface* qbone_client) { bool blocked = false; std::string error; std::unique_ptr<QuicData> packet = ReadPacket(&blocked, &error); if (packet == nullptr) { if (!blocked && visitor_) { visitor_->OnReadError(error); } return false; } qbone_client->ProcessPacketFromNetwork(packet->AsStringPiece()); return true; } void QbonePacketExchanger::WritePacketToNetwork(const char* packet, size_t size) { bool blocked = false; std::string error; if (packet_queue_.empty() && !write_blocked_) { if (WritePacket(packet, size, &blocked, &error)) { return; } if (blocked) { write_blocked_ = true; } else { QUIC_LOG_EVERY_N_SEC(ERROR, 60) << "Packet write failed: " << error; if (visitor_) { visitor_->OnWriteError(error); } } } if (packet_queue_.size() >= max_pending_packets_) { return; } auto data_copy = new char[size]; memcpy(data_copy, packet, size); packet_queue_.push_back( std::make_unique<QuicData>(data_copy, size, true)); } void QbonePacketExchanger::SetWritable() { write_blocked_ = false; while (!packet_queue_.empty()) { bool blocked = false; std::string error; if (WritePacket(packet_queue_.front()->data(), packet_queue_.front()->length(), &blocked, &error)) { packet_queue_.pop_front(); } else { if (!blocked && visitor_) { visitor_->OnWriteError(error); } write_blocked_ = blocked; return; } } } }
#include "quiche/quic/qbone/qbone_packet_exchanger.h" #include <list> #include <memory> #include <string> #include <utility> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/mock_qbone_client.h" namespace quic { namespace { using ::testing::StrEq; using ::testing::StrictMock; const size_t kMaxPendingPackets = 2; class MockVisitor : public QbonePacketExchanger::Visitor { public: MOCK_METHOD(void, OnReadError, (const std::string&), (override)); MOCK_METHOD(void, OnWriteError, (const std::string&), (override)); }; class FakeQbonePacketExchanger : public QbonePacketExchanger { public: using QbonePacketExchanger::QbonePacketExchanger; void AddPacketToBeRead(std::unique_ptr<QuicData> packet) { packets_to_be_read_.push_back(std::move(packet)); } void SetReadError(const std::string& error) { read_error_ = error; } void ForceWriteFailure(bool blocked, const std::string& error) { write_blocked_ = blocked; write_error_ = error; } const std::vector<std::string>& packets_written() const { return packets_written_; } private: std::unique_ptr<QuicData> ReadPacket(bool* blocked, std::string* error) override { *blocked = false; if (packets_to_be_read_.empty()) { *blocked = read_error_.empty(); *error = read_error_; return nullptr; } std::unique_ptr<QuicData> packet = std::move(packets_to_be_read_.front()); packets_to_be_read_.pop_front(); return packet; } bool WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) override { *blocked = false; if (write_blocked_ || !write_error_.empty()) { *blocked = write_blocked_; *error = write_error_; return false; } packets_written_.push_back(std::string(packet, size)); return true; } std::string read_error_; std::list<std::unique_ptr<QuicData>> packets_to_be_read_; std::string write_error_; bool write_blocked_ = false; std::vector<std::string> packets_written_; }; TEST(QbonePacketExchangerTest, ReadAndDeliverPacketDeliversPacketToQboneClient) { StrictMock<MockVisitor> visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); StrictMock<MockQboneClient> client; std::string packet = "data"; exchanger.AddPacketToBeRead( std::make_unique<QuicData>(packet.data(), packet.length())); EXPECT_CALL(client, ProcessPacketFromNetwork(StrEq("data"))); EXPECT_TRUE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, ReadAndDeliverPacketNotifiesVisitorOnReadFailure) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string io_error = "I/O error"; exchanger.SetReadError(io_error); EXPECT_CALL(visitor, OnReadError(StrEq(io_error))).Times(1); EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, ReadAndDeliverPacketDoesNotNotifyVisitorOnBlockedIO) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); } TEST(QbonePacketExchangerTest, WritePacketToNetworkWritesDirectlyToNetworkWhenNotBlocked) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; exchanger.WritePacketToNetwork(packet.data(), packet.length()); ASSERT_EQ(exchanger.packets_written().size(), 1); EXPECT_THAT(exchanger.packets_written()[0], StrEq(packet)); } TEST(QbonePacketExchangerTest, WritePacketToNetworkQueuesPacketsAndProcessThemLater) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); std::vector<std::string> packets = {"packet0", "packet1"}; for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), 2); for (int i = 0; i < packets.size(); i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, SetWritableContinuesProcessingPacketIfPreviousCallBlocked) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); std::vector<std::string> packets = {"packet0", "packet1"}; for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.SetWritable(); ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), 2); for (int i = 0; i < packets.size(); i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, WritePacketToNetworkDropsPacketIfQueueIfFull) { std::vector<std::string> packets = {"packet0", "packet1", "packet2"}; size_t queue_size = packets.size() - 1; MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, queue_size); MockQboneClient client; exchanger.ForceWriteFailure(true, ""); for (int i = 0; i < packets.size(); i++) { exchanger.WritePacketToNetwork(packets[i].data(), packets[i].length()); } ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(false, ""); exchanger.SetWritable(); ASSERT_EQ(exchanger.packets_written().size(), queue_size); for (int i = 0; i < queue_size; i++) { EXPECT_THAT(exchanger.packets_written()[i], StrEq(packets[i])); } } TEST(QbonePacketExchangerTest, WriteErrorsGetNotified) { MockVisitor visitor; FakeQbonePacketExchanger exchanger(&visitor, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; std::string io_error = "I/O error"; exchanger.ForceWriteFailure(false, io_error); EXPECT_CALL(visitor, OnWriteError(StrEq(io_error))).Times(1); exchanger.WritePacketToNetwork(packet.data(), packet.length()); ASSERT_TRUE(exchanger.packets_written().empty()); exchanger.ForceWriteFailure(true, ""); exchanger.WritePacketToNetwork(packet.data(), packet.length()); std::string sys_error = "sys error"; exchanger.ForceWriteFailure(false, sys_error); EXPECT_CALL(visitor, OnWriteError(StrEq(sys_error))).Times(1); exchanger.SetWritable(); ASSERT_TRUE(exchanger.packets_written().empty()); } TEST(QbonePacketExchangerTest, NullVisitorDoesntCrash) { FakeQbonePacketExchanger exchanger(nullptr, kMaxPendingPackets); MockQboneClient client; std::string packet = "data"; std::string io_error = "I/O error"; exchanger.SetReadError(io_error); EXPECT_FALSE(exchanger.ReadAndDeliverPacket(&client)); exchanger.ForceWriteFailure(false, io_error); exchanger.WritePacketToNetwork(packet.data(), packet.length()); EXPECT_TRUE(exchanger.packets_written().empty()); } } }
216
cpp
google/quiche
netlink
quiche/quic/qbone/platform/netlink.cc
quiche/quic/qbone/platform/netlink_test.cc
#ifndef QUICHE_QUIC_QBONE_PLATFORM_NETLINK_H_ #define QUICHE_QUIC_QBONE_PLATFORM_NETLINK_H_ #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <cstdint> #include <functional> #include <memory> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/qbone/platform/ip_range.h" #include "quiche/quic/qbone/platform/kernel_interface.h" #include "quiche/quic/qbone/platform/netlink_interface.h" namespace quic { class Netlink : public NetlinkInterface { public: explicit Netlink(KernelInterface* kernel); ~Netlink() override; bool GetLinkInfo(const std::string& interface_name, LinkInfo* link_info) override; bool GetAddresses(int interface_index, uint8_t unwanted_flags, std::vector<AddressInfo>* addresses, int* num_ipv6_nodad_dadfailed_addresses) override; bool ChangeLocalAddress( uint32_t interface_index, Verb verb, const QuicIpAddress& address, uint8_t prefix_length, uint8_t ifa_flags, uint8_t ifa_scope, const std::vector<struct rtattr*>& additional_attributes) override; bool GetRouteInfo(std::vector<RoutingRule>* routing_rules) override; bool ChangeRoute(Netlink::Verb verb, uint32_t table, const IpRange& destination_subnet, uint8_t scope, QuicIpAddress preferred_source, int32_t interface_index) override; bool GetRuleInfo(std::vector<Netlink::IpRule>* ip_rules) override; bool ChangeRule(Verb verb, uint32_t table, IpRange source_range) override; bool Send(struct iovec* iov, size_t iovlen) override; bool Recv(uint32_t seq, NetlinkParserInterface* parser) override; private: void ResetRecvBuf(size_t size); bool OpenSocket(); void CloseSocket(); KernelInterface* kernel_; int socket_fd_ = -1; std::unique_ptr<char[]> recvbuf_ = nullptr; size_t recvbuf_length_ = 0; uint32_t seq_; }; } #endif #include "quiche/quic/qbone/platform/netlink.h" #include <linux/fib_rules.h> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/rtnetlink_message.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic { Netlink::Netlink(KernelInterface* kernel) : kernel_(kernel) { seq_ = QuicRandom::GetInstance()->RandUint64(); } Netlink::~Netlink() { CloseSocket(); } void Netlink::ResetRecvBuf(size_t size) { if (size != 0) { recvbuf_ = std::make_unique<char[]>(size); } else { recvbuf_ = nullptr; } recvbuf_length_ = size; } bool Netlink::OpenSocket() { if (socket_fd_ >= 0) { return true; } socket_fd_ = kernel_->socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (socket_fd_ < 0) { QUIC_PLOG(ERROR) << "can't open netlink socket"; return false; } QUIC_LOG(INFO) << "Opened a new netlink socket fd = " << socket_fd_; sockaddr_nl myaddr; memset(&myaddr, 0, sizeof(myaddr)); myaddr.nl_family = AF_NETLINK; if (kernel_->bind(socket_fd_, reinterpret_cast<struct sockaddr*>(&myaddr), sizeof(myaddr)) < 0) { QUIC_LOG(INFO) << "can't bind address to socket"; CloseSocket(); return false; } return true; } void Netlink::CloseSocket() { if (socket_fd_ >= 0) { QUIC_LOG(INFO) << "Closing netlink socket fd = " << socket_fd_; kernel_->close(socket_fd_); } ResetRecvBuf(0); socket_fd_ = -1; } namespace { class LinkInfoParser : public NetlinkParserInterface { public: LinkInfoParser(std::string interface_name, Netlink::LinkInfo* link_info) : interface_name_(std::move(interface_name)), link_info_(link_info) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWLINK) { QUIC_LOG(INFO) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWLINK); return; } struct ifinfomsg* interface_info = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); if (interface_info->ifi_family != AF_UNSPEC) { QUIC_LOG(INFO) << absl::StrCat( "Unexpected ifi_family: ", interface_info->ifi_family, " expected: ", AF_UNSPEC); return; } char hardware_address[kHwAddrSize]; size_t hardware_address_length = 0; char broadcast_address[kHwAddrSize]; size_t broadcast_address_length = 0; std::string name; struct rtattr* rta; int payload_length = IFLA_PAYLOAD(netlink_message); for (rta = IFLA_RTA(interface_info); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { int attribute_length; switch (rta->rta_type) { case IFLA_ADDRESS: { attribute_length = RTA_PAYLOAD(rta); if (attribute_length > kHwAddrSize) { QUIC_VLOG(2) << "IFLA_ADDRESS too long: " << attribute_length; break; } memmove(hardware_address, RTA_DATA(rta), attribute_length); hardware_address_length = attribute_length; break; } case IFLA_BROADCAST: { attribute_length = RTA_PAYLOAD(rta); if (attribute_length > kHwAddrSize) { QUIC_VLOG(2) << "IFLA_BROADCAST too long: " << attribute_length; break; } memmove(broadcast_address, RTA_DATA(rta), attribute_length); broadcast_address_length = attribute_length; break; } case IFLA_IFNAME: { name = std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)); name = name.substr(0, name.find('\0')); break; } } } QUIC_VLOG(2) << "interface name: " << name << ", index: " << interface_info->ifi_index; if (name == interface_name_) { link_info_->index = interface_info->ifi_index; link_info_->type = interface_info->ifi_type; link_info_->hardware_address_length = hardware_address_length; if (hardware_address_length > 0) { memmove(&link_info_->hardware_address, hardware_address, hardware_address_length); } link_info_->broadcast_address_length = broadcast_address_length; if (broadcast_address_length > 0) { memmove(&link_info_->broadcast_address, broadcast_address, broadcast_address_length); } found_link_ = true; } } bool found_link() { return found_link_; } private: const std::string interface_name_; Netlink::LinkInfo* const link_info_; bool found_link_ = false; }; } bool Netlink::GetLinkInfo(const std::string& interface_name, LinkInfo* link_info) { auto message = LinkMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, seq_, getpid(), nullptr); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed."; return false; } LinkInfoParser parser(interface_name, link_info); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed."; return false; } return parser.found_link(); } namespace { class LocalAddressParser : public NetlinkParserInterface { public: LocalAddressParser(int interface_index, uint8_t unwanted_flags, std::vector<Netlink::AddressInfo>* local_addresses, int* num_ipv6_nodad_dadfailed_addresses) : interface_index_(interface_index), unwanted_flags_(unwanted_flags), local_addresses_(local_addresses), num_ipv6_nodad_dadfailed_addresses_( num_ipv6_nodad_dadfailed_addresses) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWADDR) { QUIC_LOG(INFO) << "Unexpected nlmsg_type: " << netlink_message->nlmsg_type << " expected: " << RTM_NEWADDR; return; } struct ifaddrmsg* interface_address = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_message)); if (interface_address->ifa_family != AF_INET && interface_address->ifa_family != AF_INET6) { QUIC_VLOG(2) << absl::StrCat("uninteresting ifa family: ", interface_address->ifa_family); return; } if (num_ipv6_nodad_dadfailed_addresses_ != nullptr && (interface_address->ifa_flags & IFA_F_NODAD) && (interface_address->ifa_flags & IFA_F_DADFAILED)) { ++(*num_ipv6_nodad_dadfailed_addresses_); } uint8_t unwanted_flags = interface_address->ifa_flags & unwanted_flags_; if (unwanted_flags != 0) { QUIC_VLOG(2) << absl::StrCat("unwanted ifa flags: ", unwanted_flags); return; } struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); Netlink::AddressInfo address_info; for (rta = IFA_RTA(interface_address); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { if (rta->rta_type != IFA_LOCAL && rta->rta_type != IFA_ADDRESS) { QUIC_VLOG(2) << "Ignoring uninteresting rta_type: " << rta->rta_type; continue; } switch (interface_address->ifa_family) { case AF_INET: ABSL_FALLTHROUGH_INTENDED; case AF_INET6: if (RTA_PAYLOAD(rta) == sizeof(struct in_addr) || RTA_PAYLOAD(rta) == sizeof(struct in6_addr)) { auto* raw_ip = reinterpret_cast<char*>(RTA_DATA(rta)); if (rta->rta_type == IFA_LOCAL) { address_info.local_address.FromPackedString(raw_ip, RTA_PAYLOAD(rta)); } else { address_info.interface_address.FromPackedString(raw_ip, RTA_PAYLOAD(rta)); } } break; default: QUIC_LOG(ERROR) << absl::StrCat("Unknown address family: ", interface_address->ifa_family); } } QUIC_VLOG(2) << "local_address: " << address_info.local_address.ToString() << " interface_address: " << address_info.interface_address.ToString() << " index: " << interface_address->ifa_index; if (interface_address->ifa_index != interface_index_) { return; } address_info.prefix_length = interface_address->ifa_prefixlen; address_info.scope = interface_address->ifa_scope; if (address_info.local_address.IsInitialized() || address_info.interface_address.IsInitialized()) { local_addresses_->push_back(address_info); } } private: const int interface_index_; const uint8_t unwanted_flags_; std::vector<Netlink::AddressInfo>* const local_addresses_; int* const num_ipv6_nodad_dadfailed_addresses_; }; } bool Netlink::GetAddresses(int interface_index, uint8_t unwanted_flags, std::vector<AddressInfo>* addresses, int* num_ipv6_nodad_dadfailed_addresses) { auto message = AddressMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, seq_, getpid(), nullptr); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed."; return false; } addresses->clear(); if (num_ipv6_nodad_dadfailed_addresses != nullptr) { *num_ipv6_nodad_dadfailed_addresses = 0; } LocalAddressParser parser(interface_index, unwanted_flags, addresses, num_ipv6_nodad_dadfailed_addresses); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed"; return false; } return true; } namespace { class UnknownParser : public NetlinkParserInterface { public: void Run(struct nlmsghdr* netlink_message) override { QUIC_LOG(INFO) << "nlmsg reply type: " << netlink_message->nlmsg_type; } }; } bool Netlink::ChangeLocalAddress( uint32_t interface_index, Verb verb, const QuicIpAddress& address, uint8_t prefix_length, uint8_t ifa_flags, uint8_t ifa_scope, const std::vector<struct rtattr*>& additional_attributes) { if (verb == Verb::kReplace) { return false; } auto operation = verb == Verb::kAdd ? RtnetlinkMessage::Operation::NEW : RtnetlinkMessage::Operation::DEL; uint8_t address_family; if (address.address_family() == IpAddressFamily::IP_V4) { address_family = AF_INET; } else if (address.address_family() == IpAddressFamily::IP_V6) { address_family = AF_INET6; } else { return false; } struct ifaddrmsg address_header = {address_family, prefix_length, ifa_flags, ifa_scope, interface_index}; auto message = AddressMessage::New(operation, NLM_F_REQUEST | NLM_F_ACK, seq_, getpid(), &address_header); for (const auto& attribute : additional_attributes) { if (attribute->rta_type == IFA_LOCAL) { continue; } message.AppendAttribute(attribute->rta_type, RTA_DATA(attribute), RTA_PAYLOAD(attribute)); } message.AppendAttribute(IFA_LOCAL, address.ToPackedString().c_str(), address.ToPackedString().size()); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } namespace { class RoutingRuleParser : public NetlinkParserInterface { public: explicit RoutingRuleParser(std::vector<Netlink::RoutingRule>* routing_rules) : routing_rules_(routing_rules) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWROUTE) { QUIC_LOG(WARNING) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWROUTE); return; } auto* route = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(netlink_message)); int payload_length = RTM_PAYLOAD(netlink_message); if (route->rtm_family != AF_INET && route->rtm_family != AF_INET6) { QUIC_VLOG(2) << absl::StrCat("Uninteresting family: ", route->rtm_family); return; } Netlink::RoutingRule rule; rule.scope = route->rtm_scope; rule.table = route->rtm_table; struct rtattr* rta; for (rta = RTM_RTA(route); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_TABLE: { rule.table = *reinterpret_cast<uint32_t*>(RTA_DATA(rta)); break; } case RTA_DST: { QuicIpAddress destination; destination.FromPackedString(reinterpret_cast<char*> RTA_DATA(rta), RTA_PAYLOAD(rta)); rule.destination_subnet = IpRange(destination, route->rtm_dst_len); break; } case RTA_PREFSRC: { QuicIpAddress preferred_source; rule.preferred_source.FromPackedString( reinterpret_cast<char*> RTA_DATA(rta), RTA_PAYLOAD(rta)); break; } case RTA_OIF: { rule.out_interface = *reinterpret_cast<int*>(RTA_DATA(rta)); break; } default: { QUIC_VLOG(2) << absl::StrCat("Uninteresting attribute: ", rta->rta_type); } } } routing_rules_->push_back(rule); } private: std::vector<Netlink::RoutingRule>* routing_rules_; }; } bool Netlink::GetRouteInfo(std::vector<Netlink::RoutingRule>* routing_rules) { rtmsg route_message{}; route_message.rtm_table = RT_TABLE_MAIN; auto message = RouteMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH, seq_, getpid(), &route_message); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } RoutingRuleParser parser(routing_rules); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "recv failed"; return false; } return true; } bool Netlink::ChangeRoute(Netlink::Verb verb, uint32_t table, const IpRange& destination_subnet, uint8_t scope, QuicIpAddress preferred_source, int32_t interface_index) { if (!destination_subnet.prefix().IsInitialized()) { return false; } if (destination_subnet.address_family() != IpAddressFamily::IP_V4 && destination_subnet.address_family() != IpAddressFamily::IP_V6) { return false; } if (preferred_source.IsInitialized() && preferred_source.address_family() != destination_subnet.address_family()) { return false; } RtnetlinkMessage::Operation operation; uint16_t flags = NLM_F_REQUEST | NLM_F_ACK; switch (verb) { case Verb::kAdd: operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_EXCL | NLM_F_CREATE; break; case Verb::kRemove: operation = RtnetlinkMessage::Operation::DEL; break; case Verb::kReplace: operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_REPLACE | NLM_F_CREATE; break; } struct rtmsg route_message; memset(&route_message, 0, sizeof(route_message)); route_message.rtm_family = destination_subnet.address_family() == IpAddressFamily::IP_V4 ? AF_INET : AF_INET6; route_message.rtm_dst_len = destination_subnet.prefix_length(); route_message.rtm_src_len = 0; route_message.rtm_table = RT_TABLE_MAIN; route_message.rtm_protocol = verb == Verb::kRemove ? RTPROT_UNSPEC : RTPROT_STATIC; route_message.rtm_scope = scope; route_message.rtm_type = RTN_UNICAST; auto message = RouteMessage::New(operation, flags, seq_, getpid(), &route_message); message.AppendAttribute(RTA_TABLE, &table, sizeof(table)); message.AppendAttribute(RTA_OIF, &interface_index, sizeof(interface_index)); message.AppendAttribute( RTA_DST, reinterpret_cast<const void*>( destination_subnet.prefix().ToPackedString().c_str()), destination_subnet.prefix().ToPackedString().size()); if (preferred_source.IsInitialized()) { auto src_str = preferred_source.ToPackedString(); message.AppendAttribute(RTA_PREFSRC, reinterpret_cast<const void*>(src_str.c_str()), src_str.size()); } if (verb != Verb::kRemove) { auto gateway_str = QboneConstants::GatewayAddress()->ToPackedString(); message.AppendAttribute(RTA_GATEWAY, reinterpret_cast<const void*>(gateway_str.c_str()), gateway_str.size()); } if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } namespace { class IpRuleParser : public NetlinkParserInterface { public: explicit IpRuleParser(std::vector<Netlink::IpRule>* ip_rules) : ip_rules_(ip_rules) {} void Run(struct nlmsghdr* netlink_message) override { if (netlink_message->nlmsg_type != RTM_NEWRULE) { QUIC_LOG(WARNING) << absl::StrCat( "Unexpected nlmsg_type: ", netlink_message->nlmsg_type, " expected: ", RTM_NEWRULE); return; } auto* rule = reinterpret_cast<rtmsg*>(NLMSG_DATA(netlink_message)); int payload_length = RTM_PAYLOAD(netlink_message); if (rule->rtm_family != AF_INET6) { QUIC_LOG(ERROR) << absl::StrCat("Unexpected family: ", rule->rtm_family); return; } Netlink::IpRule ip_rule; ip_rule.table = rule->rtm_table; struct rtattr* rta; for (rta = RTM_RTA(rule); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_TABLE: { ip_rule.table = *reinterpret_cast<uint32_t*>(RTA_DATA(rta)); break; } case RTA_SRC: { QuicIpAddress src_addr; src_addr.FromPackedString(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)); IpRange src_range(src_addr, rule->rtm_src_len); ip_rule.source_range = src_range; break; } default: { QUIC_VLOG(2) << absl::StrCat("Uninteresting attribute: ", rta->rta_type); } } } ip_rules_->emplace_back(ip_rule); } private: std::vector<Netlink::IpRule>* ip_rules_; }; } bool Netlink::GetRuleInfo(std::vector<Netlink::IpRule>* ip_rules) { rtmsg rule_message{}; rule_message.rtm_family = AF_INET6; auto message = RuleMessage::New(RtnetlinkMessage::Operation::GET, NLM_F_REQUEST | NLM_F_DUMP, seq_, getpid(), &rule_message); if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } IpRuleParser parser(ip_rules); if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } bool Netlink::ChangeRule(Verb verb, uint32_t table, IpRange source_range) { RtnetlinkMessage::Operation operation; uint16_t flags = NLM_F_REQUEST | NLM_F_ACK; rtmsg rule_message{}; rule_message.rtm_family = AF_INET6; rule_message.rtm_protocol = RTPROT_STATIC; rule_message.rtm_scope = RT_SCOPE_UNIVERSE; rule_message.rtm_table = RT_TABLE_UNSPEC; rule_message.rtm_flags |= FIB_RULE_FIND_SADDR; switch (verb) { case Verb::kAdd: if (!source_range.IsInitialized()) { QUIC_LOG(ERROR) << "Source range must be initialized."; return false; } operation = RtnetlinkMessage::Operation::NEW; flags |= NLM_F_EXCL | NLM_F_CREATE; rule_message.rtm_type = FRA_DST; rule_message.rtm_src_len = source_range.prefix_length(); break; case Verb::kRemove: operation = RtnetlinkMessage::Operation::DEL; break; case Verb::kReplace: QUIC_LOG(ERROR) << "Unsupported verb: kReplace"; return false; } auto message = RuleMessage::New(operation, flags, seq_, getpid(), &rule_message); message.AppendAttribute(RTA_TABLE, &table, sizeof(table)); if (source_range.IsInitialized()) { std::string packed_src = source_range.prefix().ToPackedString(); message.AppendAttribute(RTA_SRC, reinterpret_cast<const void*>(packed_src.c_str()), packed_src.size()); } if (!Send(message.BuildIoVec().get(), message.IoVecSize())) { QUIC_LOG(ERROR) << "send failed"; return false; } UnknownParser parser; if (!Recv(seq_++, &parser)) { QUIC_LOG(ERROR) << "receive failed."; return false; } return true; } bool Netlink::Send(struct iovec* iov, size_t iovlen) { if (!OpenSocket()) { QUIC_LOG(ERROR) << "can't open socket"; return false; } sockaddr_nl netlink_address; memset(&netlink_address, 0, sizeof(netlink_address)); netlink_address.nl_family = AF_NETLINK; netlink_address.nl_pid = 0; netlink_address.nl_groups = 0; struct msghdr msg = { &netlink_address, sizeof(netlink_address), iov, iovlen, nullptr, 0, 0}; if (kernel_->sendmsg(socket_fd_, &msg, 0) < 0) { QUIC_LOG(ERROR) << "sendmsg failed"; CloseSocket(); return false; } return true; } bool Netlink::Recv(uint32_t seq, NetlinkParserInterface* parser) { sockaddr_nl netlink_address; for (;;) { socklen_t address_length = sizeof(netlink_address); int next_packet_size = kernel_->recvfrom( socket_fd_, recvbuf_.get(), 0, MSG_PEEK | MSG_TRUNC, reinterpret_cast<struct sockaddr*>(&netlink_address), &address_length); if (next_packet_size < 0) { QUIC_LOG(ERROR) << "error recvfrom with MSG_PEEK | MSG_TRUNC to get packet length."; CloseSocket(); return false; } QUIC_VLOG(3) << "netlink packet size: " << next_packet_size; if (next_packet_size > recvbuf_length_) { QUIC_VLOG(2) << "resizing recvbuf to " << next_packet_size; ResetRecvBuf(next_packet_size); } memset(recvbuf_.get(), 0, recvbuf_length_); int len = kernel_->recvfrom( socket_fd_, recvbuf_.get(), recvbuf_length_, 0, reinterpret_cast<struct sockaddr*>(&netlink_address), &address_length); QUIC_VLOG(3) << "recvfrom returned: " << len; if (len < 0) { QUIC_LOG(INFO) << "can't receive netlink packet"; CloseSocket(); return false; } struct nlmsghdr* netlink_message; for (netlink_message = reinterpret_cast<struct nlmsghdr*>(recvbuf_.get()); NLMSG_OK(netlink_message, len); netlink_message = NLMSG_NEXT(netlink_message, len)) { QUIC_VLOG(3) << "netlink_message->nlmsg_type = " << netlink_message->nlmsg_type; if (netlink_message->nlmsg_seq != seq) { QUIC_LOG(INFO) << "netlink_message not meant for us." << " seq: " << seq << " nlmsg_seq: "
#include "quiche/quic/qbone/platform/netlink.h" #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/node_hash_set.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic::test { namespace { using ::testing::_; using ::testing::Contains; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::Unused; const int kSocketFd = 101; class NetlinkTest : public QuicTest { protected: NetlinkTest() { ON_CALL(mock_kernel_, socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) .WillByDefault(Invoke([this](Unused, Unused, Unused) { EXPECT_CALL(mock_kernel_, close(kSocketFd)).WillOnce(Return(0)); return kSocketFd; })); } void ExpectNetlinkPacket( uint16_t type, uint16_t flags, const std::function<ssize_t(void* buf, size_t len, int seq)>& recv_callback, const std::function<void(const void* buf, size_t len)>& send_callback = nullptr) { static int seq = -1; InSequence s; EXPECT_CALL(mock_kernel_, sendmsg(kSocketFd, _, _)) .WillOnce(Invoke([type, flags, send_callback]( Unused, const struct msghdr* msg, int) { EXPECT_EQ(sizeof(struct sockaddr_nl), msg->msg_namelen); auto* nl_addr = reinterpret_cast<const struct sockaddr_nl*>(msg->msg_name); EXPECT_EQ(AF_NETLINK, nl_addr->nl_family); EXPECT_EQ(0, nl_addr->nl_pid); EXPECT_EQ(0, nl_addr->nl_groups); EXPECT_GE(msg->msg_iovlen, 1); EXPECT_GE(msg->msg_iov[0].iov_len, sizeof(struct nlmsghdr)); std::string buf; for (int i = 0; i < msg->msg_iovlen; i++) { buf.append( std::string(reinterpret_cast<char*>(msg->msg_iov[i].iov_base), msg->msg_iov[i].iov_len)); } auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf.c_str()); EXPECT_EQ(type, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_GE(buf.size(), netlink_message->nlmsg_len); if (send_callback != nullptr) { send_callback(buf.c_str(), buf.size()); } QUICHE_CHECK_EQ(seq, -1); seq = netlink_message->nlmsg_seq; return buf.size(); })); EXPECT_CALL(mock_kernel_, recvfrom(kSocketFd, _, 0, MSG_PEEK | MSG_TRUNC, _, _)) .WillOnce(Invoke([this, recv_callback](Unused, Unused, Unused, Unused, struct sockaddr* src_addr, socklen_t* addrlen) { auto* nl_addr = reinterpret_cast<struct sockaddr_nl*>(src_addr); nl_addr->nl_family = AF_NETLINK; nl_addr->nl_pid = 0; nl_addr->nl_groups = 0; int ret = recv_callback(reply_packet_, sizeof(reply_packet_), seq); QUICHE_CHECK_LE(ret, sizeof(reply_packet_)); return ret; })); EXPECT_CALL(mock_kernel_, recvfrom(kSocketFd, _, _, _, _, _)) .WillOnce(Invoke([recv_callback](Unused, void* buf, size_t len, Unused, struct sockaddr* src_addr, socklen_t* addrlen) { auto* nl_addr = reinterpret_cast<struct sockaddr_nl*>(src_addr); nl_addr->nl_family = AF_NETLINK; nl_addr->nl_pid = 0; nl_addr->nl_groups = 0; int ret = recv_callback(buf, len, seq); EXPECT_GE(len, ret); seq = -1; return ret; })); } char reply_packet_[4096]; MockKernel mock_kernel_; }; void AddRTA(struct nlmsghdr* netlink_message, uint16_t type, const void* data, size_t len) { auto* next_header_ptr = reinterpret_cast<char*>(netlink_message) + NLMSG_ALIGN(netlink_message->nlmsg_len); auto* rta = reinterpret_cast<struct rtattr*>(next_header_ptr); rta->rta_type = type; rta->rta_len = RTA_LENGTH(len); memcpy(RTA_DATA(rta), data, len); netlink_message->nlmsg_len = NLMSG_ALIGN(netlink_message->nlmsg_len) + RTA_LENGTH(len); } void CreateIfinfomsg(struct nlmsghdr* netlink_message, const std::string& interface_name, uint16_t type, int index, unsigned int flags, unsigned int change, uint8_t address[], int address_len, uint8_t broadcast[], int broadcast_len) { auto* interface_info = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); interface_info->ifi_family = AF_UNSPEC; interface_info->ifi_type = type; interface_info->ifi_index = index; interface_info->ifi_flags = flags; interface_info->ifi_change = change; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)); AddRTA(netlink_message, IFLA_ADDRESS, address, address_len); AddRTA(netlink_message, IFLA_BROADCAST, broadcast, broadcast_len); AddRTA(netlink_message, IFLA_IFNAME, interface_name.c_str(), interface_name.size()); } struct nlmsghdr* CreateNetlinkMessage(void* buf, struct nlmsghdr* previous_netlink_message, uint16_t type, int seq) { auto* next_header_ptr = reinterpret_cast<char*>(buf); if (previous_netlink_message != nullptr) { next_header_ptr = reinterpret_cast<char*>(previous_netlink_message) + NLMSG_ALIGN(previous_netlink_message->nlmsg_len); } auto* netlink_message = reinterpret_cast<nlmsghdr*>(next_header_ptr); netlink_message->nlmsg_len = NLMSG_LENGTH(0); netlink_message->nlmsg_type = type; netlink_message->nlmsg_flags = NLM_F_MULTI; netlink_message->nlmsg_pid = 0; netlink_message->nlmsg_seq = seq; return netlink_message; } void CreateIfaddrmsg(struct nlmsghdr* nlm, int interface_index, unsigned char prefixlen, unsigned char flags, unsigned char scope, QuicIpAddress ip) { QUICHE_CHECK(ip.IsInitialized()); unsigned char family; switch (ip.address_family()) { case IpAddressFamily::IP_V4: family = AF_INET; break; case IpAddressFamily::IP_V6: family = AF_INET6; break; default: QUIC_BUG(quic_bug_11034_1) << absl::StrCat("unexpected address family: ", ip.address_family()); family = AF_UNSPEC; } auto* msg = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(nlm)); msg->ifa_family = family; msg->ifa_prefixlen = prefixlen; msg->ifa_flags = flags; msg->ifa_scope = scope; msg->ifa_index = interface_index; nlm->nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)); AddRTA(nlm, IFA_LOCAL, ip.ToPackedString().c_str(), ip.ToPackedString().size()); } void CreateRtmsg(struct nlmsghdr* nlm, unsigned char family, unsigned char destination_length, unsigned char source_length, unsigned char tos, unsigned char table, unsigned char protocol, unsigned char scope, unsigned char type, unsigned int flags, QuicIpAddress destination, int interface_index) { auto* msg = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(nlm)); msg->rtm_family = family; msg->rtm_dst_len = destination_length; msg->rtm_src_len = source_length; msg->rtm_tos = tos; msg->rtm_table = table; msg->rtm_protocol = protocol; msg->rtm_scope = scope; msg->rtm_type = type; msg->rtm_flags = flags; nlm->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); AddRTA(nlm, RTA_DST, destination.ToPackedString().c_str(), destination.ToPackedString().size()); AddRTA(nlm, RTA_OIF, &interface_index, sizeof(interface_index)); } TEST_F(NetlinkTest, GetLinkInfoWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); uint8_t hwaddr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; uint8_t bcaddr[] = {'c', 'b', 'a', 'f', 'e', 'd'}; ExpectNetlinkPacket( RTM_GETLINK, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [&hwaddr, &bcaddr](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, RTM_NEWLINK, seq); CreateIfinfomsg(netlink_message, "tun0", 1, 7, 0, 0xFFFFFFFF, hwaddr, 6, bcaddr, 6); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); netlink_message = CreateNetlinkMessage(buf, netlink_message, NLMSG_DONE, seq); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); return ret; }); Netlink::LinkInfo link_info; EXPECT_TRUE(netlink->GetLinkInfo("tun0", &link_info)); EXPECT_EQ(7, link_info.index); EXPECT_EQ(1, link_info.type); for (int i = 0; i < link_info.hardware_address_length; ++i) { EXPECT_EQ(hwaddr[i], link_info.hardware_address[i]); } for (int i = 0; i < link_info.broadcast_address_length; ++i) { EXPECT_EQ(bcaddr[i], link_info.broadcast_address[i]); } } TEST_F(NetlinkTest, GetAddressesWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); absl::node_hash_set<std::string> addresses = { QuicIpAddress::Any4().ToString(), QuicIpAddress::Any6().ToString()}; ExpectNetlinkPacket( RTM_GETADDR, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [&addresses](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* nlm = nullptr; for (const auto& address : addresses) { QuicIpAddress ip; ip.FromString(address); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 24, 0, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); } { QuicIpAddress ip; ip.FromString("10.0.0.1"); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 16, IFA_F_OPTIMISTIC, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); ip.FromString("10.0.0.2"); nlm = CreateNetlinkMessage(buf, nlm, RTM_NEWADDR, seq); CreateIfaddrmsg(nlm, 7, 16, IFA_F_TENTATIVE, RT_SCOPE_UNIVERSE, ip); ret += NLMSG_ALIGN(nlm->nlmsg_len); } nlm = CreateNetlinkMessage(buf, nlm, NLMSG_DONE, seq); ret += NLMSG_ALIGN(nlm->nlmsg_len); return ret; }); std::vector<Netlink::AddressInfo> reported_addresses; int num_ipv6_nodad_dadfailed_addresses = 0; EXPECT_TRUE(netlink->GetAddresses(7, IFA_F_TENTATIVE | IFA_F_OPTIMISTIC, &reported_addresses, &num_ipv6_nodad_dadfailed_addresses)); for (const auto& reported_address : reported_addresses) { EXPECT_TRUE(reported_address.local_address.IsInitialized()); EXPECT_FALSE(reported_address.interface_address.IsInitialized()); EXPECT_THAT(addresses, Contains(reported_address.local_address.ToString())); addresses.erase(reported_address.local_address.ToString()); EXPECT_EQ(24, reported_address.prefix_length); } EXPECT_TRUE(addresses.empty()); } TEST_F(NetlinkTest, ChangeLocalAddressAdd) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress ip = QuicIpAddress::Any6(); ExpectNetlinkPacket( RTM_NEWADDR, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [ip](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* ifa = reinterpret_cast<const struct ifaddrmsg*>( NLMSG_DATA(netlink_message)); EXPECT_EQ(19, ifa->ifa_prefixlen); EXPECT_EQ(RT_SCOPE_UNIVERSE, ifa->ifa_scope); EXPECT_EQ(IFA_F_PERMANENT, ifa->ifa_flags); EXPECT_EQ(7, ifa->ifa_index); EXPECT_EQ(AF_INET6, ifa->ifa_family); const struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); int num_rta = 0; for (rta = IFA_RTA(ifa); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case IFA_LOCAL: { EXPECT_EQ(ip.ToPackedString().size(), RTA_PAYLOAD(rta)); const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(ip, address); break; } case IFA_CACHEINFO: { EXPECT_EQ(sizeof(struct ifa_cacheinfo), RTA_PAYLOAD(rta)); const auto* cache_info = reinterpret_cast<const struct ifa_cacheinfo*>(RTA_DATA(rta)); EXPECT_EQ(8, cache_info->ifa_prefered); EXPECT_EQ(6, cache_info->ifa_valid); EXPECT_EQ(4, cache_info->cstamp); EXPECT_EQ(2, cache_info->tstamp); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not exist"; } ++num_rta; } EXPECT_EQ(2, num_rta); }); struct { struct rtattr rta; struct ifa_cacheinfo cache_info; } additional_rta; additional_rta.rta.rta_type = IFA_CACHEINFO; additional_rta.rta.rta_len = RTA_LENGTH(sizeof(struct ifa_cacheinfo)); additional_rta.cache_info.ifa_prefered = 8; additional_rta.cache_info.ifa_valid = 6; additional_rta.cache_info.cstamp = 4; additional_rta.cache_info.tstamp = 2; EXPECT_TRUE(netlink->ChangeLocalAddress(7, Netlink::Verb::kAdd, ip, 19, IFA_F_PERMANENT, RT_SCOPE_UNIVERSE, {&additional_rta.rta})); } TEST_F(NetlinkTest, ChangeLocalAddressRemove) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress ip = QuicIpAddress::Any4(); ExpectNetlinkPacket( RTM_DELADDR, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [ip](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* ifa = reinterpret_cast<const struct ifaddrmsg*>( NLMSG_DATA(netlink_message)); EXPECT_EQ(32, ifa->ifa_prefixlen); EXPECT_EQ(RT_SCOPE_UNIVERSE, ifa->ifa_scope); EXPECT_EQ(0, ifa->ifa_flags); EXPECT_EQ(7, ifa->ifa_index); EXPECT_EQ(AF_INET, ifa->ifa_family); const struct rtattr* rta; int payload_length = IFA_PAYLOAD(netlink_message); int num_rta = 0; for (rta = IFA_RTA(ifa); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case IFA_LOCAL: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(in_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(ip, address); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not exist"; } ++num_rta; } EXPECT_EQ(1, num_rta); }); EXPECT_TRUE(netlink->ChangeLocalAddress(7, Netlink::Verb::kRemove, ip, 32, 0, RT_SCOPE_UNIVERSE, {})); } TEST_F(NetlinkTest, GetRouteInfoWorks) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress destination; ASSERT_TRUE(destination.FromString("f800::2")); ExpectNetlinkPacket(RTM_GETROUTE, NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST, [destination](void* buf, size_t len, int seq) { int ret = 0; struct nlmsghdr* netlink_message = CreateNetlinkMessage( buf, nullptr, RTM_NEWROUTE, seq); CreateRtmsg(netlink_message, AF_INET6, 48, 0, 0, RT_TABLE_MAIN, RTPROT_STATIC, RT_SCOPE_LINK, RTN_UNICAST, 0, destination, 7); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); netlink_message = CreateNetlinkMessage( buf, netlink_message, NLMSG_DONE, seq); ret += NLMSG_ALIGN(netlink_message->nlmsg_len); QUIC_LOG(INFO) << "ret: " << ret; return ret; }); std::vector<Netlink::RoutingRule> routing_rules; EXPECT_TRUE(netlink->GetRouteInfo(&routing_rules)); ASSERT_EQ(1, routing_rules.size()); EXPECT_EQ(RT_SCOPE_LINK, routing_rules[0].scope); EXPECT_EQ(IpRange(destination, 48).ToString(), routing_rules[0].destination_subnet.ToString()); EXPECT_FALSE(routing_rules[0].preferred_source.IsInitialized()); EXPECT_EQ(7, routing_rules[0].out_interface); } TEST_F(NetlinkTest, ChangeRouteAdd) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_NEWROUTE, NLM_F_ACK | NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_STATIC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_GATEWAY: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(*QboneConstants::GatewayAddress(), address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(5, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kAdd, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } TEST_F(NetlinkTest, ChangeRouteRemove) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_DELROUTE, NLM_F_ACK | NLM_F_REQUEST, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_UNSPEC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(4, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kRemove, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } TEST_F(NetlinkTest, ChangeRouteReplace) { auto netlink = std::make_unique<Netlink>(&mock_kernel_); QuicIpAddress preferred_ip; preferred_ip.FromString("ff80:dead:beef::1"); IpRange subnet; subnet.FromString("ff80:dead:beef::/48"); int egress_interface_index = 7; ExpectNetlinkPacket( RTM_NEWROUTE, NLM_F_ACK | NLM_F_REQUEST | NLM_F_CREATE | NLM_F_REPLACE, [](void* buf, size_t len, int seq) { struct nlmsghdr* netlink_message = CreateNetlinkMessage(buf, nullptr, NLMSG_ERROR, seq); auto* err = reinterpret_cast<struct nlmsgerr*>(NLMSG_DATA(netlink_message)); err->error = 0; netlink_message->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); return netlink_message->nlmsg_len; }, [preferred_ip, subnet, egress_interface_index](const void* buf, size_t len) { auto* netlink_message = reinterpret_cast<const struct nlmsghdr*>(buf); auto* rtm = reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(AF_INET6, rtm->rtm_family); EXPECT_EQ(48, rtm->rtm_dst_len); EXPECT_EQ(0, rtm->rtm_src_len); EXPECT_EQ(RT_TABLE_MAIN, rtm->rtm_table); EXPECT_EQ(RTPROT_STATIC, rtm->rtm_protocol); EXPECT_EQ(RT_SCOPE_LINK, rtm->rtm_scope); EXPECT_EQ(RTN_UNICAST, rtm->rtm_type); const struct rtattr* rta; int payload_length = RTM_PAYLOAD(netlink_message); int num_rta = 0; for (rta = RTM_RTA(rtm); RTA_OK(rta, payload_length); rta = RTA_NEXT(rta, payload_length)) { switch (rta->rta_type) { case RTA_PREFSRC: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(preferred_ip, address); break; } case RTA_GATEWAY: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(*QboneConstants::GatewayAddress(), address); break; } case RTA_OIF: { ASSERT_EQ(sizeof(int), RTA_PAYLOAD(rta)); const auto* interface_index = reinterpret_cast<const int*>(RTA_DATA(rta)); EXPECT_EQ(egress_interface_index, *interface_index); break; } case RTA_DST: { const auto* raw_address = reinterpret_cast<const char*>(RTA_DATA(rta)); ASSERT_EQ(sizeof(struct in6_addr), RTA_PAYLOAD(rta)); QuicIpAddress address; address.FromPackedString(raw_address, RTA_PAYLOAD(rta)); EXPECT_EQ(subnet.ToString(), IpRange(address, rtm->rtm_dst_len).ToString()); break; } case RTA_TABLE: { ASSERT_EQ(*reinterpret_cast<uint32_t*>(RTA_DATA(rta)), QboneConstants::kQboneRouteTableId); break; } default: EXPECT_TRUE(false) << "Seeing rtattr that should not be sent"; } ++num_rta; } EXPECT_EQ(5, num_rta); }); EXPECT_TRUE(netlink->ChangeRoute( Netlink::Verb::kReplace, QboneConstants::kQboneRouteTableId, subnet, RT_SCOPE_LINK, preferred_ip, egress_interface_index)); } } }
217
cpp
google/quiche
ip_range
quiche/quic/qbone/platform/ip_range.cc
quiche/quic/qbone/platform/ip_range_test.cc
#ifndef QUICHE_QUIC_QBONE_PLATFORM_IP_RANGE_H_ #define QUICHE_QUIC_QBONE_PLATFORM_IP_RANGE_H_ #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" namespace quic { class IpRange { public: IpRange() : prefix_length_(0) {} IpRange(const QuicIpAddress& prefix, size_t prefix_length); bool operator==(IpRange other) const; bool operator!=(IpRange other) const; bool FromString(const std::string& range); std::string ToString() const { if (IsInitialized()) { return absl::StrCat(prefix_.ToString(), "/", prefix_length_); } return "(uninitialized)"; } bool IsInitialized() const { return prefix_.IsInitialized(); } QuicIpAddress FirstAddressInRange() const; IpAddressFamily address_family() const { return prefix_.address_family(); } QuicIpAddress prefix() const { return prefix_; } size_t prefix_length() const { return prefix_length_; } private: QuicIpAddress prefix_; size_t prefix_length_; }; } #endif #include "quiche/quic/qbone/platform/ip_range.h" #include <string> #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv4Size = 32; constexpr size_t kIPv6Size = 128; QuicIpAddress TruncateToLength(const QuicIpAddress& input, size_t* prefix_length) { QuicIpAddress output; if (input.IsIPv4()) { if (*prefix_length > kIPv4Size) { *prefix_length = kIPv4Size; return input; } uint32_t raw_address = *reinterpret_cast<const uint32_t*>(input.ToPackedString().data()); raw_address = quiche::QuicheEndian::NetToHost32(raw_address); raw_address &= ~0U << (kIPv4Size - *prefix_length); raw_address = quiche::QuicheEndian::HostToNet32(raw_address); output.FromPackedString(reinterpret_cast<const char*>(&raw_address), sizeof(raw_address)); return output; } if (input.IsIPv6()) { if (*prefix_length > kIPv6Size) { *prefix_length = kIPv6Size; return input; } uint64_t raw_address[2]; memcpy(raw_address, input.ToPackedString().data(), sizeof(raw_address)); raw_address[0] = quiche::QuicheEndian::NetToHost64(raw_address[0]); raw_address[1] = quiche::QuicheEndian::NetToHost64(raw_address[1]); if (*prefix_length <= kIPv6Size / 2) { raw_address[0] &= ~uint64_t{0} << (kIPv6Size / 2 - *prefix_length); raw_address[1] = 0; } else { raw_address[1] &= ~uint64_t{0} << (kIPv6Size - *prefix_length); } raw_address[0] = quiche::QuicheEndian::HostToNet64(raw_address[0]); raw_address[1] = quiche::QuicheEndian::HostToNet64(raw_address[1]); output.FromPackedString(reinterpret_cast<const char*>(raw_address), sizeof(raw_address)); return output; } return output; } } IpRange::IpRange(const QuicIpAddress& prefix, size_t prefix_length) : prefix_(prefix), prefix_length_(prefix_length) { prefix_ = TruncateToLength(prefix_, &prefix_length_); } bool IpRange::operator==(IpRange other) const { return prefix_ == other.prefix_ && prefix_length_ == other.prefix_length_; } bool IpRange::operator!=(IpRange other) const { return !(*this == other); } bool IpRange::FromString(const std::string& range) { size_t slash_pos = range.find('/'); if (slash_pos == std::string::npos) { return false; } QuicIpAddress prefix; bool success = prefix.FromString(range.substr(0, slash_pos)); if (!success) { return false; } uint64_t num_processed = 0; size_t prefix_length = std::stoi(range.substr(slash_pos + 1), &num_processed); if (num_processed + 1 + slash_pos != range.length()) { return false; } prefix_ = TruncateToLength(prefix, &prefix_length); prefix_length_ = prefix_length; return true; } QuicIpAddress IpRange::FirstAddressInRange() const { return prefix(); } }
#include "quiche/quic/qbone/platform/ip_range.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(IpRangeTest, TruncateWorksIPv4) { QuicIpAddress before_truncate; before_truncate.FromString("255.255.255.255"); EXPECT_EQ("128.0.0.0/1", IpRange(before_truncate, 1).ToString()); EXPECT_EQ("192.0.0.0/2", IpRange(before_truncate, 2).ToString()); EXPECT_EQ("255.224.0.0/11", IpRange(before_truncate, 11).ToString()); EXPECT_EQ("255.255.255.224/27", IpRange(before_truncate, 27).ToString()); EXPECT_EQ("255.255.255.254/31", IpRange(before_truncate, 31).ToString()); EXPECT_EQ("255.255.255.255/32", IpRange(before_truncate, 32).ToString()); EXPECT_EQ("255.255.255.255/32", IpRange(before_truncate, 33).ToString()); } TEST(IpRangeTest, TruncateWorksIPv6) { QuicIpAddress before_truncate; before_truncate.FromString("ffff:ffff:ffff:ffff:f903::5"); EXPECT_EQ("fe00::/7", IpRange(before_truncate, 7).ToString()); EXPECT_EQ("ffff:ffff:ffff::/48", IpRange(before_truncate, 48).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff::/64", IpRange(before_truncate, 64).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff:8000::/65", IpRange(before_truncate, 65).ToString()); EXPECT_EQ("ffff:ffff:ffff:ffff:f903::4/127", IpRange(before_truncate, 127).ToString()); } TEST(IpRangeTest, FromStringWorksIPv4) { IpRange range; ASSERT_TRUE(range.FromString("127.0.3.249/26")); EXPECT_EQ("127.0.3.192/26", range.ToString()); } TEST(IpRangeTest, FromStringWorksIPv6) { IpRange range; ASSERT_TRUE(range.FromString("ff01:8f21:77f9::/33")); EXPECT_EQ("ff01:8f21::/33", range.ToString()); } TEST(IpRangeTest, FirstAddressWorksIPv6) { IpRange range; ASSERT_TRUE(range.FromString("ffff:ffff::/64")); QuicIpAddress first_address = range.FirstAddressInRange(); EXPECT_EQ("ffff:ffff::", first_address.ToString()); } TEST(IpRangeTest, FirstAddressWorksIPv4) { IpRange range; ASSERT_TRUE(range.FromString("10.0.0.0/24")); QuicIpAddress first_address = range.FirstAddressInRange(); EXPECT_EQ("10.0.0.0", first_address.ToString()); } } }
218
cpp
google/quiche
rtnetlink_message
quiche/quic/qbone/platform/rtnetlink_message.cc
quiche/quic/qbone/platform/rtnetlink_message_test.cc
#ifndef QUICHE_QUIC_QBONE_PLATFORM_RTNETLINK_MESSAGE_H_ #define QUICHE_QUIC_QBONE_PLATFORM_RTNETLINK_MESSAGE_H_ #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <stdint.h> #include <sys/socket.h> #include <sys/uio.h> #include <memory> #include <vector> #include "quiche/quic/platform/api/quic_logging.h" namespace quic { class RtnetlinkMessage { public: virtual ~RtnetlinkMessage(); enum class Operation { NEW, DEL, GET, }; virtual void AppendAttribute(uint16_t type, const void* data, uint16_t data_length); std::unique_ptr<struct iovec[]> BuildIoVec() const; size_t IoVecSize() const; protected: RtnetlinkMessage(uint16_t type, uint16_t flags, uint32_t seq, uint32_t pid, const void* payload_header, size_t payload_header_length); void AdjustMessageLength(size_t additional_data_length); private: struct nlmsghdr* MessageHeader(); std::vector<struct iovec> message_; }; class LinkMessage : public RtnetlinkMessage { public: static LinkMessage New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifinfomsg* interface_info_header); private: using RtnetlinkMessage::RtnetlinkMessage; }; class AddressMessage : public RtnetlinkMessage { public: static AddressMessage New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifaddrmsg* interface_address_header); private: using RtnetlinkMessage::RtnetlinkMessage; }; class RouteMessage : public RtnetlinkMessage { public: static RouteMessage New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* route_message_header); private: using RtnetlinkMessage::RtnetlinkMessage; }; class RuleMessage : public RtnetlinkMessage { public: static RuleMessage New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* rule_message_header); private: using RtnetlinkMessage::RtnetlinkMessage; }; } #endif #include "quiche/quic/qbone/platform/rtnetlink_message.h" #include <memory> #include <utility> namespace quic { RtnetlinkMessage::RtnetlinkMessage(uint16_t type, uint16_t flags, uint32_t seq, uint32_t pid, const void* payload_header, size_t payload_header_length) { auto* buf = new uint8_t[NLMSG_SPACE(payload_header_length)]; memset(buf, 0, NLMSG_SPACE(payload_header_length)); auto* message_header = reinterpret_cast<struct nlmsghdr*>(buf); message_header->nlmsg_len = NLMSG_LENGTH(payload_header_length); message_header->nlmsg_type = type; message_header->nlmsg_flags = flags; message_header->nlmsg_seq = seq; message_header->nlmsg_pid = pid; if (payload_header != nullptr) { memcpy(NLMSG_DATA(message_header), payload_header, payload_header_length); } message_.push_back({buf, NLMSG_SPACE(payload_header_length)}); } RtnetlinkMessage::~RtnetlinkMessage() { for (const auto& iov : message_) { delete[] reinterpret_cast<uint8_t*>(iov.iov_base); } } void RtnetlinkMessage::AppendAttribute(uint16_t type, const void* data, uint16_t data_length) { auto* buf = new uint8_t[RTA_SPACE(data_length)]; memset(buf, 0, RTA_SPACE(data_length)); auto* rta = reinterpret_cast<struct rtattr*>(buf); static_assert(sizeof(uint16_t) == sizeof(rta->rta_len), "struct rtattr uses unsigned short, it's no longer 16bits"); static_assert(sizeof(uint16_t) == sizeof(rta->rta_type), "struct rtattr uses unsigned short, it's no longer 16bits"); rta->rta_len = RTA_LENGTH(data_length); rta->rta_type = type; memcpy(RTA_DATA(rta), data, data_length); message_.push_back({buf, RTA_SPACE(data_length)}); AdjustMessageLength(rta->rta_len); } std::unique_ptr<struct iovec[]> RtnetlinkMessage::BuildIoVec() const { auto message = std::make_unique<struct iovec[]>(message_.size()); int idx = 0; for (const auto& vec : message_) { message[idx++] = vec; } return message; } size_t RtnetlinkMessage::IoVecSize() const { return message_.size(); } void RtnetlinkMessage::AdjustMessageLength(size_t additional_data_length) { MessageHeader()->nlmsg_len = NLMSG_ALIGN(MessageHeader()->nlmsg_len) + additional_data_length; } struct nlmsghdr* RtnetlinkMessage::MessageHeader() { return reinterpret_cast<struct nlmsghdr*>(message_[0].iov_base); } LinkMessage LinkMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifinfomsg* interface_info_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWLINK; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELLINK; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETLINK; break; } bool is_get = request_type == RTM_GETLINK; if (is_get) { struct rtgenmsg g = {AF_UNSPEC}; return LinkMessage(request_type, flags, seq, pid, &g, sizeof(g)); } return LinkMessage(request_type, flags, seq, pid, interface_info_header, sizeof(struct ifinfomsg)); } AddressMessage AddressMessage::New( RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct ifaddrmsg* interface_address_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWADDR; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELADDR; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETADDR; break; } bool is_get = request_type == RTM_GETADDR; if (is_get) { struct rtgenmsg g = {AF_UNSPEC}; return AddressMessage(request_type, flags, seq, pid, &g, sizeof(g)); } return AddressMessage(request_type, flags, seq, pid, interface_address_header, sizeof(struct ifaddrmsg)); } RouteMessage RouteMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* route_message_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWROUTE; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELROUTE; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETROUTE; break; } return RouteMessage(request_type, flags, seq, pid, route_message_header, sizeof(struct rtmsg)); } RuleMessage RuleMessage::New(RtnetlinkMessage::Operation request_operation, uint16_t flags, uint32_t seq, uint32_t pid, const struct rtmsg* rule_message_header) { uint16_t request_type; switch (request_operation) { case RtnetlinkMessage::Operation::NEW: request_type = RTM_NEWRULE; break; case RtnetlinkMessage::Operation::DEL: request_type = RTM_DELRULE; break; case RtnetlinkMessage::Operation::GET: request_type = RTM_GETRULE; break; } return RuleMessage(request_type, flags, seq, pid, rule_message_header, sizeof(rtmsg)); } }
#include "quiche/quic/qbone/platform/rtnetlink_message.h" #include <net/if_arp.h> #include <string> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { using ::testing::StrEq; TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForGetOperation) { uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = LinkMessage::New(RtnetlinkMessage::Operation::GET, flags, seq, pid, nullptr); EXPECT_EQ(1, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); EXPECT_EQ(RTM_GETLINK, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); } TEST(RtnetlinkMessageTest, LinkMessageCanBeCreatedForNewOperation) { struct ifinfomsg interface_info_header = {AF_INET, 0, ARPHRD_TUNNEL, 3, 0, 0xffffffff}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = LinkMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &interface_info_header); std::string device_name = "device0"; message.AppendAttribute(IFLA_IFNAME, device_name.c_str(), device_name.size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifinfomsg))) + RTA_LENGTH(device_name.size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWLINK, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct ifinfomsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(interface_info_header.ifi_family, parsed_header->ifi_family); EXPECT_EQ(interface_info_header.ifi_type, parsed_header->ifi_type); EXPECT_EQ(interface_info_header.ifi_index, parsed_header->ifi_index); EXPECT_EQ(interface_info_header.ifi_flags, parsed_header->ifi_flags); EXPECT_EQ(interface_info_header.ifi_change, parsed_header->ifi_change); EXPECT_EQ(RTA_SPACE(device_name.size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(IFLA_IFNAME, rta->rta_type); EXPECT_EQ(RTA_LENGTH(device_name.size()), rta->rta_len); EXPECT_THAT(device_name, StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForGetOperation) { uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = AddressMessage::New(RtnetlinkMessage::Operation::GET, flags, seq, pid, nullptr); EXPECT_EQ(1, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_SPACE(sizeof(struct rtgenmsg)), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); EXPECT_EQ(RTM_GETADDR, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); EXPECT_EQ(NLMSG_LENGTH(sizeof(struct rtgenmsg)), netlink_message->nlmsg_len); } TEST(RtnetlinkMessageTest, AddressMessageCanBeCreatedForNewOperation) { struct ifaddrmsg interface_address_header = {AF_INET, 24, 0, RT_SCOPE_LINK, 4}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = AddressMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &interface_address_header); QuicIpAddress ip; QUICHE_CHECK(ip.FromString("10.0.100.3")); message.AppendAttribute(IFA_ADDRESS, ip.ToPackedString().c_str(), ip.ToPackedString().size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct ifaddrmsg))) + RTA_LENGTH(ip.ToPackedString().size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWADDR, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct ifaddrmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(interface_address_header.ifa_family, parsed_header->ifa_family); EXPECT_EQ(interface_address_header.ifa_prefixlen, parsed_header->ifa_prefixlen); EXPECT_EQ(interface_address_header.ifa_flags, parsed_header->ifa_flags); EXPECT_EQ(interface_address_header.ifa_scope, parsed_header->ifa_scope); EXPECT_EQ(interface_address_header.ifa_index, parsed_header->ifa_index); EXPECT_EQ(RTA_SPACE(ip.ToPackedString().size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(IFA_ADDRESS, rta->rta_type); EXPECT_EQ(RTA_LENGTH(ip.ToPackedString().size()), rta->rta_len); EXPECT_THAT(ip.ToPackedString(), StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } TEST(RtnetlinkMessageTest, RouteMessageCanBeCreatedFromNewOperation) { struct rtmsg route_message_header = {AF_INET6, 48, 0, 0, RT_TABLE_MAIN, RTPROT_STATIC, RT_SCOPE_LINK, RTN_LOCAL, 0}; uint16_t flags = NLM_F_REQUEST | NLM_F_ROOT | NLM_F_MATCH; uint32_t seq = 42; uint32_t pid = 7; auto message = RouteMessage::New(RtnetlinkMessage::Operation::NEW, flags, seq, pid, &route_message_header); QuicIpAddress preferred_source; QUICHE_CHECK(preferred_source.FromString("ff80::1")); message.AppendAttribute(RTA_PREFSRC, preferred_source.ToPackedString().c_str(), preferred_source.ToPackedString().size()); EXPECT_EQ(2, message.IoVecSize()); auto iov = message.BuildIoVec(); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))), iov[0].iov_len); auto* netlink_message = reinterpret_cast<struct nlmsghdr*>(iov[0].iov_base); EXPECT_EQ(NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct rtmsg))) + RTA_LENGTH(preferred_source.ToPackedString().size()), netlink_message->nlmsg_len); EXPECT_EQ(RTM_NEWROUTE, netlink_message->nlmsg_type); EXPECT_EQ(flags, netlink_message->nlmsg_flags); EXPECT_EQ(seq, netlink_message->nlmsg_seq); EXPECT_EQ(pid, netlink_message->nlmsg_pid); auto* parsed_header = reinterpret_cast<struct rtmsg*>(NLMSG_DATA(netlink_message)); EXPECT_EQ(route_message_header.rtm_family, parsed_header->rtm_family); EXPECT_EQ(route_message_header.rtm_dst_len, parsed_header->rtm_dst_len); EXPECT_EQ(route_message_header.rtm_src_len, parsed_header->rtm_src_len); EXPECT_EQ(route_message_header.rtm_tos, parsed_header->rtm_tos); EXPECT_EQ(route_message_header.rtm_table, parsed_header->rtm_table); EXPECT_EQ(route_message_header.rtm_protocol, parsed_header->rtm_protocol); EXPECT_EQ(route_message_header.rtm_scope, parsed_header->rtm_scope); EXPECT_EQ(route_message_header.rtm_type, parsed_header->rtm_type); EXPECT_EQ(route_message_header.rtm_flags, parsed_header->rtm_flags); EXPECT_EQ(RTA_SPACE(preferred_source.ToPackedString().size()), iov[1].iov_len); auto* rta = reinterpret_cast<struct rtattr*>(iov[1].iov_base); EXPECT_EQ(RTA_PREFSRC, rta->rta_type); EXPECT_EQ(RTA_LENGTH(preferred_source.ToPackedString().size()), rta->rta_len); EXPECT_THAT(preferred_source.ToPackedString(), StrEq(std::string(reinterpret_cast<char*>(RTA_DATA(rta)), RTA_PAYLOAD(rta)))); } } }
219
cpp
google/quiche
icmp_packet
quiche/quic/qbone/platform/icmp_packet.cc
quiche/quic/qbone/platform/icmp_packet_test.cc
#ifndef QUICHE_QUIC_QBONE_PLATFORM_ICMP_PACKET_H_ #define QUICHE_QUIC_QBONE_PLATFORM_ICMP_PACKET_H_ #include <netinet/icmp6.h> #include <netinet/in.h> #include <functional> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/common/quiche_callbacks.h" namespace quic { void CreateIcmpPacket(in6_addr src, in6_addr dst, const icmp6_hdr& icmp_header, absl::string_view body, quiche::UnretainedCallback<void(absl::string_view)> cb); } #endif #include "quiche/quic/qbone/platform/icmp_packet.h" #include <netinet/ip6.h> #include <algorithm> #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv6AddressSize = sizeof(in6_addr); constexpr size_t kIPv6HeaderSize = sizeof(ip6_hdr); constexpr size_t kICMPv6HeaderSize = sizeof(icmp6_hdr); constexpr size_t kIPv6MinPacketSize = 1280; constexpr size_t kIcmpTtl = 255; constexpr size_t kICMPv6BodyMaxSize = kIPv6MinPacketSize - kIPv6HeaderSize - kICMPv6HeaderSize; struct ICMPv6Packet { ip6_hdr ip_header; icmp6_hdr icmp_header; uint8_t body[kICMPv6BodyMaxSize]; }; struct IPv6PseudoHeader { uint32_t payload_size{}; uint8_t zeros[3] = {0, 0, 0}; uint8_t next_header = IPPROTO_ICMPV6; }; } void CreateIcmpPacket(in6_addr src, in6_addr dst, const icmp6_hdr& icmp_header, absl::string_view body, quiche::UnretainedCallback<void(absl::string_view)> cb) { const size_t body_size = std::min(body.size(), kICMPv6BodyMaxSize); const size_t payload_size = kICMPv6HeaderSize + body_size; ICMPv6Packet icmp_packet{}; icmp_packet.ip_header.ip6_vfc = 0x6 << 4; icmp_packet.ip_header.ip6_plen = quiche::QuicheEndian::HostToNet16(payload_size); icmp_packet.ip_header.ip6_nxt = IPPROTO_ICMPV6; icmp_packet.ip_header.ip6_hops = kIcmpTtl; icmp_packet.ip_header.ip6_src = src; icmp_packet.ip_header.ip6_dst = dst; icmp_packet.icmp_header = icmp_header; icmp_packet.icmp_header.icmp6_cksum = 0; IPv6PseudoHeader pseudo_header{}; pseudo_header.payload_size = quiche::QuicheEndian::HostToNet32(payload_size); InternetChecksum checksum; checksum.Update(icmp_packet.ip_header.ip6_src.s6_addr, kIPv6AddressSize); checksum.Update(icmp_packet.ip_header.ip6_dst.s6_addr, kIPv6AddressSize); checksum.Update(reinterpret_cast<char*>(&pseudo_header), sizeof(pseudo_header)); checksum.Update(reinterpret_cast<const char*>(&icmp_packet.icmp_header), sizeof(icmp_packet.icmp_header)); checksum.Update(body.data(), body_size); icmp_packet.icmp_header.icmp6_cksum = checksum.Value(); memcpy(icmp_packet.body, body.data(), body_size); const char* packet = reinterpret_cast<char*>(&icmp_packet); const size_t packet_size = offsetof(ICMPv6Packet, body) + body_size; cb(absl::string_view(packet, packet_size)); } }
#include "quiche/quic/qbone/platform/icmp_packet.h" #include <netinet/ip6.h> #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr char kReferenceSourceAddress[] = "fe80:1:2:3:4::1"; constexpr char kReferenceDestinationAddress[] = "fe80:4:3:2:1::1"; constexpr uint8_t kReferenceICMPMessageBody[] { 0xd2, 0x61, 0x29, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x59, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; constexpr uint8_t kReferenceICMPPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x40, 0x3a, 0xFF, 0xfe, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x04, 0x00, 0x03, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0xec, 0x00, 0xcb, 0x82, 0x00, 0x01, 0xd2, 0x61, 0x29, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x59, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; } TEST(IcmpPacketTest, CreatedPacketMatchesReference) { QuicIpAddress src; ASSERT_TRUE(src.FromString(kReferenceSourceAddress)); in6_addr src_addr; memcpy(src_addr.s6_addr, src.ToPackedString().data(), sizeof(in6_addr)); QuicIpAddress dst; ASSERT_TRUE(dst.FromString(kReferenceDestinationAddress)); in6_addr dst_addr; memcpy(dst_addr.s6_addr, dst.ToPackedString().data(), sizeof(in6_addr)); icmp6_hdr icmp_header{}; icmp_header.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header.icmp6_id = 0x82cb; icmp_header.icmp6_seq = 0x0100; absl::string_view message_body = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPMessageBody), 56); absl::string_view expected_packet = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPPacket), 104); CreateIcmpPacket(src_addr, dst_addr, icmp_header, message_body, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } TEST(IcmpPacketTest, NonZeroChecksumIsIgnored) { QuicIpAddress src; ASSERT_TRUE(src.FromString(kReferenceSourceAddress)); in6_addr src_addr; memcpy(src_addr.s6_addr, src.ToPackedString().data(), sizeof(in6_addr)); QuicIpAddress dst; ASSERT_TRUE(dst.FromString(kReferenceDestinationAddress)); in6_addr dst_addr; memcpy(dst_addr.s6_addr, dst.ToPackedString().data(), sizeof(in6_addr)); icmp6_hdr icmp_header{}; icmp_header.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header.icmp6_id = 0x82cb; icmp_header.icmp6_seq = 0x0100; icmp_header.icmp6_cksum = 0x1234; absl::string_view message_body = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPMessageBody), 56); absl::string_view expected_packet = absl::string_view( reinterpret_cast<const char*>(kReferenceICMPPacket), 104); CreateIcmpPacket(src_addr, dst_addr, icmp_header, message_body, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } }
220
cpp
google/quiche
tcp_packet
quiche/quic/qbone/platform/tcp_packet.cc
quiche/quic/qbone/platform/tcp_packet_test.cc
#ifndef QUICHE_QUIC_QBONE_PLATFORM_TCP_PACKET_H_ #define QUICHE_QUIC_QBONE_PLATFORM_TCP_PACKET_H_ #include <netinet/in.h> #include <netinet/tcp.h> #include <functional> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/common/quiche_callbacks.h" namespace quic { void CreateTcpResetPacket( absl::string_view original_packet, quiche::UnretainedCallback<void(absl::string_view)> cb); } #endif #include "quiche/quic/qbone/platform/tcp_packet.h" #include <netinet/ip6.h> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { constexpr size_t kIPv6AddressSize = sizeof(in6_addr); constexpr size_t kTcpTtl = 64; struct TCPv6Packet { ip6_hdr ip_header; tcphdr tcp_header; }; struct TCPv6PseudoHeader { uint32_t payload_size{}; uint8_t zeros[3] = {0, 0, 0}; uint8_t next_header = IPPROTO_TCP; }; } void CreateTcpResetPacket( absl::string_view original_packet, quiche::UnretainedCallback<void(absl::string_view)> cb) { if (ABSL_PREDICT_FALSE(original_packet.size() < sizeof(ip6_hdr))) { return; } auto* ip6_header = reinterpret_cast<const ip6_hdr*>(original_packet.data()); if (ABSL_PREDICT_FALSE(ip6_header->ip6_vfc >> 4 != 6)) { return; } if (ABSL_PREDICT_FALSE(ip6_header->ip6_nxt != IPPROTO_TCP)) { return; } if (ABSL_PREDICT_FALSE(quiche::QuicheEndian::NetToHost16( ip6_header->ip6_plen) < sizeof(tcphdr))) { return; } auto* tcp_header = reinterpret_cast<const tcphdr*>(ip6_header + 1); TCPv6Packet tcp_packet{}; const size_t payload_size = sizeof(tcphdr); tcp_packet.ip_header.ip6_vfc = 0x6 << 4; tcp_packet.ip_header.ip6_plen = quiche::QuicheEndian::HostToNet16(payload_size); tcp_packet.ip_header.ip6_nxt = IPPROTO_TCP; tcp_packet.ip_header.ip6_hops = kTcpTtl; tcp_packet.ip_header.ip6_src = ip6_header->ip6_dst; tcp_packet.ip_header.ip6_dst = ip6_header->ip6_src; tcp_packet.tcp_header.dest = tcp_header->source; tcp_packet.tcp_header.source = tcp_header->dest; tcp_packet.tcp_header.doff = sizeof(tcphdr) >> 2; tcp_packet.tcp_header.check = 0; tcp_packet.tcp_header.rst = 1; if (tcp_header->ack) { tcp_packet.tcp_header.seq = tcp_header->ack_seq; } else { tcp_packet.tcp_header.ack = 1; tcp_packet.tcp_header.seq = 0; tcp_packet.tcp_header.ack_seq = quiche::QuicheEndian::HostToNet32( quiche::QuicheEndian::NetToHost32(tcp_header->seq) + 1); } TCPv6PseudoHeader pseudo_header{}; pseudo_header.payload_size = quiche::QuicheEndian::HostToNet32(payload_size); InternetChecksum checksum; checksum.Update(tcp_packet.ip_header.ip6_src.s6_addr, kIPv6AddressSize); checksum.Update(tcp_packet.ip_header.ip6_dst.s6_addr, kIPv6AddressSize); checksum.Update(reinterpret_cast<char*>(&pseudo_header), sizeof(pseudo_header)); checksum.Update(reinterpret_cast<const char*>(&tcp_packet.tcp_header), sizeof(tcp_packet.tcp_header)); tcp_packet.tcp_header.check = checksum.Value(); const char* packet = reinterpret_cast<char*>(&tcp_packet); cb(absl::string_view(packet, sizeof(tcp_packet))); } }
#include "quiche/quic/qbone/platform/tcp_packet.h" #include <netinet/ip6.h> #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr uint8_t kReferenceTCPSYNPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x28, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xac, 0x1e, 0x27, 0x0f, 0x4b, 0x01, 0xe8, 0x99, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x02, 0xaa, 0xaa, 0x2e, 0x21, 0x00, 0x00, 0x02, 0x04, 0xff, 0xc4, 0x04, 0x02, 0x08, 0x0a, 0x1b, 0xb8, 0x52, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07, }; constexpr uint8_t kReferenceTCPRSTPacket[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x27, 0x0f, 0xac, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x4b, 0x01, 0xe8, 0x9a, 0x50, 0x14, 0x00, 0x00, 0xa9, 0x05, 0x00, 0x00, }; } TEST(TcpPacketTest, CreatedPacketMatchesReference) { absl::string_view syn = absl::string_view(reinterpret_cast<const char*>(kReferenceTCPSYNPacket), sizeof(kReferenceTCPSYNPacket)); absl::string_view expected_packet = absl::string_view(reinterpret_cast<const char*>(kReferenceTCPRSTPacket), sizeof(kReferenceTCPRSTPacket)); CreateTcpResetPacket(syn, [&expected_packet](absl::string_view packet) { QUIC_LOG(INFO) << quiche::QuicheTextUtils::HexDump(packet); ASSERT_EQ(packet, expected_packet); }); } }
221
cpp
google/quiche
tun_device_packet_exchanger
quiche/quic/qbone/bonnet/tun_device_packet_exchanger.cc
quiche/quic/qbone/bonnet/tun_device_packet_exchanger_test.cc
#ifndef QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_PACKET_EXCHANGER_H_ #define QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_PACKET_EXCHANGER_H_ #include <linux/if_ether.h> #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/qbone/platform/kernel_interface.h" #include "quiche/quic/qbone/platform/netlink_interface.h" #include "quiche/quic/qbone/qbone_client_interface.h" #include "quiche/quic/qbone/qbone_packet_exchanger.h" namespace quic { class TunDevicePacketExchanger : public QbonePacketExchanger { public: class StatsInterface { public: StatsInterface() = default; StatsInterface(const StatsInterface&) = delete; StatsInterface& operator=(const StatsInterface&) = delete; StatsInterface(StatsInterface&&) = delete; StatsInterface& operator=(StatsInterface&&) = delete; virtual ~StatsInterface() = default; virtual void OnPacketRead(size_t count) = 0; virtual void OnPacketWritten(size_t count) = 0; virtual void OnReadError(std::string* error) = 0; virtual void OnWriteError(std::string* error) = 0; ABSL_MUST_USE_RESULT virtual int64_t PacketsRead() const = 0; ABSL_MUST_USE_RESULT virtual int64_t PacketsWritten() const = 0; }; TunDevicePacketExchanger(size_t mtu, KernelInterface* kernel, NetlinkInterface* netlink, QbonePacketExchanger::Visitor* visitor, size_t max_pending_packets, bool is_tap, StatsInterface* stats, absl::string_view ifname); void set_file_descriptor(int fd); ABSL_MUST_USE_RESULT const StatsInterface* stats_interface() const; private: std::unique_ptr<QuicData> ReadPacket(bool* blocked, std::string* error) override; bool WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) override; std::unique_ptr<QuicData> ApplyL2Headers(const QuicData& l3_packet); std::unique_ptr<QuicData> ConsumeL2Headers(const QuicData& l2_packet); int fd_ = -1; size_t mtu_; KernelInterface* kernel_; NetlinkInterface* netlink_; const std::string ifname_; const bool is_tap_; uint8_t tap_mac_[ETH_ALEN]{}; bool mac_initialized_ = false; StatsInterface* stats_; }; } #endif #include "quiche/quic/qbone/bonnet/tun_device_packet_exchanger.h" #include <netinet/icmp6.h> #include <netinet/ip6.h> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/quic/qbone/platform/netlink_interface.h" #include "quiche/quic/qbone/qbone_constants.h" namespace quic { TunDevicePacketExchanger::TunDevicePacketExchanger( size_t mtu, KernelInterface* kernel, NetlinkInterface* netlink, QbonePacketExchanger::Visitor* visitor, size_t max_pending_packets, bool is_tap, StatsInterface* stats, absl::string_view ifname) : QbonePacketExchanger(visitor, max_pending_packets), mtu_(mtu), kernel_(kernel), netlink_(netlink), ifname_(ifname), is_tap_(is_tap), stats_(stats) { if (is_tap_) { mtu_ += ETH_HLEN; } } bool TunDevicePacketExchanger::WritePacket(const char* packet, size_t size, bool* blocked, std::string* error) { *blocked = false; if (fd_ < 0) { *error = absl::StrCat("Invalid file descriptor of the TUN device: ", fd_); stats_->OnWriteError(error); return false; } auto buffer = std::make_unique<QuicData>(packet, size); if (is_tap_) { buffer = ApplyL2Headers(*buffer); } int result = kernel_->write(fd_, buffer->data(), buffer->length()); if (result == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) { *error = absl::StrCat("Write to the TUN device was blocked: ", errno); *blocked = true; stats_->OnWriteError(error); } return false; } stats_->OnPacketWritten(result); return true; } std::unique_ptr<QuicData> TunDevicePacketExchanger::ReadPacket( bool* blocked, std::string* error) { *blocked = false; if (fd_ < 0) { *error = absl::StrCat("Invalid file descriptor of the TUN device: ", fd_); stats_->OnReadError(error); return nullptr; } auto read_buffer = std::make_unique<char[]>(mtu_); int result = kernel_->read(fd_, read_buffer.get(), mtu_); if (result <= 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { *error = absl::StrCat("Read from the TUN device was blocked: ", errno); *blocked = true; stats_->OnReadError(error); } return nullptr; } auto buffer = std::make_unique<QuicData>(read_buffer.release(), result, true); if (is_tap_) { buffer = ConsumeL2Headers(*buffer); } if (buffer) { stats_->OnPacketRead(buffer->length()); } return buffer; } void TunDevicePacketExchanger::set_file_descriptor(int fd) { fd_ = fd; } const TunDevicePacketExchanger::StatsInterface* TunDevicePacketExchanger::stats_interface() const { return stats_; } std::unique_ptr<QuicData> TunDevicePacketExchanger::ApplyL2Headers( const QuicData& l3_packet) { if (is_tap_ && !mac_initialized_) { NetlinkInterface::LinkInfo link_info{}; if (netlink_->GetLinkInfo(ifname_, &link_info)) { memcpy(tap_mac_, link_info.hardware_address, ETH_ALEN); mac_initialized_ = true; } else { QUIC_LOG_EVERY_N_SEC(ERROR, 30) << "Unable to get link info for: " << ifname_; } } const auto l2_packet_size = l3_packet.length() + ETH_HLEN; auto l2_buffer = std::make_unique<char[]>(l2_packet_size); auto* hdr = reinterpret_cast<ethhdr*>(l2_buffer.get()); memcpy(hdr->h_dest, tap_mac_, ETH_ALEN); memcpy(hdr->h_source, tap_mac_, ETH_ALEN); hdr->h_proto = absl::ghtons(ETH_P_IPV6); memcpy(l2_buffer.get() + ETH_HLEN, l3_packet.data(), l3_packet.length()); return std::make_unique<QuicData>(l2_buffer.release(), l2_packet_size, true); } std::unique_ptr<QuicData> TunDevicePacketExchanger::ConsumeL2Headers( const QuicData& l2_packet) { if (l2_packet.length() < ETH_HLEN) { return nullptr; } auto* hdr = reinterpret_cast<const ethhdr*>(l2_packet.data()); if (hdr->h_proto != absl::ghtons(ETH_P_IPV6)) { return nullptr; } constexpr auto kIp6PrefixLen = ETH_HLEN + sizeof(ip6_hdr); constexpr auto kIcmp6PrefixLen = kIp6PrefixLen + sizeof(icmp6_hdr); if (l2_packet.length() < kIp6PrefixLen) { return nullptr; } auto* ip_hdr = reinterpret_cast<const ip6_hdr*>(l2_packet.data() + ETH_HLEN); const bool is_icmp = ip_hdr->ip6_ctlun.ip6_un1.ip6_un1_nxt == IPPROTO_ICMPV6; bool is_neighbor_solicit = false; if (is_icmp) { if (l2_packet.length() < kIcmp6PrefixLen) { return nullptr; } is_neighbor_solicit = reinterpret_cast<const icmp6_hdr*>(l2_packet.data() + kIp6PrefixLen) ->icmp6_type == ND_NEIGHBOR_SOLICIT; } if (is_neighbor_solicit) { auto* icmp6_payload = l2_packet.data() + kIcmp6PrefixLen; QuicIpAddress target_address( *reinterpret_cast<const in6_addr*>(icmp6_payload)); if (target_address != *QboneConstants::GatewayAddress()) { return nullptr; } constexpr size_t kIcmpv6OptionSize = 8; const int payload_size = sizeof(in6_addr) + kIcmpv6OptionSize; auto payload = std::make_unique<char[]>(payload_size); memcpy(payload.get(), icmp6_payload, sizeof(in6_addr)); int pos = sizeof(in6_addr); payload[pos++] = ND_OPT_TARGET_LINKADDR; payload[pos++] = 1; memcpy(&payload[pos], tap_mac_, ETH_ALEN); icmp6_hdr response_hdr{}; response_hdr.icmp6_type = ND_NEIGHBOR_ADVERT; response_hdr.icmp6_dataun.icmp6_un_data8[0] = 64; CreateIcmpPacket(ip_hdr->ip6_src, ip_hdr->ip6_src, response_hdr, absl::string_view(payload.get(), payload_size), [this](absl::string_view packet) { bool blocked; std::string error; WritePacket(packet.data(), packet.size(), &blocked, &error); }); return nullptr; } const auto l3_packet_size = l2_packet.length() - ETH_HLEN; auto shift_buffer = std::make_unique<char[]>(l3_packet_size); memcpy(shift_buffer.get(), l2_packet.data() + ETH_HLEN, l3_packet_size); return std::make_unique<QuicData>(shift_buffer.release(), l3_packet_size, true); } }
#include "quiche/quic/qbone/bonnet/tun_device_packet_exchanger.h" #include <string> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/bonnet/mock_packet_exchanger_stats_interface.h" #include "quiche/quic/qbone/mock_qbone_client.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { const size_t kMtu = 1000; const size_t kMaxPendingPackets = 5; const int kFd = 15; using ::testing::_; using ::testing::Invoke; using ::testing::StrEq; using ::testing::StrictMock; class MockVisitor : public QbonePacketExchanger::Visitor { public: MOCK_METHOD(void, OnReadError, (const std::string&), (override)); MOCK_METHOD(void, OnWriteError, (const std::string&), (override)); }; class TunDevicePacketExchangerTest : public QuicTest { protected: TunDevicePacketExchangerTest() : exchanger_(kMtu, &mock_kernel_, nullptr, &mock_visitor_, kMaxPendingPackets, false, &mock_stats_, absl::string_view()) { exchanger_.set_file_descriptor(kFd); } ~TunDevicePacketExchangerTest() override = default; MockKernel mock_kernel_; StrictMock<MockVisitor> mock_visitor_; StrictMock<MockQboneClient> mock_client_; StrictMock<MockPacketExchangerStatsInterface> mock_stats_; TunDevicePacketExchanger exchanger_; }; TEST_F(TunDevicePacketExchangerTest, WritePacketReturnsFalseOnError) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([](int fd, const void* buf, size_t count) { errno = ECOMM; return -1; })); EXPECT_CALL(mock_visitor_, OnWriteError(_)); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, WritePacketReturnFalseAndBlockedOnBlockedTunnel) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([](int fd, const void* buf, size_t count) { errno = EAGAIN; return -1; })); EXPECT_CALL(mock_stats_, OnWriteError(_)).Times(1); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, WritePacketReturnsTrueOnSuccessfulWrite) { std::string packet = "fake packet"; EXPECT_CALL(mock_kernel_, write(kFd, _, packet.size())) .WillOnce(Invoke([packet](int fd, const void* buf, size_t count) { EXPECT_THAT(reinterpret_cast<const char*>(buf), StrEq(packet)); return count; })); EXPECT_CALL(mock_stats_, OnPacketWritten(_)).Times(1); exchanger_.WritePacketToNetwork(packet.data(), packet.size()); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsNullOnError) { EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([](int fd, void* buf, size_t count) { errno = ECOMM; return -1; })); EXPECT_CALL(mock_visitor_, OnReadError(_)); exchanger_.ReadAndDeliverPacket(&mock_client_); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsNullOnBlockedRead) { EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([](int fd, void* buf, size_t count) { errno = EAGAIN; return -1; })); EXPECT_CALL(mock_stats_, OnReadError(_)).Times(1); EXPECT_FALSE(exchanger_.ReadAndDeliverPacket(&mock_client_)); } TEST_F(TunDevicePacketExchangerTest, ReadPacketReturnsThePacketOnSuccessfulRead) { std::string packet = "fake_packet"; EXPECT_CALL(mock_kernel_, read(kFd, _, kMtu)) .WillOnce(Invoke([packet](int fd, void* buf, size_t count) { memcpy(buf, packet.data(), packet.size()); return packet.size(); })); EXPECT_CALL(mock_client_, ProcessPacketFromNetwork(StrEq(packet))); EXPECT_CALL(mock_stats_, OnPacketRead(_)).Times(1); EXPECT_TRUE(exchanger_.ReadAndDeliverPacket(&mock_client_)); } } }
222
cpp
google/quiche
icmp_reachable
quiche/quic/qbone/bonnet/icmp_reachable.cc
quiche/quic/qbone/bonnet/icmp_reachable_test.cc
#ifndef QUICHE_QUIC_QBONE_BONNET_ICMP_REACHABLE_H_ #define QUICHE_QUIC_QBONE_BONNET_ICMP_REACHABLE_H_ #include <netinet/icmp6.h> #include <memory> #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/qbone/bonnet/icmp_reachable_interface.h" #include "quiche/quic/qbone/platform/kernel_interface.h" namespace quic { extern const char kUnknownSource[]; extern const char kNoSource[]; class IcmpReachable : public IcmpReachableInterface { public: enum Status { REACHABLE, UNREACHABLE }; struct ReachableEvent { Status status; QuicTime::Delta response_time; std::string source; }; class StatsInterface { public: StatsInterface() = default; StatsInterface(const StatsInterface&) = delete; StatsInterface& operator=(const StatsInterface&) = delete; StatsInterface(StatsInterface&&) = delete; StatsInterface& operator=(StatsInterface&&) = delete; virtual ~StatsInterface() = default; virtual void OnEvent(ReachableEvent event) = 0; virtual void OnReadError(int error) = 0; virtual void OnWriteError(int error) = 0; }; IcmpReachable(QuicIpAddress source, QuicIpAddress destination, QuicTime::Delta timeout, KernelInterface* kernel, QuicEventLoop* event_loop, StatsInterface* stats); ~IcmpReachable() override; bool Init() QUIC_LOCKS_EXCLUDED(header_lock_) override; void OnAlarm() QUIC_LOCKS_EXCLUDED(header_lock_); static absl::string_view StatusName(Status status); private: class EpollCallback : public QuicSocketEventListener { public: explicit EpollCallback(IcmpReachable* reachable) : reachable_(reachable) {} EpollCallback(const EpollCallback&) = delete; EpollCallback& operator=(const EpollCallback&) = delete; EpollCallback(EpollCallback&&) = delete; EpollCallback& operator=(EpollCallback&&) = delete; void OnSocketEvent(QuicEventLoop* event_loop, SocketFd fd, QuicSocketEventMask events) override; private: IcmpReachable* reachable_; }; class AlarmCallback : public QuicAlarm::DelegateWithoutContext { public: explicit AlarmCallback(IcmpReachable* reachable) : reachable_(reachable) {} void OnAlarm() override { reachable_->OnAlarm(); } private: IcmpReachable* reachable_; }; bool OnEvent(int fd) QUIC_LOCKS_EXCLUDED(header_lock_); const QuicTime::Delta timeout_; QuicEventLoop* event_loop_; const QuicClock* clock_; std::unique_ptr<QuicAlarmFactory> alarm_factory_; EpollCallback cb_; std::unique_ptr<QuicAlarm> alarm_; sockaddr_in6 src_{}; sockaddr_in6 dst_{}; KernelInterface* kernel_; StatsInterface* stats_; int send_fd_; int recv_fd_; QuicMutex header_lock_; icmp6_hdr icmp_header_ QUIC_GUARDED_BY(header_lock_){}; QuicTime start_ = QuicTime::Zero(); QuicTime end_ = QuicTime::Zero(); }; } #endif #include "quiche/quic/qbone/bonnet/icmp_reachable.h" #include <netinet/ip6.h> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/qbone/platform/icmp_packet.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr QuicSocketEventMask kEventMask = kSocketEventReadable | kSocketEventWritable; constexpr size_t kMtu = 1280; constexpr size_t kIPv6AddrSize = sizeof(in6_addr); } const char kUnknownSource[] = "UNKNOWN"; const char kNoSource[] = "N/A"; IcmpReachable::IcmpReachable(QuicIpAddress source, QuicIpAddress destination, QuicTime::Delta timeout, KernelInterface* kernel, QuicEventLoop* event_loop, StatsInterface* stats) : timeout_(timeout), event_loop_(event_loop), clock_(event_loop->GetClock()), alarm_factory_(event_loop->CreateAlarmFactory()), cb_(this), alarm_(alarm_factory_->CreateAlarm(new AlarmCallback(this))), kernel_(kernel), stats_(stats), send_fd_(0), recv_fd_(0) { src_.sin6_family = AF_INET6; dst_.sin6_family = AF_INET6; memcpy(&src_.sin6_addr, source.ToPackedString().data(), kIPv6AddrSize); memcpy(&dst_.sin6_addr, destination.ToPackedString().data(), kIPv6AddrSize); } IcmpReachable::~IcmpReachable() { if (send_fd_ > 0) { kernel_->close(send_fd_); } if (recv_fd_ > 0) { bool success = event_loop_->UnregisterSocket(recv_fd_); QUICHE_DCHECK(success); kernel_->close(recv_fd_); } } bool IcmpReachable::Init() { send_fd_ = kernel_->socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_RAW); if (send_fd_ < 0) { QUIC_LOG(ERROR) << "Unable to open socket: " << errno; return false; } if (kernel_->bind(send_fd_, reinterpret_cast<struct sockaddr*>(&src_), sizeof(sockaddr_in6)) < 0) { QUIC_LOG(ERROR) << "Unable to bind socket: " << errno; return false; } recv_fd_ = kernel_->socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_ICMPV6); if (recv_fd_ < 0) { QUIC_LOG(ERROR) << "Unable to open socket: " << errno; return false; } if (kernel_->bind(recv_fd_, reinterpret_cast<struct sockaddr*>(&src_), sizeof(sockaddr_in6)) < 0) { QUIC_LOG(ERROR) << "Unable to bind socket: " << errno; return false; } icmp6_filter filter; ICMP6_FILTER_SETBLOCKALL(&filter); ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filter); if (kernel_->setsockopt(recv_fd_, SOL_ICMPV6, ICMP6_FILTER, &filter, sizeof(filter)) < 0) { QUIC_LOG(ERROR) << "Unable to set ICMP6 filter."; return false; } if (!event_loop_->RegisterSocket(recv_fd_, kEventMask, &cb_)) { QUIC_LOG(ERROR) << "Unable to register recv ICMP socket"; return false; } alarm_->Set(clock_->Now()); QuicWriterMutexLock mu(&header_lock_); icmp_header_.icmp6_type = ICMP6_ECHO_REQUEST; icmp_header_.icmp6_code = 0; QuicRandom::GetInstance()->RandBytes(&icmp_header_.icmp6_id, sizeof(uint16_t)); return true; } bool IcmpReachable::OnEvent(int fd) { char buffer[kMtu]; sockaddr_in6 source_addr{}; socklen_t source_addr_len = sizeof(source_addr); ssize_t size = kernel_->recvfrom(fd, &buffer, kMtu, 0, reinterpret_cast<sockaddr*>(&source_addr), &source_addr_len); if (size < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { stats_->OnReadError(errno); } return false; } QUIC_VLOG(2) << quiche::QuicheTextUtils::HexDump( absl::string_view(buffer, size)); auto* header = reinterpret_cast<const icmp6_hdr*>(&buffer); QuicWriterMutexLock mu(&header_lock_); if (header->icmp6_data32[0] != icmp_header_.icmp6_data32[0]) { QUIC_VLOG(2) << "Unexpected response. id: " << header->icmp6_id << " seq: " << header->icmp6_seq << " Expected id: " << icmp_header_.icmp6_id << " seq: " << icmp_header_.icmp6_seq; return true; } end_ = clock_->Now(); QUIC_VLOG(1) << "Received ping response in " << (end_ - start_); std::string source; QuicIpAddress source_ip; if (!source_ip.FromPackedString( reinterpret_cast<char*>(&source_addr.sin6_addr), sizeof(in6_addr))) { QUIC_LOG(WARNING) << "Unable to parse source address."; source = kUnknownSource; } else { source = source_ip.ToString(); } stats_->OnEvent({Status::REACHABLE, end_ - start_, source}); return true; } void IcmpReachable::OnAlarm() { QuicWriterMutexLock mu(&header_lock_); if (end_ < start_) { QUIC_VLOG(1) << "Timed out on sequence: " << icmp_header_.icmp6_seq; stats_->OnEvent({Status::UNREACHABLE, QuicTime::Delta::Zero(), kNoSource}); } icmp_header_.icmp6_seq++; CreateIcmpPacket(src_.sin6_addr, dst_.sin6_addr, icmp_header_, "", [this](absl::string_view packet) { QUIC_VLOG(2) << quiche::QuicheTextUtils::HexDump(packet); ssize_t size = kernel_->sendto( send_fd_, packet.data(), packet.size(), 0, reinterpret_cast<struct sockaddr*>(&dst_), sizeof(sockaddr_in6)); if (size < packet.size()) { stats_->OnWriteError(errno); } start_ = clock_->Now(); }); alarm_->Set(clock_->ApproximateNow() + timeout_); } absl::string_view IcmpReachable::StatusName(IcmpReachable::Status status) { switch (status) { case REACHABLE: return "REACHABLE"; case UNREACHABLE: return "UNREACHABLE"; default: return "UNKNOWN"; } } void IcmpReachable::EpollCallback::OnSocketEvent(QuicEventLoop* event_loop, SocketFd fd, QuicSocketEventMask events) { bool can_read_more = reachable_->OnEvent(fd); if (can_read_more) { bool success = event_loop->ArtificiallyNotifyEvent(fd, kSocketEventReadable); QUICHE_DCHECK(success); } } }
#include "quiche/quic/qbone/bonnet/icmp_reachable.h" #include <netinet/ip6.h> #include <memory> #include <string> #include "absl/container/node_hash_map.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { using ::testing::_; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrictMock; constexpr char kSourceAddress[] = "fe80:1:2:3:4::1"; constexpr char kDestinationAddress[] = "fe80:4:3:2:1::1"; constexpr int kFakeWriteFd = 0; icmp6_hdr GetHeaderFromPacket(const void* buf, size_t len) { QUICHE_CHECK_GE(len, sizeof(ip6_hdr) + sizeof(icmp6_hdr)); auto* buffer = reinterpret_cast<const char*>(buf); return *reinterpret_cast<const icmp6_hdr*>(&buffer[sizeof(ip6_hdr)]); } class StatsInterface : public IcmpReachable::StatsInterface { public: void OnEvent(IcmpReachable::ReachableEvent event) override { switch (event.status) { case IcmpReachable::REACHABLE: { reachable_count_++; break; } case IcmpReachable::UNREACHABLE: { unreachable_count_++; break; } } current_source_ = event.source; } void OnReadError(int error) override { read_errors_[error]++; } void OnWriteError(int error) override { write_errors_[error]++; } bool HasWriteErrors() { return !write_errors_.empty(); } int WriteErrorCount(int error) { return write_errors_[error]; } bool HasReadErrors() { return !read_errors_.empty(); } int ReadErrorCount(int error) { return read_errors_[error]; } int reachable_count() { return reachable_count_; } int unreachable_count() { return unreachable_count_; } std::string current_source() { return current_source_; } private: int reachable_count_ = 0; int unreachable_count_ = 0; std::string current_source_{}; absl::node_hash_map<int, int> read_errors_; absl::node_hash_map<int, int> write_errors_; }; class IcmpReachableTest : public QuicTest { public: IcmpReachableTest() : event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())) { QUICHE_CHECK(source_.FromString(kSourceAddress)); QUICHE_CHECK(destination_.FromString(kDestinationAddress)); int pipe_fds[2]; QUICHE_CHECK(pipe(pipe_fds) >= 0) << "pipe() failed"; read_fd_ = pipe_fds[0]; read_src_fd_ = pipe_fds[1]; } void SetFdExpectations() { InSequence seq; EXPECT_CALL(kernel_, socket(_, _, _)).WillOnce(Return(kFakeWriteFd)); EXPECT_CALL(kernel_, bind(kFakeWriteFd, _, _)).WillOnce(Return(0)); EXPECT_CALL(kernel_, socket(_, _, _)).WillOnce(Return(read_fd_)); EXPECT_CALL(kernel_, bind(read_fd_, _, _)).WillOnce(Return(0)); EXPECT_CALL(kernel_, setsockopt(read_fd_, SOL_ICMPV6, ICMP6_FILTER, _, _)); EXPECT_CALL(kernel_, close(read_fd_)).WillOnce(Invoke([](int fd) { return close(fd); })); } protected: QuicIpAddress source_; QuicIpAddress destination_; int read_fd_; int read_src_fd_; StrictMock<MockKernel> kernel_; std::unique_ptr<QuicEventLoop> event_loop_; StatsInterface stats_; }; TEST_F(IcmpReachableTest, SendsPings) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { auto icmp_header = GetHeaderFromPacket(buf, len); EXPECT_EQ(icmp_header.icmp6_type, ICMP6_ECHO_REQUEST); EXPECT_EQ(icmp_header.icmp6_seq, 1); return len; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasWriteErrors()); } TEST_F(IcmpReachableTest, HandlesUnreachableEvents) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .Times(2) .WillRepeatedly(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { return len; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.unreachable_count(), 0); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasWriteErrors()); EXPECT_EQ(stats_.unreachable_count(), 1); EXPECT_EQ(stats_.current_source(), kNoSource); } TEST_F(IcmpReachableTest, HandlesReachableEvents) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); icmp6_hdr last_request_hdr{}; EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .Times(2) .WillRepeatedly( Invoke([&last_request_hdr]( int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { last_request_hdr = GetHeaderFromPacket(buf, len); return len; })); sockaddr_in6 source_addr{}; std::string packed_source = source_.ToPackedString(); memcpy(&source_addr.sin6_addr, packed_source.data(), packed_source.size()); EXPECT_CALL(kernel_, recvfrom(read_fd_, _, _, _, _, _)) .WillOnce( Invoke([&source_addr](int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, socklen_t* addrlen) { *reinterpret_cast<sockaddr_in6*>(src_addr) = source_addr; return read(sockfd, buf, len); })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.reachable_count(), 0); icmp6_hdr response = last_request_hdr; response.icmp6_type = ICMP6_ECHO_REPLY; write(read_src_fd_, reinterpret_cast<const void*>(&response), sizeof(icmp6_hdr)); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(stats_.HasReadErrors()); EXPECT_FALSE(stats_.HasWriteErrors()); EXPECT_EQ(stats_.reachable_count(), 1); EXPECT_EQ(stats_.current_source(), source_.ToString()); } TEST_F(IcmpReachableTest, HandlesWriteErrors) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { errno = EAGAIN; return 0; })); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.WriteErrorCount(EAGAIN), 1); } TEST_F(IcmpReachableTest, HandlesReadErrors) { IcmpReachable reachable(source_, destination_, QuicTime::Delta::Zero(), &kernel_, event_loop_.get(), &stats_); SetFdExpectations(); ASSERT_TRUE(reachable.Init()); EXPECT_CALL(kernel_, sendto(kFakeWriteFd, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, socklen_t addrlen) { return len; })); EXPECT_CALL(kernel_, recvfrom(read_fd_, _, _, _, _, _)) .WillOnce(Invoke([](int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, socklen_t* addrlen) { errno = EIO; return -1; })); icmp6_hdr response{}; write(read_src_fd_, reinterpret_cast<const void*>(&response), sizeof(icmp6_hdr)); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); EXPECT_EQ(stats_.reachable_count(), 0); EXPECT_EQ(stats_.ReadErrorCount(EIO), 1); } } }
223
cpp
google/quiche
tun_device_controller
quiche/quic/qbone/bonnet/tun_device_controller.cc
quiche/quic/qbone/bonnet/tun_device_controller_test.cc
#ifndef QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_CONTROLLER_H_ #define QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_CONTROLLER_H_ #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/qbone/bonnet/tun_device.h" #include "quiche/quic/qbone/platform/netlink_interface.h" #include "quiche/quic/qbone/qbone_control.pb.h" #include "quiche/quic/qbone/qbone_control_stream.h" #include "quiche/common/quiche_callbacks.h" namespace quic { class TunDeviceController { public: TunDeviceController(std::string ifname, bool setup_tun, NetlinkInterface* netlink) : ifname_(std::move(ifname)), setup_tun_(setup_tun), netlink_(netlink) {} TunDeviceController(const TunDeviceController&) = delete; TunDeviceController& operator=(const TunDeviceController&) = delete; TunDeviceController(TunDeviceController&&) = delete; TunDeviceController& operator=(TunDeviceController&&) = delete; virtual ~TunDeviceController() = default; virtual bool UpdateAddress(const IpRange& desired_range); virtual bool UpdateRoutes(const IpRange& desired_range, const std::vector<IpRange>& desired_routes); virtual bool UpdateRoutesWithRetries( const IpRange& desired_range, const std::vector<IpRange>& desired_routes, int retries); virtual void RegisterAddressUpdateCallback( quiche::MultiUseCallback<void(QuicIpAddress)> cb); virtual QuicIpAddress current_address(); private: bool UpdateRules(IpRange desired_range); const std::string ifname_; const bool setup_tun_; NetlinkInterface* netlink_; QuicIpAddress current_address_; std::vector<quiche::MultiUseCallback<void(QuicIpAddress)>> address_update_cbs_; }; } #endif #include "quiche/quic/qbone/bonnet/tun_device_controller.h" #include <linux/rtnetlink.h> #include <utility> #include <vector> #include "absl/flags/flag.h" #include "absl/time/clock.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/qbone_constants.h" #include "quiche/common/quiche_callbacks.h" ABSL_FLAG(bool, qbone_tun_device_replace_default_routing_rules, true, "If true, will define a rule that points packets sourced from the " "qbone interface to the qbone table. This is unnecessary in " "environments with no other ipv6 route."); ABSL_RETIRED_FLAG(int, qbone_route_init_cwnd, 0, "Deprecated. Code no longer modifies initcwnd."); namespace quic { bool TunDeviceController::UpdateAddress(const IpRange& desired_range) { if (!setup_tun_) { return true; } NetlinkInterface::LinkInfo link_info{}; if (!netlink_->GetLinkInfo(ifname_, &link_info)) { return false; } std::vector<NetlinkInterface::AddressInfo> addresses; if (!netlink_->GetAddresses(link_info.index, 0, &addresses, nullptr)) { return false; } QuicIpAddress desired_address = desired_range.FirstAddressInRange(); for (const auto& address : addresses) { if (!netlink_->ChangeLocalAddress( link_info.index, NetlinkInterface::Verb::kRemove, address.interface_address, address.prefix_length, 0, 0, {})) { return false; } } bool address_updated = netlink_->ChangeLocalAddress( link_info.index, NetlinkInterface::Verb::kAdd, desired_address, desired_range.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, {}); if (address_updated) { current_address_ = desired_address; for (const auto& cb : address_update_cbs_) { cb(current_address_); } } return address_updated; } bool TunDeviceController::UpdateRoutes( const IpRange& desired_range, const std::vector<IpRange>& desired_routes) { if (!setup_tun_) { return true; } NetlinkInterface::LinkInfo link_info{}; if (!netlink_->GetLinkInfo(ifname_, &link_info)) { QUIC_LOG(ERROR) << "Could not get link info for interface <" << ifname_ << ">"; return false; } std::vector<NetlinkInterface::RoutingRule> routing_rules; if (!netlink_->GetRouteInfo(&routing_rules)) { QUIC_LOG(ERROR) << "Unable to get route info"; return false; } for (const auto& rule : routing_rules) { if (rule.out_interface == link_info.index && rule.table == QboneConstants::kQboneRouteTableId) { if (!netlink_->ChangeRoute(NetlinkInterface::Verb::kRemove, rule.table, rule.destination_subnet, rule.scope, rule.preferred_source, rule.out_interface)) { QUIC_LOG(ERROR) << "Unable to remove old route to <" << rule.destination_subnet.ToString() << ">"; return false; } } } if (!UpdateRules(desired_range)) { return false; } QuicIpAddress desired_address = desired_range.FirstAddressInRange(); std::vector<IpRange> routes(desired_routes.begin(), desired_routes.end()); routes.emplace_back(*QboneConstants::TerminatorLocalAddressRange()); for (const auto& route : routes) { if (!netlink_->ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, route, RT_SCOPE_LINK, desired_address, link_info.index)) { QUIC_LOG(ERROR) << "Unable to add route <" << route.ToString() << ">"; return false; } } return true; } bool TunDeviceController::UpdateRoutesWithRetries( const IpRange& desired_range, const std::vector<IpRange>& desired_routes, int retries) { while (retries-- > 0) { if (UpdateRoutes(desired_range, desired_routes)) { return true; } absl::SleepFor(absl::Milliseconds(100)); } return false; } bool TunDeviceController::UpdateRules(IpRange desired_range) { if (!absl::GetFlag(FLAGS_qbone_tun_device_replace_default_routing_rules)) { return true; } std::vector<NetlinkInterface::IpRule> ip_rules; if (!netlink_->GetRuleInfo(&ip_rules)) { QUIC_LOG(ERROR) << "Unable to get rule info"; return false; } for (const auto& rule : ip_rules) { if (rule.table == QboneConstants::kQboneRouteTableId) { if (!netlink_->ChangeRule(NetlinkInterface::Verb::kRemove, rule.table, rule.source_range)) { QUIC_LOG(ERROR) << "Unable to remove old rule for table <" << rule.table << "> from source <" << rule.source_range.ToString() << ">"; return false; } } } if (!netlink_->ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, desired_range)) { QUIC_LOG(ERROR) << "Unable to add rule for <" << desired_range.ToString() << ">"; return false; } return true; } QuicIpAddress TunDeviceController::current_address() { return current_address_; } void TunDeviceController::RegisterAddressUpdateCallback( quiche::MultiUseCallback<void(QuicIpAddress)> cb) { address_update_cbs_.push_back(std::move(cb)); } }
#include "quiche/quic/qbone/bonnet/tun_device_controller.h" #include <linux/if_addr.h> #include <linux/rtnetlink.h> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_netlink.h" #include "quiche/quic/qbone/qbone_constants.h" ABSL_DECLARE_FLAG(bool, qbone_tun_device_replace_default_routing_rules); ABSL_DECLARE_FLAG(int, qbone_route_init_cwnd); namespace quic::test { namespace { using ::testing::Eq; constexpr int kIfindex = 42; constexpr char kIfname[] = "qbone0"; const IpRange kIpRange = []() { IpRange range; QCHECK(range.FromString("2604:31c0:2::/64")); return range; }(); constexpr char kOldAddress[] = "1.2.3.4"; constexpr int kOldPrefixLen = 24; using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::StrictMock; MATCHER_P(IpRangeEq, range, absl::StrCat("expected IpRange to equal ", range.ToString())) { return arg == range; } class TunDeviceControllerTest : public QuicTest { public: TunDeviceControllerTest() : controller_(kIfname, true, &netlink_), link_local_range_(*QboneConstants::TerminatorLocalAddressRange()) { controller_.RegisterAddressUpdateCallback( [this](QuicIpAddress address) { notified_address_ = address; }); } protected: void ExpectLinkInfo(const std::string& interface_name, int ifindex) { EXPECT_CALL(netlink_, GetLinkInfo(interface_name, _)) .WillOnce(Invoke([ifindex](absl::string_view ifname, NetlinkInterface::LinkInfo* link_info) { link_info->index = ifindex; return true; })); } MockNetlink netlink_; TunDeviceController controller_; QuicIpAddress notified_address_; IpRange link_local_range_; }; TEST_F(TunDeviceControllerTest, AddressAppliedWhenNoneExisted) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetAddresses(kIfindex, _, _, _)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeLocalAddress( kIfindex, NetlinkInterface::Verb::kAdd, kIpRange.FirstAddressInRange(), kIpRange.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, _)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateAddress(kIpRange)); EXPECT_THAT(notified_address_, Eq(kIpRange.FirstAddressInRange())); } TEST_F(TunDeviceControllerTest, OldAddressesAreRemoved) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetAddresses(kIfindex, _, _, _)) .WillOnce(Invoke([](int interface_index, uint8_t unwanted_flags, std::vector<NetlinkInterface::AddressInfo>* addresses, int* num_ipv6_nodad_dadfailed_addresses) { NetlinkInterface::AddressInfo info{}; info.interface_address.FromString(kOldAddress); info.prefix_length = kOldPrefixLen; addresses->emplace_back(info); return true; })); QuicIpAddress old_address; old_address.FromString(kOldAddress); EXPECT_CALL(netlink_, ChangeLocalAddress(kIfindex, NetlinkInterface::Verb::kRemove, old_address, kOldPrefixLen, _, _, _)) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeLocalAddress( kIfindex, NetlinkInterface::Verb::kAdd, kIpRange.FirstAddressInRange(), kIpRange.prefix_length(), IFA_F_PERMANENT | IFA_F_NODAD, RT_SCOPE_LINK, _)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateAddress(kIpRange)); EXPECT_THAT(notified_address_, Eq(kIpRange.FirstAddressInRange())); } TEST_F(TunDeviceControllerTest, UpdateRoutesRemovedOldRoutes) { ExpectLinkInfo(kIfname, kIfindex); const int num_matching_routes = 3; EXPECT_CALL(netlink_, GetRouteInfo(_)) .WillOnce( Invoke([](std::vector<NetlinkInterface::RoutingRule>* routing_rules) { NetlinkInterface::RoutingRule non_matching_route{}; non_matching_route.table = QboneConstants::kQboneRouteTableId; non_matching_route.out_interface = kIfindex + 1; routing_rules->push_back(non_matching_route); NetlinkInterface::RoutingRule matching_route{}; matching_route.table = QboneConstants::kQboneRouteTableId; matching_route.out_interface = kIfindex; for (int i = 0; i < num_matching_routes; i++) { routing_rules->push_back(matching_route); } NetlinkInterface::RoutingRule non_matching_table{}; non_matching_table.table = QboneConstants::kQboneRouteTableId + 1; non_matching_table.out_interface = kIfindex; routing_rules->push_back(non_matching_table); return true; })); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kRemove, QboneConstants::kQboneRouteTableId, _, _, _, kIfindex)) .Times(num_matching_routes) .WillRepeatedly(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {})); } TEST_F(TunDeviceControllerTest, UpdateRoutesAddsNewRoutes) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange), _, _, kIfindex)) .Times(2) .WillRepeatedly(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {kIpRange, kIpRange})); } TEST_F(TunDeviceControllerTest, EmptyUpdateRouteKeepsLinkLocalRoute) { ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, GetRuleInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRule(NetlinkInterface::Verb::kAdd, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange))) .WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {})); } TEST_F(TunDeviceControllerTest, DisablingRoutingRulesSkipsRuleCreation) { absl::SetFlag(&FLAGS_qbone_tun_device_replace_default_routing_rules, false); ExpectLinkInfo(kIfname, kIfindex); EXPECT_CALL(netlink_, GetRouteInfo(_)).WillOnce(Return(true)); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(kIpRange), _, _, kIfindex)) .Times(2) .WillRepeatedly(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(netlink_, ChangeRoute(NetlinkInterface::Verb::kReplace, QboneConstants::kQboneRouteTableId, IpRangeEq(link_local_range_), _, _, kIfindex)) .WillOnce(Return(true)); EXPECT_TRUE(controller_.UpdateRoutes(kIpRange, {kIpRange, kIpRange})); } class DisabledTunDeviceControllerTest : public QuicTest { public: DisabledTunDeviceControllerTest() : controller_(kIfname, false, &netlink_), link_local_range_(*QboneConstants::TerminatorLocalAddressRange()) {} StrictMock<MockNetlink> netlink_; TunDeviceController controller_; IpRange link_local_range_; }; TEST_F(DisabledTunDeviceControllerTest, UpdateRoutesIsNop) { EXPECT_THAT(controller_.UpdateRoutes(kIpRange, {}), Eq(true)); } TEST_F(DisabledTunDeviceControllerTest, UpdateAddressIsNop) { EXPECT_THAT(controller_.UpdateAddress(kIpRange), Eq(true)); } } }
224
cpp
google/quiche
tun_device
quiche/quic/qbone/bonnet/tun_device.cc
quiche/quic/qbone/bonnet/tun_device_test.cc
#ifndef QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_H_ #define QUICHE_QUIC_QBONE_BONNET_TUN_DEVICE_H_ #include <string> #include <vector> #include "quiche/quic/qbone/bonnet/tun_device_interface.h" #include "quiche/quic/qbone/platform/kernel_interface.h" namespace quic { class TunTapDevice : public TunDeviceInterface { public: TunTapDevice(const std::string& interface_name, int mtu, bool persist, bool setup_tun, bool is_tap, KernelInterface* kernel); ~TunTapDevice() override; bool Init() override; bool Up() override; bool Down() override; void CloseDevice() override; int GetFileDescriptor() const override; private: bool OpenDevice(); bool ConfigureInterface(); bool CheckFeatures(int tun_device_fd); bool NetdeviceIoctl(int request, void* argp); const std::string interface_name_; const int mtu_; const bool persist_; const bool setup_tun_; const bool is_tap_; int file_descriptor_; KernelInterface& kernel_; }; } #endif #include "quiche/quic/qbone/bonnet/tun_device.h" #include <fcntl.h> #include <linux/if_tun.h> #include <net/if.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <ios> #include <string> #include "absl/cleanup/cleanup.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/qbone/platform/kernel_interface.h" ABSL_FLAG(std::string, qbone_client_tun_device_path, "/dev/net/tun", "The path to the QBONE client's TUN device."); namespace quic { const int kInvalidFd = -1; TunTapDevice::TunTapDevice(const std::string& interface_name, int mtu, bool persist, bool setup_tun, bool is_tap, KernelInterface* kernel) : interface_name_(interface_name), mtu_(mtu), persist_(persist), setup_tun_(setup_tun), is_tap_(is_tap), file_descriptor_(kInvalidFd), kernel_(*kernel) {} TunTapDevice::~TunTapDevice() { if (!persist_) { Down(); } CloseDevice(); } bool TunTapDevice::Init() { if (interface_name_.empty() || interface_name_.size() >= IFNAMSIZ) { QUIC_BUG(quic_bug_10995_1) << "interface_name must be nonempty and shorter than " << IFNAMSIZ; return false; } if (!OpenDevice()) { return false; } if (!ConfigureInterface()) { return false; } return true; } bool TunTapDevice::Up() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = IFF_UP; return NetdeviceIoctl(SIOCSIFFLAGS, reinterpret_cast<void*>(&if_request)); } bool TunTapDevice::Down() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = 0; return NetdeviceIoctl(SIOCSIFFLAGS, reinterpret_cast<void*>(&if_request)); } int TunTapDevice::GetFileDescriptor() const { return file_descriptor_; } bool TunTapDevice::OpenDevice() { if (file_descriptor_ != kInvalidFd) { CloseDevice(); } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_flags = IFF_MULTI_QUEUE | IFF_NO_PI; if (is_tap_) { if_request.ifr_flags |= IFF_TAP; } else { if_request.ifr_flags |= IFF_TUN; } bool successfully_opened = false; auto cleanup = absl::MakeCleanup([this, &successfully_opened]() { if (!successfully_opened) { CloseDevice(); } }); const std::string tun_device_path = absl::GetFlag(FLAGS_qbone_client_tun_device_path); int fd = kernel_.open(tun_device_path.c_str(), O_RDWR); if (fd < 0) { QUIC_PLOG(WARNING) << "Failed to open " << tun_device_path; return successfully_opened; } file_descriptor_ = fd; if (!CheckFeatures(fd)) { return successfully_opened; } if (kernel_.ioctl(fd, TUNSETIFF, reinterpret_cast<void*>(&if_request)) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNSETIFF on fd(" << fd << ")"; return successfully_opened; } if (kernel_.ioctl( fd, TUNSETPERSIST, persist_ ? reinterpret_cast<void*>(&if_request) : nullptr) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNSETPERSIST on fd(" << fd << ")"; return successfully_opened; } successfully_opened = true; return successfully_opened; } bool TunTapDevice::ConfigureInterface() { if (!setup_tun_) { return true; } struct ifreq if_request; memset(&if_request, 0, sizeof(if_request)); interface_name_.copy(if_request.ifr_name, IFNAMSIZ); if_request.ifr_mtu = mtu_; if (!NetdeviceIoctl(SIOCSIFMTU, reinterpret_cast<void*>(&if_request))) { CloseDevice(); return false; } return true; } bool TunTapDevice::CheckFeatures(int tun_device_fd) { unsigned int actual_features; if (kernel_.ioctl(tun_device_fd, TUNGETFEATURES, &actual_features) != 0) { QUIC_PLOG(WARNING) << "Failed to TUNGETFEATURES"; return false; } unsigned int required_features = IFF_TUN | IFF_NO_PI; if ((required_features & actual_features) != required_features) { QUIC_LOG(WARNING) << "Required feature does not exist. required_features: 0x" << std::hex << required_features << " vs actual_features: 0x" << std::hex << actual_features; return false; } return true; } bool TunTapDevice::NetdeviceIoctl(int request, void* argp) { int fd = kernel_.socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { QUIC_PLOG(WARNING) << "Failed to create AF_INET6 socket."; return false; } if (kernel_.ioctl(fd, request, argp) != 0) { QUIC_PLOG(WARNING) << "Failed ioctl request: " << request; kernel_.close(fd); return false; } kernel_.close(fd); return true; } void TunTapDevice::CloseDevice() { if (file_descriptor_ != kInvalidFd) { kernel_.close(file_descriptor_); file_descriptor_ = kInvalidFd; } } }
#include "quiche/quic/qbone/bonnet/tun_device.h" #include <linux/if.h> #include <linux/if_tun.h> #include <sys/ioctl.h> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/platform/mock_kernel.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; using ::testing::Unused; const char kDeviceName[] = "tun0"; const int kSupportedFeatures = IFF_TUN | IFF_TAP | IFF_MULTI_QUEUE | IFF_ONE_QUEUE | IFF_NO_PI; class TunDeviceTest : public QuicTest { protected: void SetUp() override { EXPECT_CALL(mock_kernel_, socket(AF_INET6, _, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([this](Unused, Unused, Unused) { EXPECT_CALL(mock_kernel_, close(next_fd_)).WillOnce(Return(0)); return next_fd_++; })); } void SetInitExpectations(int mtu, bool persist) { EXPECT_CALL(mock_kernel_, open(StrEq("/dev/net/tun"), _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([this](Unused, Unused) { EXPECT_CALL(mock_kernel_, close(next_fd_)).WillOnce(Return(0)); return next_fd_++; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([](Unused, Unused, void* argp) { auto* actual_flags = reinterpret_cast<int*>(argp); *actual_flags = kSupportedFeatures; return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETIFF, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_EQ(IFF_TUN | IFF_MULTI_QUEUE | IFF_NO_PI, ifr->ifr_flags); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETPERSIST, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([persist](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); if (persist) { EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); } else { EXPECT_EQ(nullptr, ifr); } return 0; })); EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFMTU, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke([mtu](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_EQ(mtu, ifr->ifr_mtu); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); return 0; })); } void ExpectUp(bool fail) { EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFFLAGS, _)) .WillOnce(Invoke([fail](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_TRUE(ifr->ifr_flags & IFF_UP); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); if (fail) { return -1; } else { return 0; } })); } void ExpectDown(bool fail) { EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFFLAGS, _)) .WillOnce(Invoke([fail](Unused, Unused, void* argp) { auto* ifr = reinterpret_cast<struct ifreq*>(argp); EXPECT_FALSE(ifr->ifr_flags & IFF_UP); EXPECT_THAT(ifr->ifr_name, StrEq(kDeviceName)); if (fail) { return -1; } else { return 0; } })); } MockKernel mock_kernel_; int next_fd_ = 100; }; TEST_F(TunDeviceTest, BasicWorkFlow) { SetInitExpectations( 1500, false); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_TRUE(tun_device.Init()); EXPECT_GT(tun_device.GetFileDescriptor(), -1); ExpectUp( false); EXPECT_TRUE(tun_device.Up()); ExpectDown( false); } TEST_F(TunDeviceTest, FailToOpenTunDevice) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, open(StrEq("/dev/net/tun"), _)) .WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, FailToCheckFeature) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, TooFewFeature) { SetInitExpectations( 1500, false); EXPECT_CALL(mock_kernel_, ioctl(_, TUNGETFEATURES, _)) .WillOnce(Invoke([](Unused, Unused, void* argp) { int* actual_features = reinterpret_cast<int*>(argp); *actual_features = IFF_TUN | IFF_ONE_QUEUE; return 0; })); TunTapDevice tun_device(kDeviceName, 1500, false, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); ExpectDown(false); } TEST_F(TunDeviceTest, FailToSetFlag) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETIFF, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToPersistDevice) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, TUNSETPERSIST, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToOpenSocket) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, socket(AF_INET6, _, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToSetMtu) { SetInitExpectations( 1500, true); EXPECT_CALL(mock_kernel_, ioctl(_, SIOCSIFMTU, _)).WillOnce(Return(-1)); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_FALSE(tun_device.Init()); EXPECT_EQ(tun_device.GetFileDescriptor(), -1); } TEST_F(TunDeviceTest, FailToUp) { SetInitExpectations( 1500, true); TunTapDevice tun_device(kDeviceName, 1500, true, true, false, &mock_kernel_); EXPECT_TRUE(tun_device.Init()); EXPECT_GT(tun_device.GetFileDescriptor(), -1); ExpectUp( true); EXPECT_FALSE(tun_device.Up()); } } }
225
cpp
google/quiche
qbone_tunnel_silo
quiche/quic/qbone/bonnet/qbone_tunnel_silo.cc
quiche/quic/qbone/bonnet/qbone_tunnel_silo_test.cc
#ifndef QUICHE_QUIC_QBONE_BONNET_QBONE_TUNNEL_SILO_H_ #define QUICHE_QUIC_QBONE_BONNET_QBONE_TUNNEL_SILO_H_ #include "absl/synchronization/notification.h" #include "quiche/quic/platform/api/quic_thread.h" #include "quiche/quic/qbone/bonnet/qbone_tunnel_interface.h" namespace quic { class QboneTunnelSilo : public QuicThread { public: explicit QboneTunnelSilo(QboneTunnelInterface* tunnel, bool only_setup_tun) : QuicThread("QboneTunnelSilo"), tunnel_(tunnel), only_setup_tun_(only_setup_tun) {} QboneTunnelSilo(const QboneTunnelSilo&) = delete; QboneTunnelSilo& operator=(const QboneTunnelSilo&) = delete; QboneTunnelSilo(QboneTunnelSilo&&) = delete; QboneTunnelSilo& operator=(QboneTunnelSilo&&) = delete; void Quit(); protected: void Run() override; private: bool ShouldRun(); QboneTunnelInterface* tunnel_; absl::Notification quitting_; const bool only_setup_tun_; }; } #endif #include "quiche/quic/qbone/bonnet/qbone_tunnel_silo.h" namespace quic { void QboneTunnelSilo::Run() { while (ShouldRun()) { tunnel_->WaitForEvents(); } QUIC_LOG(INFO) << "Tunnel has disconnected in state: " << tunnel_->StateToString(tunnel_->Disconnect()); } void QboneTunnelSilo::Quit() { QUIC_LOG(INFO) << "Quit called on QboneTunnelSilo"; quitting_.Notify(); tunnel_->Wake(); } bool QboneTunnelSilo::ShouldRun() { bool post_init_shutdown_ready = only_setup_tun_ && tunnel_->state() == quic::QboneTunnelInterface::STARTED; return !quitting_.HasBeenNotified() && !post_init_shutdown_ready; } }
#include "quiche/quic/qbone/bonnet/qbone_tunnel_silo.h" #include "absl/synchronization/notification.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/qbone/bonnet/mock_qbone_tunnel.h" namespace quic { namespace { using ::testing::Eq; using ::testing::Invoke; using ::testing::Return; TEST(QboneTunnelSiloTest, SiloRunsEventLoop) { MockQboneTunnel mock_tunnel; absl::Notification event_loop_run; EXPECT_CALL(mock_tunnel, WaitForEvents) .WillRepeatedly(Invoke([&event_loop_run]() { if (!event_loop_run.HasBeenNotified()) { event_loop_run.Notify(); } return false; })); QboneTunnelSilo silo(&mock_tunnel, false); silo.Start(); event_loop_run.WaitForNotification(); absl::Notification client_disconnected; EXPECT_CALL(mock_tunnel, Disconnect) .WillOnce(Invoke([&client_disconnected]() { client_disconnected.Notify(); return QboneTunnelInterface::ENDED; })); silo.Quit(); client_disconnected.WaitForNotification(); silo.Join(); } TEST(QboneTunnelSiloTest, SiloCanShutDownAfterInit) { MockQboneTunnel mock_tunnel; int iteration_count = 0; EXPECT_CALL(mock_tunnel, WaitForEvents) .WillRepeatedly(Invoke([&iteration_count]() { iteration_count++; return false; })); EXPECT_CALL(mock_tunnel, state) .WillOnce(Return(QboneTunnelInterface::START_REQUESTED)) .WillOnce(Return(QboneTunnelInterface::STARTED)); absl::Notification client_disconnected; EXPECT_CALL(mock_tunnel, Disconnect) .WillOnce(Invoke([&client_disconnected]() { client_disconnected.Notify(); return QboneTunnelInterface::ENDED; })); QboneTunnelSilo silo(&mock_tunnel, true); silo.Start(); client_disconnected.WaitForNotification(); silo.Join(); EXPECT_THAT(iteration_count, Eq(1)); } } }
226
cpp
google/quiche
quic_trace_visitor
quiche/quic/core/quic_trace_visitor.cc
quiche/quic/core/quic_trace_visitor_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_TRACE_VISITOR_H_ #define QUICHE_QUIC_CORE_QUIC_TRACE_VISITOR_H_ #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_types.h" #include "quic_trace/quic_trace.pb.h" namespace quic { class QUICHE_NO_EXPORT QuicTraceVisitor : public QuicConnectionDebugVisitor { public: explicit QuicTraceVisitor(const QuicConnection* connection); void OnPacketSent(QuicPacketNumber packet_number, QuicPacketLength packet_length, bool has_crypto_handshake, TransmissionType transmission_type, EncryptionLevel encryption_level, const QuicFrames& retransmittable_frames, const QuicFrames& nonretransmittable_frames, QuicTime sent_time, uint32_t batch_id) override; void OnIncomingAck(QuicPacketNumber ack_packet_number, EncryptionLevel ack_decrypted_level, const QuicAckFrame& ack_frame, QuicTime ack_receive_time, QuicPacketNumber largest_observed, bool rtt_updated, QuicPacketNumber least_unacked_sent_packet) override; void OnPacketLoss(QuicPacketNumber lost_packet_number, EncryptionLevel encryption_level, TransmissionType transmission_type, QuicTime detection_time) override; void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame, const QuicTime& receive_time) override; void OnSuccessfulVersionNegotiation( const ParsedQuicVersion& version) override; void OnApplicationLimited() override; void OnAdjustNetworkParameters(QuicBandwidth bandwidth, QuicTime::Delta rtt, QuicByteCount old_cwnd, QuicByteCount new_cwnd) override; quic_trace::Trace* trace() { return &trace_; } private: uint64_t ConvertTimestampToRecordedFormat(QuicTime timestamp); void PopulateFrameInfo(const QuicFrame& frame, quic_trace::Frame* frame_record); void PopulateTransportState(quic_trace::TransportState* state); quic_trace::Trace trace_; const QuicConnection* connection_; const QuicTime start_time_; }; } #endif #include "quiche/quic/core/quic_trace_visitor.h" #include <string> #include "quiche/quic/core/quic_types.h" #include "quiche/common/quiche_endian.h" namespace quic { quic_trace::EncryptionLevel EncryptionLevelToProto(EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: return quic_trace::ENCRYPTION_INITIAL; case ENCRYPTION_HANDSHAKE: return quic_trace::ENCRYPTION_HANDSHAKE; case ENCRYPTION_ZERO_RTT: return quic_trace::ENCRYPTION_0RTT; case ENCRYPTION_FORWARD_SECURE: return quic_trace::ENCRYPTION_1RTT; case NUM_ENCRYPTION_LEVELS: QUIC_BUG(EncryptionLevelToProto.Invalid) << "Invalid encryption level specified"; return quic_trace::ENCRYPTION_UNKNOWN; } QUIC_BUG(EncryptionLevelToProto.Unknown) << "Unknown encryption level specified " << static_cast<int>(level); return quic_trace::ENCRYPTION_UNKNOWN; } QuicTraceVisitor::QuicTraceVisitor(const QuicConnection* connection) : connection_(connection), start_time_(connection_->clock()->ApproximateNow()) { std::string binary_connection_id(connection->connection_id().data(), connection->connection_id().length()); switch (connection->perspective()) { case Perspective::IS_CLIENT: trace_.set_destination_connection_id(binary_connection_id); break; case Perspective::IS_SERVER: trace_.set_source_connection_id(binary_connection_id); break; } } void QuicTraceVisitor::OnPacketSent( QuicPacketNumber packet_number, QuicPacketLength packet_length, bool , TransmissionType , EncryptionLevel encryption_level, const QuicFrames& retransmittable_frames, const QuicFrames& , QuicTime sent_time, uint32_t ) { quic_trace::Event* event = trace_.add_events(); event->set_event_type(quic_trace::PACKET_SENT); event->set_time_us(ConvertTimestampToRecordedFormat(sent_time)); event->set_packet_number(packet_number.ToUint64()); event->set_packet_size(packet_length); event->set_encryption_level(EncryptionLevelToProto(encryption_level)); for (const QuicFrame& frame : retransmittable_frames) { switch (frame.type) { case STREAM_FRAME: case RST_STREAM_FRAME: case CONNECTION_CLOSE_FRAME: case WINDOW_UPDATE_FRAME: case BLOCKED_FRAME: case PING_FRAME: case HANDSHAKE_DONE_FRAME: case ACK_FREQUENCY_FRAME: PopulateFrameInfo(frame, event->add_frames()); break; case PADDING_FRAME: case MTU_DISCOVERY_FRAME: case STOP_WAITING_FRAME: case ACK_FRAME: QUIC_BUG(quic_bug_12732_1) << "Frames of type are not retransmittable and are not supposed " "to be in retransmittable_frames"; break; case NEW_CONNECTION_ID_FRAME: case RETIRE_CONNECTION_ID_FRAME: case MAX_STREAMS_FRAME: case STREAMS_BLOCKED_FRAME: case PATH_RESPONSE_FRAME: case PATH_CHALLENGE_FRAME: case STOP_SENDING_FRAME: case MESSAGE_FRAME: case CRYPTO_FRAME: case NEW_TOKEN_FRAME: case RESET_STREAM_AT_FRAME: break; case GOAWAY_FRAME: break; case NUM_FRAME_TYPES: QUIC_BUG(quic_bug_10284_2) << "Unknown frame type encountered"; break; } } if (connection_->sent_packet_manager() .GetSendAlgorithm() ->GetCongestionControlType() == kPCC) { PopulateTransportState(event->mutable_transport_state()); } } void QuicTraceVisitor::PopulateFrameInfo(const QuicFrame& frame, quic_trace::Frame* frame_record) { switch (frame.type) { case STREAM_FRAME: { frame_record->set_frame_type(quic_trace::STREAM); quic_trace::StreamFrameInfo* info = frame_record->mutable_stream_frame_info(); info->set_stream_id(frame.stream_frame.stream_id); info->set_fin(frame.stream_frame.fin); info->set_offset(frame.stream_frame.offset); info->set_length(frame.stream_frame.data_length); break; } case ACK_FRAME: { frame_record->set_frame_type(quic_trace::ACK); quic_trace::AckInfo* info = frame_record->mutable_ack_info(); info->set_ack_delay_us(frame.ack_frame->ack_delay_time.ToMicroseconds()); for (const auto& interval : frame.ack_frame->packets) { quic_trace::AckBlock* block = info->add_acked_packets(); block->set_first_packet(interval.min().ToUint64()); block->set_last_packet(interval.max().ToUint64() - 1); } break; } case RST_STREAM_FRAME: { frame_record->set_frame_type(quic_trace::RESET_STREAM); quic_trace::ResetStreamInfo* info = frame_record->mutable_reset_stream_info(); info->set_stream_id(frame.rst_stream_frame->stream_id); info->set_final_offset(frame.rst_stream_frame->byte_offset); info->set_application_error_code(frame.rst_stream_frame->error_code); break; } case CONNECTION_CLOSE_FRAME: { frame_record->set_frame_type(quic_trace::CONNECTION_CLOSE); quic_trace::CloseInfo* info = frame_record->mutable_close_info(); info->set_error_code(frame.connection_close_frame->quic_error_code); info->set_reason_phrase(frame.connection_close_frame->error_details); info->set_close_type(static_cast<quic_trace::CloseType>( frame.connection_close_frame->close_type)); info->set_transport_close_frame_type( frame.connection_close_frame->transport_close_frame_type); break; } case GOAWAY_FRAME: break; case WINDOW_UPDATE_FRAME: { bool is_connection = frame.window_update_frame.stream_id == 0; frame_record->set_frame_type(is_connection ? quic_trace::MAX_DATA : quic_trace::MAX_STREAM_DATA); quic_trace::FlowControlInfo* info = frame_record->mutable_flow_control_info(); info->set_max_data(frame.window_update_frame.max_data); if (!is_connection) { info->set_stream_id(frame.window_update_frame.stream_id); } break; } case BLOCKED_FRAME: { bool is_connection = frame.blocked_frame.stream_id == 0; frame_record->set_frame_type(is_connection ? quic_trace::BLOCKED : quic_trace::STREAM_BLOCKED); quic_trace::FlowControlInfo* info = frame_record->mutable_flow_control_info(); if (!is_connection) { info->set_stream_id(frame.window_update_frame.stream_id); } break; } case PING_FRAME: case MTU_DISCOVERY_FRAME: case HANDSHAKE_DONE_FRAME: frame_record->set_frame_type(quic_trace::PING); break; case PADDING_FRAME: frame_record->set_frame_type(quic_trace::PADDING); break; case STOP_WAITING_FRAME: break; case NEW_CONNECTION_ID_FRAME: case RETIRE_CONNECTION_ID_FRAME: case MAX_STREAMS_FRAME: case STREAMS_BLOCKED_FRAME: case PATH_RESPONSE_FRAME: case PATH_CHALLENGE_FRAME: case STOP_SENDING_FRAME: case MESSAGE_FRAME: case CRYPTO_FRAME: case NEW_TOKEN_FRAME: case ACK_FREQUENCY_FRAME: case RESET_STREAM_AT_FRAME: break; case NUM_FRAME_TYPES: QUIC_BUG(quic_bug_10284_3) << "Unknown frame type encountered"; break; } } void QuicTraceVisitor::OnIncomingAck( QuicPacketNumber , EncryptionLevel ack_decrypted_level, const QuicAckFrame& ack_frame, QuicTime ack_receive_time, QuicPacketNumber , bool , QuicPacketNumber ) { quic_trace::Event* event = trace_.add_events(); event->set_time_us(ConvertTimestampToRecordedFormat(ack_receive_time)); event->set_packet_number(connection_->GetLargestReceivedPacket().ToUint64()); event->set_event_type(quic_trace::PACKET_RECEIVED); event->set_encryption_level(EncryptionLevelToProto(ack_decrypted_level)); QuicAckFrame copy_of_ack = ack_frame; PopulateFrameInfo(QuicFrame(&copy_of_ack), event->add_frames()); PopulateTransportState(event->mutable_transport_state()); } void QuicTraceVisitor::OnPacketLoss(QuicPacketNumber lost_packet_number, EncryptionLevel encryption_level, TransmissionType , QuicTime detection_time) { quic_trace::Event* event = trace_.add_events(); event->set_time_us(ConvertTimestampToRecordedFormat(detection_time)); event->set_event_type(quic_trace::PACKET_LOST); event->set_packet_number(lost_packet_number.ToUint64()); PopulateTransportState(event->mutable_transport_state()); event->set_encryption_level(EncryptionLevelToProto(encryption_level)); } void QuicTraceVisitor::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame, const QuicTime& receive_time) { quic_trace::Event* event = trace_.add_events(); event->set_time_us(ConvertTimestampToRecordedFormat(receive_time)); event->set_event_type(quic_trace::PACKET_RECEIVED); event->set_packet_number(connection_->GetLargestReceivedPacket().ToUint64()); PopulateFrameInfo(QuicFrame(frame), event->add_frames()); } void QuicTraceVisitor::OnSuccessfulVersionNegotiation( const ParsedQuicVersion& version) { uint32_t tag = quiche::QuicheEndian::HostToNet32(CreateQuicVersionLabel(version)); std::string binary_tag(reinterpret_cast<const char*>(&tag), sizeof(tag)); trace_.set_protocol_version(binary_tag); } void QuicTraceVisitor::OnApplicationLimited() { quic_trace::Event* event = trace_.add_events(); event->set_time_us( ConvertTimestampToRecordedFormat(connection_->clock()->ApproximateNow())); event->set_event_type(quic_trace::APPLICATION_LIMITED); } void QuicTraceVisitor::OnAdjustNetworkParameters(QuicBandwidth bandwidth, QuicTime::Delta rtt, QuicByteCount , QuicByteCount ) { quic_trace::Event* event = trace_.add_events(); event->set_time_us( ConvertTimestampToRecordedFormat(connection_->clock()->ApproximateNow())); event->set_event_type(quic_trace::EXTERNAL_PARAMETERS); quic_trace::ExternalNetworkParameters* parameters = event->mutable_external_network_parameters(); if (!bandwidth.IsZero()) { parameters->set_bandwidth_bps(bandwidth.ToBitsPerSecond()); } if (!rtt.IsZero()) { parameters->set_rtt_us(rtt.ToMicroseconds()); } } uint64_t QuicTraceVisitor::ConvertTimestampToRecordedFormat( QuicTime timestamp) { if (timestamp < start_time_) { QUIC_BUG(quic_bug_10284_4) << "Timestamp went back in time while recording a trace"; return 0; } return (timestamp - start_time_).ToMicroseconds(); } void QuicTraceVisitor::PopulateTransportState( quic_trace::TransportState* state) { const RttStats* rtt_stats = connection_->sent_packet_manager().GetRttStats(); state->set_min_rtt_us(rtt_stats->min_rtt().ToMicroseconds()); state->set_smoothed_rtt_us(rtt_stats->smoothed_rtt().ToMicroseconds()); state->set_last_rtt_us(rtt_stats->latest_rtt().ToMicroseconds()); state->set_cwnd_bytes( connection_->sent_packet_manager().GetCongestionWindowInBytes()); QuicByteCount in_flight = connection_->sent_packet_manager().GetBytesInFlight(); state->set_in_flight_bytes(in_flight); state->set_pacing_rate_bps(connection_->sent_packet_manager() .GetSendAlgorithm() ->PacingRate(in_flight) .ToBitsPerSecond()); if (connection_->sent_packet_manager() .GetSendAlgorithm() ->GetCongestionControlType() == kPCC) { state->set_congestion_control_state( connection_->sent_packet_manager().GetSendAlgorithm()->GetDebugState()); } } }
#include "quiche/quic/core/quic_trace_visitor.h" #include <string> #include <vector> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/switch.h" namespace quic::test { namespace { const QuicByteCount kTransferSize = 1000 * kMaxOutgoingPacketSize; const QuicByteCount kTestStreamNumber = 3; const QuicTime::Delta kDelay = QuicTime::Delta::FromMilliseconds(20); class QuicTraceVisitorTest : public QuicTest { public: QuicTraceVisitorTest() { QuicConnectionId connection_id = test::TestConnectionId(); simulator::Simulator simulator; simulator::QuicEndpoint client(&simulator, "Client", "Server", Perspective::IS_CLIENT, connection_id); simulator::QuicEndpoint server(&simulator, "Server", "Client", Perspective::IS_SERVER, connection_id); const QuicBandwidth kBandwidth = QuicBandwidth::FromKBitsPerSecond(1000); const QuicByteCount kBdp = kBandwidth * (2 * kDelay); simulator::Switch network_switch(&simulator, "Switch", 8, 0.5 * kBdp); simulator::SymmetricLink client_link(&client, network_switch.port(1), 2 * kBandwidth, kDelay); simulator::SymmetricLink server_link(&server, network_switch.port(2), kBandwidth, kDelay); QuicTraceVisitor visitor(client.connection()); client.connection()->set_debug_visitor(&visitor); const QuicTime::Delta kDeadline = 3 * kBandwidth.TransferTime(kTransferSize); client.AddBytesToTransfer(kTransferSize); bool simulator_result = simulator.RunUntilOrTimeout( [&]() { return server.bytes_received() >= kTransferSize; }, kDeadline); QUICHE_CHECK(simulator_result); trace_.Swap(visitor.trace()); QUICHE_CHECK_NE(0u, client.connection()->GetStats().packets_retransmitted); packets_sent_ = client.connection()->GetStats().packets_sent; } std::vector<quic_trace::Event> AllEventsWithType( quic_trace::EventType event_type) { std::vector<quic_trace::Event> result; for (const auto& event : trace_.events()) { if (event.event_type() == event_type) { result.push_back(event); } } return result; } protected: quic_trace::Trace trace_; QuicPacketCount packets_sent_; }; TEST_F(QuicTraceVisitorTest, ConnectionId) { char expected_cid[] = {0, 0, 0, 0, 0, 0, 0, 42}; EXPECT_EQ(std::string(expected_cid, sizeof(expected_cid)), trace_.destination_connection_id()); } TEST_F(QuicTraceVisitorTest, Version) { std::string version = trace_.protocol_version(); ASSERT_EQ(4u, version.size()); EXPECT_TRUE(version[0] != 0 || version[1] != 0 || version[2] != 0 || version[3] != 0); } TEST_F(QuicTraceVisitorTest, SentPacket) { auto sent_packets = AllEventsWithType(quic_trace::PACKET_SENT); EXPECT_EQ(packets_sent_, sent_packets.size()); ASSERT_GT(sent_packets.size(), 0u); EXPECT_EQ(sent_packets[0].packet_size(), kDefaultMaxPacketSize); EXPECT_EQ(sent_packets[0].packet_number(), 1u); } TEST_F(QuicTraceVisitorTest, SentStream) { auto sent_packets = AllEventsWithType(quic_trace::PACKET_SENT); QuicIntervalSet<QuicStreamOffset> offsets; for (const quic_trace::Event& packet : sent_packets) { for (const quic_trace::Frame& frame : packet.frames()) { if (frame.frame_type() != quic_trace::STREAM) { continue; } const quic_trace::StreamFrameInfo& info = frame.stream_frame_info(); if (info.stream_id() != kTestStreamNumber) { continue; } ASSERT_GT(info.length(), 0u); offsets.Add(info.offset(), info.offset() + info.length()); } } ASSERT_EQ(1u, offsets.Size()); EXPECT_EQ(0u, offsets.begin()->min()); EXPECT_EQ(kTransferSize, offsets.rbegin()->max()); } TEST_F(QuicTraceVisitorTest, AckPackets) { QuicIntervalSet<QuicPacketNumber> packets; for (const quic_trace::Event& packet : trace_.events()) { if (packet.event_type() == quic_trace::PACKET_RECEIVED) { for (const quic_trace::Frame& frame : packet.frames()) { if (frame.frame_type() != quic_trace::ACK) { continue; } const quic_trace::AckInfo& info = frame.ack_info(); for (const auto& block : info.acked_packets()) { packets.Add(QuicPacketNumber(block.first_packet()), QuicPacketNumber(block.last_packet()) + 1); } } } if (packet.event_type() == quic_trace::PACKET_LOST) { packets.Add(QuicPacketNumber(packet.packet_number()), QuicPacketNumber(packet.packet_number()) + 1); } } ASSERT_EQ(1u, packets.Size()); EXPECT_EQ(QuicPacketNumber(1u), packets.begin()->min()); EXPECT_GT(packets.rbegin()->max(), QuicPacketNumber(packets_sent_ - 20)); } TEST_F(QuicTraceVisitorTest, TransportState) { auto acks = AllEventsWithType(quic_trace::PACKET_RECEIVED); ASSERT_EQ(1, acks[0].frames_size()); ASSERT_EQ(quic_trace::ACK, acks[0].frames(0).frame_type()); EXPECT_LE((4 * kDelay).ToMicroseconds() * 1., acks.rbegin()->transport_state().min_rtt_us()); EXPECT_GE((4 * kDelay).ToMicroseconds() * 1.25, acks.rbegin()->transport_state().min_rtt_us()); } TEST_F(QuicTraceVisitorTest, EncryptionLevels) { for (const auto& event : trace_.events()) { switch (event.event_type()) { case quic_trace::PACKET_SENT: case quic_trace::PACKET_RECEIVED: case quic_trace::PACKET_LOST: ASSERT_TRUE(event.has_encryption_level()); ASSERT_NE(event.encryption_level(), quic_trace::ENCRYPTION_UNKNOWN); break; default: break; } } } } }
227
cpp
google/quiche
quic_crypto_client_handshaker
quiche/quic/core/quic_crypto_client_handshaker.cc
quiche/quic/core/quic_crypto_client_handshaker_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_HANDSHAKER_H_ #define QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_HANDSHAKER_H_ #include <string> #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { class QUICHE_EXPORT QuicCryptoClientHandshaker : public QuicCryptoClientStream::HandshakerInterface, public QuicCryptoHandshaker { public: QuicCryptoClientHandshaker( const QuicServerId& server_id, QuicCryptoClientStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler); QuicCryptoClientHandshaker(const QuicCryptoClientHandshaker&) = delete; QuicCryptoClientHandshaker& operator=(const QuicCryptoClientHandshaker&) = delete; ~QuicCryptoClientHandshaker() override; bool CryptoConnect() override; int num_sent_client_hellos() const override; bool ResumptionAttempted() const override; bool IsResumption() const override; bool EarlyDataAccepted() const override; ssl_early_data_reason_t EarlyDataReason() const override; bool ReceivedInchoateReject() const override; int num_scup_messages_received() const override; std::string chlo_hash() const override; bool encryption_established() const override; bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override; EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override; bool one_rtt_keys_available() const override; const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override; CryptoMessageParser* crypto_message_parser() override; HandshakeState GetHandshakeState() const override; size_t BufferSizeLimitForLevel(EncryptionLevel level) const override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnConnectionClosed(QuicErrorCode , ConnectionCloseSource ) override; void OnHandshakeDoneReceived() override; void OnNewTokenReceived(absl::string_view token) override; void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override { QUICHE_NOTREACHED(); } bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { QUICHE_NOTREACHED(); return false; } void OnHandshakeMessage(const CryptoHandshakeMessage& message) override; protected: QuicSession* session() const { return session_; } void DoSendCHLO(QuicCryptoClientConfig::CachedState* cached); private: class QUICHE_EXPORT ProofVerifierCallbackImpl : public ProofVerifierCallback { public: explicit ProofVerifierCallbackImpl(QuicCryptoClientHandshaker* parent); ~ProofVerifierCallbackImpl() override; void Run(bool ok, const std::string& error_details, std::unique_ptr<ProofVerifyDetails>* details) override; void Cancel(); private: QuicCryptoClientHandshaker* parent_; }; enum State { STATE_IDLE, STATE_INITIALIZE, STATE_SEND_CHLO, STATE_RECV_REJ, STATE_VERIFY_PROOF, STATE_VERIFY_PROOF_COMPLETE, STATE_RECV_SHLO, STATE_INITIALIZE_SCUP, STATE_NONE, STATE_CONNECTION_CLOSED, }; void HandleServerConfigUpdateMessage( const CryptoHandshakeMessage& server_config_update); void DoHandshakeLoop(const CryptoHandshakeMessage* in); void DoInitialize(QuicCryptoClientConfig::CachedState* cached); void DoReceiveREJ(const CryptoHandshakeMessage* in, QuicCryptoClientConfig::CachedState* cached); QuicAsyncStatus DoVerifyProof(QuicCryptoClientConfig::CachedState* cached); void DoVerifyProofComplete(QuicCryptoClientConfig::CachedState* cached); void DoReceiveSHLO(const CryptoHandshakeMessage* in, QuicCryptoClientConfig::CachedState* cached); void DoInitializeServerConfigUpdate( QuicCryptoClientConfig::CachedState* cached); void SetCachedProofValid(QuicCryptoClientConfig::CachedState* cached); QuicCryptoClientStream* stream_; QuicSession* session_; HandshakerDelegateInterface* delegate_; State next_state_; int num_client_hellos_; ssl_early_data_reason_t early_data_reason_ = ssl_early_data_unknown; QuicCryptoClientConfig* const crypto_config_; std::string chlo_hash_; const QuicServerId server_id_; uint64_t generation_counter_; std::unique_ptr<ProofVerifyContext> verify_context_; ProofVerifierCallbackImpl* proof_verify_callback_; QuicCryptoClientStream::ProofHandler* proof_handler_; bool verify_ok_; std::string verify_error_details_; std::unique_ptr<ProofVerifyDetails> verify_details_; QuicTime proof_verify_start_time_; int num_scup_messages_received_; bool encryption_established_; bool one_rtt_keys_available_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> crypto_negotiated_params_; }; } #endif #include "quiche/quic/core/quic_crypto_client_handshaker.h" #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_client_stats.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QuicCryptoClientHandshaker::ProofVerifierCallbackImpl:: ProofVerifierCallbackImpl(QuicCryptoClientHandshaker* parent) : parent_(parent) {} QuicCryptoClientHandshaker::ProofVerifierCallbackImpl:: ~ProofVerifierCallbackImpl() {} void QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::Run( bool ok, const std::string& error_details, std::unique_ptr<ProofVerifyDetails>* details) { if (parent_ == nullptr) { return; } parent_->verify_ok_ = ok; parent_->verify_error_details_ = error_details; parent_->verify_details_ = std::move(*details); parent_->proof_verify_callback_ = nullptr; parent_->DoHandshakeLoop(nullptr); } void QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::Cancel() { parent_ = nullptr; } QuicCryptoClientHandshaker::QuicCryptoClientHandshaker( const QuicServerId& server_id, QuicCryptoClientStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler) : QuicCryptoHandshaker(stream, session), stream_(stream), session_(session), delegate_(session), next_state_(STATE_IDLE), num_client_hellos_(0), crypto_config_(crypto_config), server_id_(server_id), generation_counter_(0), verify_context_(std::move(verify_context)), proof_verify_callback_(nullptr), proof_handler_(proof_handler), verify_ok_(false), proof_verify_start_time_(QuicTime::Zero()), num_scup_messages_received_(0), encryption_established_(false), one_rtt_keys_available_(false), crypto_negotiated_params_(new QuicCryptoNegotiatedParameters) {} QuicCryptoClientHandshaker::~QuicCryptoClientHandshaker() { if (proof_verify_callback_) { proof_verify_callback_->Cancel(); } } void QuicCryptoClientHandshaker::OnHandshakeMessage( const CryptoHandshakeMessage& message) { QuicCryptoHandshaker::OnHandshakeMessage(message); if (message.tag() == kSCUP) { if (!one_rtt_keys_available()) { stream_->OnUnrecoverableError( QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE, "Early SCUP disallowed"); return; } HandleServerConfigUpdateMessage(message); num_scup_messages_received_++; return; } if (one_rtt_keys_available()) { stream_->OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, "Unexpected handshake message"); return; } DoHandshakeLoop(&message); } bool QuicCryptoClientHandshaker::CryptoConnect() { next_state_ = STATE_INITIALIZE; DoHandshakeLoop(nullptr); return session()->connection()->connected(); } int QuicCryptoClientHandshaker::num_sent_client_hellos() const { return num_client_hellos_; } bool QuicCryptoClientHandshaker::ResumptionAttempted() const { QUICHE_DCHECK(false); return false; } bool QuicCryptoClientHandshaker::IsResumption() const { QUIC_BUG_IF(quic_bug_12522_1, !one_rtt_keys_available_); return false; } bool QuicCryptoClientHandshaker::EarlyDataAccepted() const { QUIC_BUG_IF(quic_bug_12522_2, !one_rtt_keys_available_); return num_client_hellos_ == 1; } ssl_early_data_reason_t QuicCryptoClientHandshaker::EarlyDataReason() const { return early_data_reason_; } bool QuicCryptoClientHandshaker::ReceivedInchoateReject() const { QUIC_BUG_IF(quic_bug_12522_3, !one_rtt_keys_available_); return num_client_hellos_ >= 3; } int QuicCryptoClientHandshaker::num_scup_messages_received() const { return num_scup_messages_received_; } std::string QuicCryptoClientHandshaker::chlo_hash() const { return chlo_hash_; } bool QuicCryptoClientHandshaker::encryption_established() const { return encryption_established_; } bool QuicCryptoClientHandshaker::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel ) const { return true; } EncryptionLevel QuicCryptoClientHandshaker::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { if (space == INITIAL_DATA) { return ENCRYPTION_INITIAL; } QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } bool QuicCryptoClientHandshaker::one_rtt_keys_available() const { return one_rtt_keys_available_; } const QuicCryptoNegotiatedParameters& QuicCryptoClientHandshaker::crypto_negotiated_params() const { return *crypto_negotiated_params_; } CryptoMessageParser* QuicCryptoClientHandshaker::crypto_message_parser() { return QuicCryptoHandshaker::crypto_message_parser(); } HandshakeState QuicCryptoClientHandshaker::GetHandshakeState() const { return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void QuicCryptoClientHandshaker::OnHandshakeDoneReceived() { QUICHE_DCHECK(false); } void QuicCryptoClientHandshaker::OnNewTokenReceived( absl::string_view ) { QUICHE_DCHECK(false); } size_t QuicCryptoClientHandshaker::BufferSizeLimitForLevel( EncryptionLevel level) const { return QuicCryptoHandshaker::BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> QuicCryptoClientHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter() { QUICHE_DCHECK(false); return nullptr; } std::unique_ptr<QuicEncrypter> QuicCryptoClientHandshaker::CreateCurrentOneRttEncrypter() { QUICHE_DCHECK(false); return nullptr; } void QuicCryptoClientHandshaker::OnConnectionClosed( QuicErrorCode , ConnectionCloseSource ) { next_state_ = STATE_CONNECTION_CLOSED; } void QuicCryptoClientHandshaker::HandleServerConfigUpdateMessage( const CryptoHandshakeMessage& server_config_update) { QUICHE_DCHECK(server_config_update.tag() == kSCUP); std::string error_details; QuicCryptoClientConfig::CachedState* cached = crypto_config_->LookupOrCreate(server_id_); QuicErrorCode error = crypto_config_->ProcessServerConfigUpdate( server_config_update, session()->connection()->clock()->WallNow(), session()->transport_version(), chlo_hash_, cached, crypto_negotiated_params_, &error_details); if (error != QUIC_NO_ERROR) { stream_->OnUnrecoverableError( error, "Server config update invalid: " + error_details); return; } QUICHE_DCHECK(one_rtt_keys_available()); if (proof_verify_callback_) { proof_verify_callback_->Cancel(); } next_state_ = STATE_INITIALIZE_SCUP; DoHandshakeLoop(nullptr); } void QuicCryptoClientHandshaker::DoHandshakeLoop( const CryptoHandshakeMessage* in) { QuicCryptoClientConfig::CachedState* cached = crypto_config_->LookupOrCreate(server_id_); QuicAsyncStatus rv = QUIC_SUCCESS; do { QUICHE_CHECK_NE(STATE_NONE, next_state_); const State state = next_state_; next_state_ = STATE_IDLE; rv = QUIC_SUCCESS; switch (state) { case STATE_INITIALIZE: DoInitialize(cached); break; case STATE_SEND_CHLO: DoSendCHLO(cached); return; case STATE_RECV_REJ: DoReceiveREJ(in, cached); break; case STATE_VERIFY_PROOF: rv = DoVerifyProof(cached); break; case STATE_VERIFY_PROOF_COMPLETE: DoVerifyProofComplete(cached); break; case STATE_RECV_SHLO: DoReceiveSHLO(in, cached); break; case STATE_IDLE: stream_->OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, "Handshake in idle state"); return; case STATE_INITIALIZE_SCUP: DoInitializeServerConfigUpdate(cached); break; case STATE_NONE: QUICHE_NOTREACHED(); return; case STATE_CONNECTION_CLOSED: rv = QUIC_FAILURE; return; } } while (rv != QUIC_PENDING && next_state_ != STATE_NONE); } void QuicCryptoClientHandshaker::DoInitialize( QuicCryptoClientConfig::CachedState* cached) { if (!cached->IsEmpty() && !cached->signature().empty()) { QUICHE_DCHECK(crypto_config_->proof_verifier()); proof_verify_start_time_ = session()->connection()->clock()->Now(); chlo_hash_ = cached->chlo_hash(); next_state_ = STATE_VERIFY_PROOF; } else { next_state_ = STATE_SEND_CHLO; } } void QuicCryptoClientHandshaker::DoSendCHLO( QuicCryptoClientConfig::CachedState* cached) { session()->connection()->SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); encryption_established_ = false; if (num_client_hellos_ >= QuicCryptoClientStream::kMaxClientHellos) { stream_->OnUnrecoverableError( QUIC_CRYPTO_TOO_MANY_REJECTS, absl::StrCat("More than ", QuicCryptoClientStream::kMaxClientHellos, " rejects")); return; } num_client_hellos_++; CryptoHandshakeMessage out; QUICHE_DCHECK(session() != nullptr); QUICHE_DCHECK(session()->config() != nullptr); session()->config()->ToHandshakeMessage(&out, session()->transport_version()); bool fill_inchoate_client_hello = false; if (!cached->IsComplete(session()->connection()->clock()->WallNow())) { early_data_reason_ = ssl_early_data_no_session_offered; fill_inchoate_client_hello = true; } else if (session()->config()->HasClientRequestedIndependentOption( kQNZ2, session()->perspective()) && num_client_hellos_ == 1) { early_data_reason_ = ssl_early_data_disabled; fill_inchoate_client_hello = true; } if (fill_inchoate_client_hello) { crypto_config_->FillInchoateClientHello( server_id_, session()->supported_versions().front(), cached, session()->connection()->random_generator(), true, crypto_negotiated_params_, &out); const QuicByteCount kFramingOverhead = 50; const QuicByteCount max_packet_size = session()->connection()->max_packet_length(); if (max_packet_size <= kFramingOverhead) { QUIC_DLOG(DFATAL) << "max_packet_length (" << max_packet_size << ") has no room for framing overhead."; stream_->OnUnrecoverableError(QUIC_INTERNAL_ERROR, "max_packet_size too smalll"); return; } if (kClientHelloMinimumSize > max_packet_size - kFramingOverhead) { QUIC_DLOG(DFATAL) << "Client hello won't fit in a single packet."; stream_->OnUnrecoverableError(QUIC_INTERNAL_ERROR, "CHLO too large"); return; } next_state_ = STATE_RECV_REJ; chlo_hash_ = CryptoUtils::HashHandshakeMessage(out, Perspective::IS_CLIENT); session()->connection()->set_fully_pad_crypto_handshake_packets( crypto_config_->pad_inchoate_hello()); SendHandshakeMessage(out, ENCRYPTION_INITIAL); return; } std::string error_details; QuicErrorCode error = crypto_config_->FillClientHello( server_id_, session()->connection()->connection_id(), session()->supported_versions().front(), session()->connection()->version(), cached, session()->connection()->clock()->WallNow(), session()->connection()->random_generator(), crypto_negotiated_params_, &out, &error_details); if (error != QUIC_NO_ERROR) { cached->InvalidateServerConfig(); stream_->OnUnrecoverableError(error, error_details); return; } chlo_hash_ = CryptoUtils::HashHandshakeMessage(out, Perspective::IS_CLIENT); if (cached->proof_verify_details()) { proof_handler_->OnProofVerifyDetailsAvailable( *cached->proof_verify_details()); } next_state_ = STATE_RECV_SHLO; session()->connection()->set_fully_pad_crypto_handshake_packets( crypto_config_->pad_full_hello()); SendHandshakeMessage(out, ENCRYPTION_INITIAL); delegate_->OnNewEncryptionKeyAvailable( ENCRYPTION_ZERO_RTT, std::move(crypto_negotiated_params_->initial_crypters.encrypter)); delegate_->OnNewDecryptionKeyAvailable( ENCRYPTION_ZERO_RTT, std::move(crypto_negotiated_params_->initial_crypters.decrypter), true, true); encryption_established_ = true; delegate_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); if (early_data_reason_ == ssl_early_data_unknown && num_client_hellos_ > 1) { early_data_reason_ = ssl_early_data_peer_declined; } } void QuicCryptoClientHandshaker::DoReceiveREJ( const CryptoHandshakeMessage* in, QuicCryptoClientConfig::CachedState* cached) { if (in->tag() != kREJ) { next_state_ = STATE_NONE; stream_->OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, "Expected REJ"); return; } QuicTagVector reject_reasons; static_assert(sizeof(QuicTag) == sizeof(uint32_t), "header out of sync"); if (in->GetTaglist(kRREJ, &reject_reasons) == QUIC_NO_ERROR) { uint32_t packed_error = 0; for (size_t i = 0; i < reject_reasons.size(); ++i) { if (reject_reasons[i] == HANDSHAKE_OK || reject_reasons[i] >= 32) { continue; } HandshakeFailureReason reason = static_cast<HandshakeFailureReason>(reject_reasons[i]); packed_error |= 1 << (reason - 1); } QUIC_DVLOG(1) << "Reasons for rejection: " << packed_error; } delegate_->NeuterUnencryptedData(); std::string error_details; QuicErrorCode error = crypto_config_->ProcessRejection( *in, session()->connection()->clock()->WallNow(), session()->transport_version(), chlo_hash_, cached, crypto_negotiated_params_, &error_details); if (error != QUIC_NO_ERROR) { next_state_ = STATE_NONE; stream_->OnUnrecoverableError(error, error_details); return; } if (!cached->proof_valid()) { if (!cached->signature().empty()) { next_state_ = STATE_VERIFY_PROOF; return; } } next_state_ = STATE_SEND_CHLO; } QuicAsyncStatus QuicCryptoClientHandshaker::DoVerifyProof( QuicCryptoClientConfig::CachedState* cached) { ProofVerifier* verifier = crypto_config_->proof_verifier(); QUICHE_DCHECK(verifier); next_state_ = STATE_VERIFY_PROOF_COMPLETE; generation_counter_ = cached->generation_counter(); ProofVerifierCallbackImpl* proof_verify_callback = new ProofVerifierCallbackImpl(this); verify_ok_ = false; QuicAsyncStatus status = verifier->VerifyProof( server_id_.host(), server_id_.port(), cached->server_config(), session()->transport_version(), chlo_hash_, cached->certs(), cached->cert_sct(), cached->signature(), verify_context_.get(), &verify_error_details_, &verify_details_, std::unique_ptr<ProofVerifierCallback>(proof_verify_callback)); switch (status) { case QUIC_PENDING: proof_verify_callback_ = proof_verify_callback; QUIC_DVLOG(1) << "Doing VerifyProof"; break; case QUIC_FAILURE: break; case QUIC_SUCCESS: verify_ok_ = true; break; } return status; } void QuicCryptoClientHandshaker::DoVerifyProofComplete( QuicCryptoClientConfig::CachedState* cached) { if (proof_verify_start_time_.IsInitialized()) { QUIC_CLIENT_HISTOGRAM_TIMES( "QuicSession.VerifyProofTime.CachedServerConfig", (session()->connection()->clock()->Now() - proof_verify_start_time_), QuicTime::Delta::FromMilliseconds(1), QuicTime::Delta::FromSeconds(10), 50, ""); } if (!verify_ok_) { if (verify_details_) { proof_handler_->OnProofVerifyDetailsAvailable(*verify_details_); } if (num_client_hellos_ == 0) { cached->Clear(); next_state_ = STATE_INITIALIZE; return; } next_state_ = STATE_NONE; QUIC_CLIENT_HISTOGRAM_BOOL("QuicVerifyProofFailed.HandshakeConfirmed", one_rtt_keys_available(), ""); stream_->OnUnrecoverableError(QUIC_PROOF_INVALID, "Proof invalid: " + verify_error_details_); return; } if (generation_counter_ != cached->generation_counter()) { next_state_ = STATE_VERIFY_PROOF; } else { SetCachedProofValid(cached); cached->SetProofVerifyDetails(verify_details_.release()); if (!one_rtt_keys_available()) { next_state_ = STATE_SEND_CHLO; } else { next_state_ = STATE_NONE; } } } void QuicCryptoClientHandshaker::DoReceiveSHLO( const CryptoHandshakeMessage* in, QuicCryptoClientConfig::CachedState* cached) { next_state_ = STATE_NONE; if (in->tag() == kREJ) { if (session()->connection()->last_decrypted_level() != ENCRYPTION_INITIAL) { stream_->OnUnrecoverableError(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT, "encrypted REJ message"); return; } next_state_ = STATE_RECV_REJ; return; } if (in->tag() != kSHLO) { stream_->OnUnrecoverableError( QUIC_INVALID_CRYPTO_MESSAGE_TYPE, absl::StrCat("Expected SHLO or REJ. Received: ", QuicTagToString(in->tag()))); return; } if (session()->connection()->last_decrypted_level() == ENCRYPTION_INITIAL) { stream_->OnUnrecoverableError(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT, "unencrypted SHLO message"); return; } if (num_client_hellos_ == 1) { early_data_reason_ = ssl_early_data_accepted; } std::string error_details; QuicErrorCode error = crypto_config_->ProcessServerHello( *in, session()->connection()->connection_id(), session()->connection()->version(), session()->connection()->server_supported_versions(), cached, crypto_negotiated_params_, &error_details); if (error != QUIC_NO_ERROR) { stream_->OnUnrecoverableError(error, "Server hello invalid: " + error_details); return; } error = session()->config()->ProcessPeerHello(*in, SERVER, &error_details); if (error != QUIC_NO_ERROR) { stream_->OnUnrecoverableError(error, "Server hello invalid: " + error_details); return; } session()->OnConfigNegotiated(); CrypterPair* crypters = &crypto_negotiated_params_->forward_secure_crypters; delegate_->OnNewEncryptionKeyAvailable(ENCRYPTION_FORWARD_SECURE, std::move(crypters->encrypter)); delegate_->OnNewDecryptionKeyAvailable(ENCRYPTION_FORWARD_SECURE, std::move(crypters->decrypter), true, false); one_rtt_keys_available_ = true; delegate_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); delegate_->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); delegate_->NeuterHandshakeData(); } void QuicCryptoClientHandshaker::DoInitializeServerConfigUpdate( QuicCryptoClientConfig::CachedState* cached) { bool update_ignored = false; if (!cached->IsEmpty() && !cached->signature().empty()) { QUICHE_DCHECK(crypto_config_->proof_verifier()); next_state_ = STATE_VERIFY_PROOF; } else { update_ignored = true; next_state_ = STATE_NONE; } QUIC_CLIENT_HISTOGRAM_COUNTS("QuicNumServerConfig.UpdateMessagesIgnored", update_ignored, 1, 1000000, 50, ""); } void QuicCryptoClientHandshaker::SetCachedProofValid( QuicCryptoClientConfig::CachedState* cached) { cached->SetProofValid(); proof_handler_->OnProofValid(*cached); } }
#include "quiche/quic/core/quic_crypto_client_handshaker.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic::test { namespace { class TestProofHandler : public QuicCryptoClientStream::ProofHandler { public: ~TestProofHandler() override {} void OnProofValid( const QuicCryptoClientConfig::CachedState& ) override {} void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& ) override {} }; class InsecureProofVerifier : public ProofVerifier { public: InsecureProofVerifier() {} ~InsecureProofVerifier() override {} QuicAsyncStatus VerifyProof( const std::string& , const uint16_t , const std::string& , QuicTransportVersion , absl::string_view , const std::vector<std::string>& , const std::string& , const std::string& , const ProofVerifyContext* , std::string* , std::unique_ptr<ProofVerifyDetails>* , std::unique_ptr<ProofVerifierCallback> ) override { return QUIC_SUCCESS; } QuicAsyncStatus VerifyCertChain( const std::string& , const uint16_t , const std::vector<std::string>& , const std::string& , const std::string& , const ProofVerifyContext* , std::string* , std::unique_ptr<ProofVerifyDetails>* , uint8_t* , std::unique_ptr<ProofVerifierCallback> ) override { return QUIC_SUCCESS; } std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override { return nullptr; } }; class DummyProofSource : public ProofSource { public: DummyProofSource() {} ~DummyProofSource() override {} void GetProof(const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, const std::string& , QuicTransportVersion , absl::string_view , std::unique_ptr<Callback> callback) override { bool cert_matched_sni; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain = GetCertChain(server_address, client_address, hostname, &cert_matched_sni); QuicCryptoProof proof; proof.signature = "Dummy signature"; proof.leaf_cert_scts = "Dummy timestamp"; proof.cert_matched_sni = cert_matched_sni; callback->Run(true, chain, proof, nullptr); } quiche::QuicheReferenceCountedPointer<Chain> GetCertChain( const QuicSocketAddress& , const QuicSocketAddress& , const std::string& , bool* ) override { std::vector<std::string> certs; certs.push_back("Dummy cert"); return quiche::QuicheReferenceCountedPointer<ProofSource::Chain>( new ProofSource::Chain(certs)); } void ComputeTlsSignature( const QuicSocketAddress& , const QuicSocketAddress& , const std::string& , uint16_t , absl::string_view , std::unique_ptr<SignatureCallback> callback) override { callback->Run(true, "Dummy signature", nullptr); } absl::InlinedVector<uint16_t, 8> SupportedTlsSignatureAlgorithms() const override { return {}; } TicketCrypter* GetTicketCrypter() override { return nullptr; } }; class Handshaker : public QuicCryptoClientHandshaker { public: Handshaker(const QuicServerId& server_id, QuicCryptoClientStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler) : QuicCryptoClientHandshaker(server_id, stream, session, std::move(verify_context), crypto_config, proof_handler) {} void DoSendCHLOTest(QuicCryptoClientConfig::CachedState* cached) { QuicCryptoClientHandshaker::DoSendCHLO(cached); } }; class QuicCryptoClientHandshakerTest : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicCryptoClientHandshakerTest() : version_(GetParam()), proof_handler_(), helper_(), alarm_factory_(), server_id_("host", 123), connection_(new test::MockQuicConnection( &helper_, &alarm_factory_, Perspective::IS_CLIENT, {version_})), session_(connection_, false), crypto_client_config_(std::make_unique<InsecureProofVerifier>()), client_stream_( new QuicCryptoClientStream(server_id_, &session_, nullptr, &crypto_client_config_, &proof_handler_, false)), handshaker_(server_id_, client_stream_, &session_, nullptr, &crypto_client_config_, &proof_handler_), state_() { session_.SetCryptoStream(client_stream_); session_.Initialize(); } void InitializeServerParametersToEnableFullHello() { QuicCryptoServerConfig::ConfigOptions options; QuicServerConfigProtobuf config = QuicCryptoServerConfig::GenerateConfig( helper_.GetRandomGenerator(), helper_.GetClock(), options); state_.Initialize( config.config(), "sourcetoken", std::vector<std::string>{"Dummy cert"}, "", "chlo_hash", "signature", helper_.GetClock()->WallNow(), helper_.GetClock()->WallNow().Add(QuicTime::Delta::FromSeconds(30))); state_.SetProofValid(); } ParsedQuicVersion version_; TestProofHandler proof_handler_; test::MockQuicConnectionHelper helper_; test::MockAlarmFactory alarm_factory_; QuicServerId server_id_; test::MockQuicConnection* connection_; test::MockQuicSession session_; QuicCryptoClientConfig crypto_client_config_; QuicCryptoClientStream* client_stream_; Handshaker handshaker_; QuicCryptoClientConfig::CachedState state_; }; INSTANTIATE_TEST_SUITE_P( QuicCryptoClientHandshakerTests, QuicCryptoClientHandshakerTest, ::testing::ValuesIn(AllSupportedVersionsWithQuicCrypto()), ::testing::PrintToStringParamName()); TEST_P(QuicCryptoClientHandshakerTest, TestSendFullPaddingInInchoateHello) { handshaker_.DoSendCHLOTest(&state_); EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestDisabledPaddingInInchoateHello) { crypto_client_config_.set_pad_inchoate_hello(false); handshaker_.DoSendCHLOTest(&state_); EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestPaddingInFullHelloEvenIfInchoateDisabled) { crypto_client_config_.set_pad_inchoate_hello(false); InitializeServerParametersToEnableFullHello(); handshaker_.DoSendCHLOTest(&state_); EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake()); } TEST_P(QuicCryptoClientHandshakerTest, TestNoPaddingInFullHelloWhenDisabled) { crypto_client_config_.set_pad_full_hello(false); InitializeServerParametersToEnableFullHello(); handshaker_.DoSendCHLOTest(&state_); EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake()); } } }
228
cpp
google/quiche
quic_version_manager
quiche/quic/core/quic_version_manager.cc
quiche/quic/core/quic_version_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_VERSION_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_VERSION_MANAGER_H_ #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QuicVersionManager { public: explicit QuicVersionManager(ParsedQuicVersionVector supported_versions); virtual ~QuicVersionManager(); const ParsedQuicVersionVector& GetSupportedVersions(); const ParsedQuicVersionVector& GetSupportedVersionsWithOnlyHttp3(); const std::vector<std::string>& GetSupportedAlpns(); protected: void MaybeRefilterSupportedVersions(); virtual void RefilterSupportedVersions(); const QuicTransportVersionVector& filtered_transport_versions() const { return filtered_transport_versions_; } void AddCustomAlpn(const std::string& alpn); private: bool enable_version_2_draft_08_ = false; bool disable_version_rfcv1_ = true; bool disable_version_draft_29_ = true; bool disable_version_q046_ = true; const ParsedQuicVersionVector allowed_supported_versions_; ParsedQuicVersionVector filtered_supported_versions_; ParsedQuicVersionVector filtered_supported_versions_with_http3_; QuicTransportVersionVector filtered_transport_versions_; std::vector<std::string> filtered_supported_alpns_; }; } #endif #include "quiche/quic/core/quic_version_manager.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicVersionManager::QuicVersionManager( ParsedQuicVersionVector supported_versions) : allowed_supported_versions_(std::move(supported_versions)) {} QuicVersionManager::~QuicVersionManager() {} const ParsedQuicVersionVector& QuicVersionManager::GetSupportedVersions() { MaybeRefilterSupportedVersions(); return filtered_supported_versions_; } const ParsedQuicVersionVector& QuicVersionManager::GetSupportedVersionsWithOnlyHttp3() { MaybeRefilterSupportedVersions(); return filtered_supported_versions_with_http3_; } const std::vector<std::string>& QuicVersionManager::GetSupportedAlpns() { MaybeRefilterSupportedVersions(); return filtered_supported_alpns_; } void QuicVersionManager::MaybeRefilterSupportedVersions() { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); if (enable_version_2_draft_08_ != GetQuicReloadableFlag(quic_enable_version_rfcv2) || disable_version_rfcv1_ != GetQuicReloadableFlag(quic_disable_version_rfcv1) || disable_version_draft_29_ != GetQuicReloadableFlag(quic_disable_version_draft_29) || disable_version_q046_ != GetQuicReloadableFlag(quic_disable_version_q046)) { enable_version_2_draft_08_ = GetQuicReloadableFlag(quic_enable_version_rfcv2); disable_version_rfcv1_ = GetQuicReloadableFlag(quic_disable_version_rfcv1); disable_version_draft_29_ = GetQuicReloadableFlag(quic_disable_version_draft_29); disable_version_q046_ = GetQuicReloadableFlag(quic_disable_version_q046); RefilterSupportedVersions(); } } void QuicVersionManager::RefilterSupportedVersions() { filtered_supported_versions_ = FilterSupportedVersions(allowed_supported_versions_); filtered_supported_versions_with_http3_.clear(); filtered_transport_versions_.clear(); filtered_supported_alpns_.clear(); for (const ParsedQuicVersion& version : filtered_supported_versions_) { auto transport_version = version.transport_version; if (std::find(filtered_transport_versions_.begin(), filtered_transport_versions_.end(), transport_version) == filtered_transport_versions_.end()) { filtered_transport_versions_.push_back(transport_version); } if (version.UsesHttp3()) { filtered_supported_versions_with_http3_.push_back(version); } if (std::find(filtered_supported_alpns_.begin(), filtered_supported_alpns_.end(), AlpnForVersion(version)) == filtered_supported_alpns_.end()) { filtered_supported_alpns_.emplace_back(AlpnForVersion(version)); } } } void QuicVersionManager::AddCustomAlpn(const std::string& alpn) { filtered_supported_alpns_.push_back(alpn); } }
#include "quiche/quic/core/quic_version_manager.h" #include "absl/base/macros.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" using ::testing::ElementsAre; namespace quic { namespace test { namespace { class QuicVersionManagerTest : public QuicTest {}; TEST_F(QuicVersionManagerTest, QuicVersionManager) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } QuicDisableVersion(ParsedQuicVersion::RFCv2()); QuicDisableVersion(ParsedQuicVersion::RFCv1()); QuicDisableVersion(ParsedQuicVersion::Draft29()); QuicVersionManager manager(AllSupportedVersions()); ParsedQuicVersionVector expected_parsed_versions; expected_parsed_versions.push_back(ParsedQuicVersion::Q046()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_TRUE(manager.GetSupportedVersionsWithOnlyHttp3().empty()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-Q046")); QuicEnableVersion(ParsedQuicVersion::Draft29()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::Draft29()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(1u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-29", "h3-Q046")); QuicEnableVersion(ParsedQuicVersion::RFCv1()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::RFCv1()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(2u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3", "h3-29", "h3-Q046")); QuicEnableVersion(ParsedQuicVersion::RFCv2()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::RFCv2()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(3u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3", "h3-29", "h3-Q046")); } } } }
229
cpp
google/quiche
quic_error_codes
quiche/quic/core/quic_error_codes.cc
quiche/quic/core/quic_error_codes_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_ERROR_CODES_H_ #define QUICHE_QUIC_CORE_QUIC_ERROR_CODES_H_ #include <cstdint> #include <limits> #include <string> #include "quiche/quic/platform/api/quic_export.h" namespace quic { enum QuicRstStreamErrorCode : uint32_t { QUIC_STREAM_NO_ERROR = 0, QUIC_ERROR_PROCESSING_STREAM = 1, QUIC_MULTIPLE_TERMINATION_OFFSETS = 2, QUIC_BAD_APPLICATION_PAYLOAD = 3, QUIC_STREAM_CONNECTION_ERROR = 4, QUIC_STREAM_PEER_GOING_AWAY = 5, QUIC_STREAM_CANCELLED = 6, QUIC_RST_ACKNOWLEDGEMENT = 7, QUIC_REFUSED_STREAM = 8, QUIC_INVALID_PROMISE_URL = 9, QUIC_UNAUTHORIZED_PROMISE_URL = 10, QUIC_DUPLICATE_PROMISE_URL = 11, QUIC_PROMISE_VARY_MISMATCH = 12, QUIC_INVALID_PROMISE_METHOD = 13, QUIC_PUSH_STREAM_TIMED_OUT = 14, QUIC_HEADERS_TOO_LARGE = 15, QUIC_STREAM_TTL_EXPIRED = 16, QUIC_DATA_AFTER_CLOSE_OFFSET = 17, QUIC_STREAM_GENERAL_PROTOCOL_ERROR = 18, QUIC_STREAM_INTERNAL_ERROR = 19, QUIC_STREAM_STREAM_CREATION_ERROR = 20, QUIC_STREAM_CLOSED_CRITICAL_STREAM = 21, QUIC_STREAM_FRAME_UNEXPECTED = 22, QUIC_STREAM_FRAME_ERROR = 23, QUIC_STREAM_EXCESSIVE_LOAD = 24, QUIC_STREAM_ID_ERROR = 25, QUIC_STREAM_SETTINGS_ERROR = 26, QUIC_STREAM_MISSING_SETTINGS = 27, QUIC_STREAM_REQUEST_REJECTED = 28, QUIC_STREAM_REQUEST_INCOMPLETE = 29, QUIC_STREAM_CONNECT_ERROR = 30, QUIC_STREAM_VERSION_FALLBACK = 31, QUIC_STREAM_DECOMPRESSION_FAILED = 32, QUIC_STREAM_ENCODER_STREAM_ERROR = 33, QUIC_STREAM_DECODER_STREAM_ERROR = 34, QUIC_STREAM_UNKNOWN_APPLICATION_ERROR_CODE = 35, QUIC_STREAM_WEBTRANSPORT_SESSION_GONE = 36, QUIC_STREAM_WEBTRANSPORT_BUFFERED_STREAMS_LIMIT_EXCEEDED = 37, QUIC_APPLICATION_DONE_WITH_STREAM = 38, QUIC_STREAM_LAST_ERROR = 39, }; static_assert(static_cast<int>(QUIC_STREAM_LAST_ERROR) <= std::numeric_limits<uint8_t>::max(), "QuicRstStreamErrorCode exceeds single octet"); enum QuicErrorCode : uint32_t { QUIC_NO_ERROR = 0, QUIC_INTERNAL_ERROR = 1, QUIC_STREAM_DATA_AFTER_TERMINATION = 2, QUIC_INVALID_PACKET_HEADER = 3, QUIC_INVALID_FRAME_DATA = 4, QUIC_MISSING_PAYLOAD = 48, QUIC_INVALID_FEC_DATA = 5, QUIC_INVALID_STREAM_DATA = 46, QUIC_OVERLAPPING_STREAM_DATA = 87, QUIC_UNENCRYPTED_STREAM_DATA = 61, QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA = 88, QUIC_MAYBE_CORRUPTED_MEMORY = 89, QUIC_UNENCRYPTED_FEC_DATA = 77, QUIC_INVALID_RST_STREAM_DATA = 6, QUIC_INVALID_CONNECTION_CLOSE_DATA = 7, QUIC_INVALID_GOAWAY_DATA = 8, QUIC_INVALID_WINDOW_UPDATE_DATA = 57, QUIC_INVALID_BLOCKED_DATA = 58, QUIC_INVALID_STOP_WAITING_DATA = 60, QUIC_INVALID_PATH_CLOSE_DATA = 78, QUIC_INVALID_ACK_DATA = 9, QUIC_INVALID_MESSAGE_DATA = 112, QUIC_INVALID_VERSION_NEGOTIATION_PACKET = 10, QUIC_INVALID_PUBLIC_RST_PACKET = 11, QUIC_DECRYPTION_FAILURE = 12, QUIC_ENCRYPTION_FAILURE = 13, QUIC_PACKET_TOO_LARGE = 14, QUIC_PEER_GOING_AWAY = 16, QUIC_INVALID_STREAM_ID = 17, QUIC_INVALID_PRIORITY = 49, QUIC_TOO_MANY_OPEN_STREAMS = 18, QUIC_TOO_MANY_AVAILABLE_STREAMS = 76, QUIC_PUBLIC_RESET = 19, QUIC_INVALID_VERSION = 20, QUIC_PACKET_WRONG_VERSION = 212, QUIC_INVALID_HEADER_ID = 22, QUIC_INVALID_NEGOTIATED_VALUE = 23, QUIC_DECOMPRESSION_FAILURE = 24, QUIC_NETWORK_IDLE_TIMEOUT = 25, QUIC_HANDSHAKE_TIMEOUT = 67, QUIC_ERROR_MIGRATING_ADDRESS = 26, QUIC_ERROR_MIGRATING_PORT = 86, QUIC_PACKET_WRITE_ERROR = 27, QUIC_PACKET_READ_ERROR = 51, QUIC_EMPTY_STREAM_FRAME_NO_FIN = 50, QUIC_INVALID_HEADERS_STREAM_DATA = 56, QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE = 97, QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA = 59, QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA = 63, QUIC_FLOW_CONTROL_INVALID_WINDOW = 64, QUIC_CONNECTION_IP_POOLED = 62, QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS = 68, QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS = 69, QUIC_CONNECTION_CANCELLED = 70, QUIC_BAD_PACKET_LOSS_RATE = 71, QUIC_PUBLIC_RESETS_POST_HANDSHAKE = 73, QUIC_FAILED_TO_SERIALIZE_PACKET = 75, QUIC_TOO_MANY_RTOS = 85, QUIC_HANDSHAKE_FAILED = 28, QUIC_HANDSHAKE_FAILED_PACKETS_BUFFERED_TOO_LONG = 214, QUIC_CRYPTO_TAGS_OUT_OF_ORDER = 29, QUIC_CRYPTO_TOO_MANY_ENTRIES = 30, QUIC_CRYPTO_INVALID_VALUE_LENGTH = 31, QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE = 32, QUIC_INVALID_CRYPTO_MESSAGE_TYPE = 33, QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER = 34, QUIC_INVALID_CHANNEL_ID_SIGNATURE = 52, QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND = 35, QUIC_CRYPTO_MESSAGE_PARAMETER_NO_OVERLAP = 36, QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND = 37, QUIC_UNSUPPORTED_PROOF_DEMAND = 94, QUIC_CRYPTO_INTERNAL_ERROR = 38, QUIC_CRYPTO_VERSION_NOT_SUPPORTED = 39, QUIC_CRYPTO_NO_SUPPORT = 40, QUIC_CRYPTO_TOO_MANY_REJECTS = 41, QUIC_PROOF_INVALID = 42, QUIC_CRYPTO_DUPLICATE_TAG = 43, QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT = 44, QUIC_CRYPTO_SERVER_CONFIG_EXPIRED = 45, QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED = 53, QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO = 54, QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE = 65, QUIC_CRYPTO_CHLO_TOO_LARGE = 90, QUIC_VERSION_NEGOTIATION_MISMATCH = 55, QUIC_BAD_MULTIPATH_FLAG = 79, QUIC_MULTIPATH_PATH_DOES_NOT_EXIST = 91, QUIC_MULTIPATH_PATH_NOT_ACTIVE = 92, QUIC_IP_ADDRESS_CHANGED = 80, QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS = 81, QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES = 82, QUIC_CONNECTION_MIGRATION_NO_NEW_NETWORK = 83, QUIC_CONNECTION_MIGRATION_NON_MIGRATABLE_STREAM = 84, QUIC_CONNECTION_MIGRATION_DISABLED_BY_CONFIG = 99, QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR = 100, QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED = 111, QUIC_PEER_PORT_CHANGE_HANDSHAKE_UNCONFIRMED = 194, QUIC_TOO_MANY_STREAM_DATA_INTERVALS = 93, QUIC_STREAM_SEQUENCER_INVALID_STATE = 95, QUIC_TOO_MANY_SESSIONS_ON_SERVER = 96, QUIC_STREAM_LENGTH_OVERFLOW = 98, QUIC_INVALID_MAX_DATA_FRAME_DATA = 102, QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA = 103, QUIC_MAX_STREAMS_DATA = 104, QUIC_STREAMS_BLOCKED_DATA = 105, QUIC_INVALID_STREAM_BLOCKED_DATA = 106, QUIC_INVALID_NEW_CONNECTION_ID_DATA = 107, QUIC_CONNECTION_ID_LIMIT_ERROR = 203, QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE = 204, QUIC_INVALID_STOP_SENDING_FRAME_DATA = 108, QUIC_INVALID_PATH_CHALLENGE_DATA = 109, QUIC_INVALID_PATH_RESPONSE_DATA = 110, IETF_QUIC_PROTOCOL_VIOLATION = 113, QUIC_INVALID_NEW_TOKEN = 114, QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM = 115, QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM = 116, QUIC_INVALID_RETIRE_CONNECTION_ID_DATA = 117, QUIC_STREAMS_BLOCKED_ERROR = 118, QUIC_MAX_STREAMS_ERROR = 119, QUIC_HTTP_DECODER_ERROR = 120, QUIC_STALE_CONNECTION_CANCELLED = 121, QUIC_IETF_GQUIC_ERROR_MISSING = 122, QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM = 123, QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES = 124, QUIC_TRANSPORT_INVALID_CLIENT_INDICATION = 125, QUIC_QPACK_DECOMPRESSION_FAILED = 126, QUIC_QPACK_ENCODER_STREAM_ERROR = 127, QUIC_QPACK_DECODER_STREAM_ERROR = 128, QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE = 174, QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG = 175, QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR = 176, QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY = 177, QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_STATIC = 178, QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX = 179, QUIC_QPACK_ENCODER_STREAM_INSERTION_DYNAMIC_ENTRY_NOT_FOUND = 180, QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_DYNAMIC = 181, QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL = 182, QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX = 183, QUIC_QPACK_ENCODER_STREAM_DUPLICATE_DYNAMIC_ENTRY_NOT_FOUND = 184, QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY = 185, QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE = 186, QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT = 187, QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW = 188, QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT = 189, QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT = 190, QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET = 129, QUIC_STREAM_MULTIPLE_OFFSET = 130, QUIC_HTTP_FRAME_TOO_LARGE = 131, QUIC_HTTP_FRAME_ERROR = 132, QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM = 133, QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM = 134, QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM = 151, QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_CONTROL_STREAM = 152, QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM = 153, QUIC_HTTP_SERVER_INITIATED_BIDIRECTIONAL_STREAM = 154, QUIC_HTTP_STREAM_WRONG_DIRECTION = 155, QUIC_HTTP_CLOSED_CRITICAL_STREAM = 156, QUIC_HTTP_MISSING_SETTINGS_FRAME = 157, QUIC_HTTP_DUPLICATE_SETTING_IDENTIFIER = 158, QUIC_HTTP_INVALID_MAX_PUSH_ID = 159, QUIC_HTTP_STREAM_LIMIT_TOO_LOW = 160, QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH = 164, QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH = 165, QUIC_HTTP_GOAWAY_INVALID_STREAM_ID = 166, QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS = 167, QUIC_HTTP_RECEIVE_SPDY_SETTING = 169, QUIC_HTTP_RECEIVE_SPDY_FRAME = 171, QUIC_HTTP_RECEIVE_SERVER_PUSH = 205, QUIC_HTTP_INVALID_SETTING_VALUE = 207, QUIC_HPACK_INDEX_VARINT_ERROR = 135, QUIC_HPACK_NAME_LENGTH_VARINT_ERROR = 136, QUIC_HPACK_VALUE_LENGTH_VARINT_ERROR = 137, QUIC_HPACK_NAME_TOO_LONG = 138, QUIC_HPACK_VALUE_TOO_LONG = 139, QUIC_HPACK_NAME_HUFFMAN_ERROR = 140, QUIC_HPACK_VALUE_HUFFMAN_ERROR = 141, QUIC_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE = 142, QUIC_HPACK_INVALID_INDEX = 143, QUIC_HPACK_INVALID_NAME_INDEX = 144, QUIC_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED = 145, QUIC_HPACK_INITIAL_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK = 146, QUIC_HPACK_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING = 147, QUIC_HPACK_TRUNCATED_BLOCK = 148, QUIC_HPACK_FRAGMENT_TOO_LONG = 149, QUIC_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT = 150, QUIC_ZERO_RTT_UNRETRANSMITTABLE = 161, QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED = 162, QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED = 163, QUIC_SILENT_IDLE_TIMEOUT = 168, QUIC_MISSING_WRITE_KEYS = 170, QUIC_KEY_UPDATE_ERROR = 172, QUIC_AEAD_LIMIT_REACHED = 173, QUIC_MAX_AGE_TIMEOUT = 191, QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER = 192, QUIC_INVALID_PRIORITY_UPDATE = 193, QUIC_TLS_BAD_CERTIFICATE = 195, QUIC_TLS_UNSUPPORTED_CERTIFICATE = 196, QUIC_TLS_CERTIFICATE_REVOKED = 197, QUIC_TLS_CERTIFICATE_EXPIRED = 198, QUIC_TLS_CERTIFICATE_UNKNOWN = 199, QUIC_TLS_INTERNAL_ERROR = 200, QUIC_TLS_UNRECOGNIZED_NAME = 201, QUIC_TLS_CERTIFICATE_REQUIRED = 202, QUIC_INVALID_CHARACTER_IN_FIELD_VALUE = 206, QUIC_TLS_UNEXPECTED_KEYING_MATERIAL_EXPORT_LABEL = 208, QUIC_TLS_KEYING_MATERIAL_EXPORTS_MISMATCH = 209, QUIC_TLS_KEYING_MATERIAL_EXPORT_NOT_AVAILABLE = 210, QUIC_UNEXPECTED_DATA_BEFORE_ENCRYPTION_ESTABLISHED = 211, QUIC_SERVER_UNHEALTHY = 213, QUIC_LAST_ERROR = 215, }; static_assert(static_cast<uint64_t>(QUIC_LAST_ERROR) <= static_cast<uint64_t>(std::numeric_limits<uint32_t>::max()), "QuicErrorCode exceeds four octets"); enum class QuicHttp3ErrorCode { HTTP3_NO_ERROR = 0x100, GENERAL_PROTOCOL_ERROR = 0x101, INTERNAL_ERROR = 0x102, STREAM_CREATION_ERROR = 0x103, CLOSED_CRITICAL_STREAM = 0x104, FRAME_UNEXPECTED = 0x105, FRAME_ERROR = 0x106, EXCESSIVE_LOAD = 0x107, ID_ERROR = 0x108, SETTINGS_ERROR = 0x109, MISSING_SETTINGS = 0x10A, REQUEST_REJECTED = 0x10B, REQUEST_CANCELLED = 0x10C, REQUEST_INCOMPLETE = 0x10D, MESSAGE_ERROR = 0x10E, CONNECT_ERROR = 0x10F, VERSION_FALLBACK = 0x110, }; enum class QuicHttpQpackErrorCode { DECOMPRESSION_FAILED = 0x200, ENCODER_STREAM_ERROR = 0x201, DECODER_STREAM_ERROR = 0x202 }; class QUICHE_EXPORT QuicResetStreamError { public: static QuicResetStreamError FromInternal(QuicRstStreamErrorCode code); static QuicResetStreamError FromIetf(uint64_t code); static QuicResetStreamError FromIetf(QuicHttp3ErrorCode code); static QuicResetStreamError FromIetf(QuicHttpQpackErrorCode code); static QuicResetStreamError NoError() { return FromInternal(QUIC_STREAM_NO_ERROR); } QuicResetStreamError(QuicRstStreamErrorCode internal_code, uint64_t ietf_application_code) : internal_code_(internal_code), ietf_application_code_(ietf_application_code) {} QuicRstStreamErrorCode internal_code() const { return internal_code_; } uint64_t ietf_application_code() const { return ietf_application_code_; } bool operator==(const QuicResetStreamError& other) const { return internal_code() == other.internal_code() && ietf_application_code() == other.ietf_application_code(); } bool ok() const { return internal_code() == QUIC_STREAM_NO_ERROR; } private: QuicRstStreamErrorCode internal_code_; uint64_t ietf_application_code_; }; QUICHE_EXPORT QuicErrorCode TlsAlertToQuicErrorCode(uint8_t desc); QUICHE_EXPORT const char* QuicRstStreamErrorCodeToString( QuicRstStreamErrorCode error); QUICHE_EXPORT const char* QuicErrorCodeToString(QuicErrorCode error); enum QuicIetfTransportErrorCodes : uint64_t { NO_IETF_QUIC_ERROR = 0x0, INTERNAL_ERROR = 0x1, SERVER_BUSY_ERROR = 0x2, FLOW_CONTROL_ERROR = 0x3, STREAM_LIMIT_ERROR = 0x4, STREAM_STATE_ERROR = 0x5, FINAL_SIZE_ERROR = 0x6, FRAME_ENCODING_ERROR = 0x7, TRANSPORT_PARAMETER_ERROR = 0x8, CONNECTION_ID_LIMIT_ERROR = 0x9, PROTOCOL_VIOLATION = 0xA, INVALID_TOKEN = 0xB, CRYPTO_BUFFER_EXCEEDED = 0xD, KEY_UPDATE_ERROR = 0xE, AEAD_LIMIT_REACHED = 0xF, CRYPTO_ERROR_FIRST = 0x100, CRYPTO_ERROR_LAST = 0x1FF, }; QUICHE_EXPORT std::string QuicIetfTransportErrorCodeString( QuicIetfTransportErrorCodes c); QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const QuicIetfTransportErrorCodes& c);
#include "quiche/quic/core/quic_error_codes.h" #include <cstdint> #include <string> #include "openssl/ssl.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { using QuicErrorCodesTest = QuicTest; TEST_F(QuicErrorCodesTest, QuicErrorCodeToString) { EXPECT_STREQ("QUIC_NO_ERROR", QuicErrorCodeToString(QUIC_NO_ERROR)); } TEST_F(QuicErrorCodesTest, QuicIetfTransportErrorCodeString) { EXPECT_EQ("CRYPTO_ERROR(missing extension)", QuicIetfTransportErrorCodeString( static_cast<quic::QuicIetfTransportErrorCodes>( CRYPTO_ERROR_FIRST + SSL_AD_MISSING_EXTENSION))); EXPECT_EQ("NO_IETF_QUIC_ERROR", QuicIetfTransportErrorCodeString(NO_IETF_QUIC_ERROR)); EXPECT_EQ("INTERNAL_ERROR", QuicIetfTransportErrorCodeString(INTERNAL_ERROR)); EXPECT_EQ("SERVER_BUSY_ERROR", QuicIetfTransportErrorCodeString(SERVER_BUSY_ERROR)); EXPECT_EQ("FLOW_CONTROL_ERROR", QuicIetfTransportErrorCodeString(FLOW_CONTROL_ERROR)); EXPECT_EQ("STREAM_LIMIT_ERROR", QuicIetfTransportErrorCodeString(STREAM_LIMIT_ERROR)); EXPECT_EQ("STREAM_STATE_ERROR", QuicIetfTransportErrorCodeString(STREAM_STATE_ERROR)); EXPECT_EQ("FINAL_SIZE_ERROR", QuicIetfTransportErrorCodeString(FINAL_SIZE_ERROR)); EXPECT_EQ("FRAME_ENCODING_ERROR", QuicIetfTransportErrorCodeString(FRAME_ENCODING_ERROR)); EXPECT_EQ("TRANSPORT_PARAMETER_ERROR", QuicIetfTransportErrorCodeString(TRANSPORT_PARAMETER_ERROR)); EXPECT_EQ("CONNECTION_ID_LIMIT_ERROR", QuicIetfTransportErrorCodeString(CONNECTION_ID_LIMIT_ERROR)); EXPECT_EQ("PROTOCOL_VIOLATION", QuicIetfTransportErrorCodeString(PROTOCOL_VIOLATION)); EXPECT_EQ("INVALID_TOKEN", QuicIetfTransportErrorCodeString(INVALID_TOKEN)); EXPECT_EQ("CRYPTO_BUFFER_EXCEEDED", QuicIetfTransportErrorCodeString(CRYPTO_BUFFER_EXCEEDED)); EXPECT_EQ("KEY_UPDATE_ERROR", QuicIetfTransportErrorCodeString(KEY_UPDATE_ERROR)); EXPECT_EQ("AEAD_LIMIT_REACHED", QuicIetfTransportErrorCodeString(AEAD_LIMIT_REACHED)); EXPECT_EQ("Unknown(1024)", QuicIetfTransportErrorCodeString( static_cast<quic::QuicIetfTransportErrorCodes>(0x400))); } TEST_F(QuicErrorCodesTest, QuicErrorCodeToTransportErrorCode) { for (uint32_t internal_error_code = 0; internal_error_code < QUIC_LAST_ERROR; ++internal_error_code) { std::string internal_error_code_string = QuicErrorCodeToString(static_cast<QuicErrorCode>(internal_error_code)); if (internal_error_code_string == "INVALID_ERROR_CODE") { continue; } QuicErrorCodeToIetfMapping ietf_error_code = QuicErrorCodeToTransportErrorCode( static_cast<QuicErrorCode>(internal_error_code)); if (ietf_error_code.is_transport_close) { QuicIetfTransportErrorCodes transport_error_code = static_cast<QuicIetfTransportErrorCodes>(ietf_error_code.error_code); bool is_transport_crypto_error_code = transport_error_code >= 0x100 && transport_error_code <= 0x1ff; if (is_transport_crypto_error_code) { EXPECT_EQ( internal_error_code, TlsAlertToQuicErrorCode(transport_error_code - CRYPTO_ERROR_FIRST)); } bool is_valid_transport_error_code = transport_error_code <= 0x0f || is_transport_crypto_error_code; EXPECT_TRUE(is_valid_transport_error_code) << internal_error_code_string; } else { uint64_t application_error_code = ietf_error_code.error_code; bool is_valid_http3_error_code = application_error_code >= 0x100 && application_error_code <= 0x110; bool is_valid_qpack_error_code = application_error_code >= 0x200 && application_error_code <= 0x202; EXPECT_TRUE(is_valid_http3_error_code || is_valid_qpack_error_code) << internal_error_code_string; } } } using QuicRstErrorCodesTest = QuicTest; TEST_F(QuicRstErrorCodesTest, QuicRstStreamErrorCodeToString) { EXPECT_STREQ("QUIC_BAD_APPLICATION_PAYLOAD", QuicRstStreamErrorCodeToString(QUIC_BAD_APPLICATION_PAYLOAD)); } TEST_F(QuicRstErrorCodesTest, IetfResetStreamErrorCodeToRstStreamErrorCodeAndBack) { for (uint64_t wire_code : {static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::CLOSED_CRITICAL_STREAM), static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED), static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD), static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::MISSING_SETTINGS), static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED), static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED), static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_INCOMPLETE), static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR), static_cast<uint64_t>(QuicHttp3ErrorCode::VERSION_FALLBACK), static_cast<uint64_t>(QuicHttpQpackErrorCode::DECOMPRESSION_FAILED), static_cast<uint64_t>(QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR), static_cast<uint64_t>(QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)}) { QuicRstStreamErrorCode rst_stream_error_code = IetfResetStreamErrorCodeToRstStreamErrorCode(wire_code); EXPECT_EQ(wire_code, RstStreamErrorCodeToIetfResetStreamErrorCode( rst_stream_error_code)); } } } } }
230
cpp
google/quiche
quic_blocked_writer_list
quiche/quic/core/quic_blocked_writer_list.cc
quiche/quic/core/quic_blocked_writer_list_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_BLOCKED_WRITER_LIST_H_ #define QUICHE_QUIC_CORE_QUIC_BLOCKED_WRITER_LIST_H_ #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { class QUICHE_EXPORT QuicBlockedWriterList { public: void Add(QuicBlockedWriterInterface& blocked_writer); bool Empty() const; bool Remove(QuicBlockedWriterInterface& blocked_writer); void OnWriterUnblocked(); private: using WriteBlockedList = quiche::QuicheLinkedHashMap<QuicBlockedWriterInterface*, bool>; WriteBlockedList write_blocked_list_; }; } #endif #include "quiche/quic/core/quic_blocked_writer_list.h" #include <utility> #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" namespace quic { void QuicBlockedWriterList::Add(QuicBlockedWriterInterface& blocked_writer) { if (!blocked_writer.IsWriterBlocked()) { QUIC_BUG(quic_bug_12724_4) << "Tried to add writer into blocked list when it shouldn't be added"; return; } write_blocked_list_.insert(std::make_pair(&blocked_writer, true)); } bool QuicBlockedWriterList::Empty() const { return write_blocked_list_.empty(); } bool QuicBlockedWriterList::Remove(QuicBlockedWriterInterface& blocked_writer) { return write_blocked_list_.erase(&blocked_writer) != 0; } void QuicBlockedWriterList::OnWriterUnblocked() { const size_t num_blocked_writers_before = write_blocked_list_.size(); WriteBlockedList temp_list; temp_list.swap(write_blocked_list_); QUICHE_DCHECK(write_blocked_list_.empty()); while (!temp_list.empty()) { QuicBlockedWriterInterface* blocked_writer = temp_list.begin()->first; temp_list.erase(temp_list.begin()); blocked_writer->OnBlockedWriterCanWrite(); } const size_t num_blocked_writers_after = write_blocked_list_.size(); if (num_blocked_writers_after != 0) { if (num_blocked_writers_before == num_blocked_writers_after) { QUIC_CODE_COUNT(quic_zero_progress_on_can_write); } else { QUIC_CODE_COUNT(quic_blocked_again_on_can_write); } } } }
#include "quiche/quic/core/quic_blocked_writer_list.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { using testing::Invoke; using testing::Return; namespace { class TestWriter : public QuicBlockedWriterInterface { public: ~TestWriter() override = default; MOCK_METHOD(void, OnBlockedWriterCanWrite, ()); MOCK_METHOD(bool, IsWriterBlocked, (), (const)); }; } TEST(QuicBlockedWriterList, Empty) { QuicBlockedWriterList list; EXPECT_TRUE(list.Empty()); } TEST(QuicBlockedWriterList, NotEmpty) { QuicBlockedWriterList list; testing::StrictMock<TestWriter> writer1; EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); EXPECT_FALSE(list.Empty()); list.Remove(writer1); EXPECT_TRUE(list.Empty()); } TEST(QuicBlockedWriterList, OnWriterUnblocked) { QuicBlockedWriterList list; testing::StrictMock<TestWriter> writer1; EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); EXPECT_CALL(writer1, OnBlockedWriterCanWrite()); list.OnWriterUnblocked(); EXPECT_TRUE(list.Empty()); } TEST(QuicBlockedWriterList, OnWriterUnblockedInOrder) { QuicBlockedWriterList list; testing::StrictMock<TestWriter> writer1; testing::StrictMock<TestWriter> writer2; testing::StrictMock<TestWriter> writer3; EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); list.Add(writer2); list.Add(writer3); testing::InSequence s; EXPECT_CALL(writer1, OnBlockedWriterCanWrite()); EXPECT_CALL(writer2, OnBlockedWriterCanWrite()); EXPECT_CALL(writer3, OnBlockedWriterCanWrite()); list.OnWriterUnblocked(); EXPECT_TRUE(list.Empty()); } TEST(QuicBlockedWriterList, OnWriterUnblockedInOrderAfterReinsertion) { QuicBlockedWriterList list; testing::StrictMock<TestWriter> writer1; testing::StrictMock<TestWriter> writer2; testing::StrictMock<TestWriter> writer3; EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); list.Add(writer2); list.Add(writer3); EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); testing::InSequence s; EXPECT_CALL(writer1, OnBlockedWriterCanWrite()); EXPECT_CALL(writer2, OnBlockedWriterCanWrite()); EXPECT_CALL(writer3, OnBlockedWriterCanWrite()); list.OnWriterUnblocked(); EXPECT_TRUE(list.Empty()); } TEST(QuicBlockedWriterList, OnWriterUnblockedThenBlocked) { QuicBlockedWriterList list; testing::StrictMock<TestWriter> writer1; testing::StrictMock<TestWriter> writer2; testing::StrictMock<TestWriter> writer3; EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true)); list.Add(writer1); list.Add(writer2); list.Add(writer3); EXPECT_CALL(writer1, OnBlockedWriterCanWrite()); EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true)); EXPECT_CALL(writer2, OnBlockedWriterCanWrite()).WillOnce(Invoke([&]() { list.Add(writer2); })); EXPECT_CALL(writer3, OnBlockedWriterCanWrite()); list.OnWriterUnblocked(); EXPECT_FALSE(list.Empty()); EXPECT_CALL(writer2, OnBlockedWriterCanWrite()); list.OnWriterUnblocked(); EXPECT_TRUE(list.Empty()); } }
231
cpp
google/quiche
quic_data_writer
quiche/quic/core/quic_data_writer.cc
quiche/quic/core/quic_data_writer_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_DATA_WRITER_H_ #define QUICHE_QUIC_CORE_QUIC_DATA_WRITER_H_ #include <cstddef> #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_endian.h" namespace quic { class QUICHE_EXPORT QuicDataWriter : public quiche::QuicheDataWriter { public: QuicDataWriter(size_t size, char* buffer); QuicDataWriter(size_t size, char* buffer, quiche::Endianness endianness); QuicDataWriter(const QuicDataWriter&) = delete; QuicDataWriter& operator=(const QuicDataWriter&) = delete; ~QuicDataWriter(); bool WriteUFloat16(uint64_t value); bool WriteConnectionId(QuicConnectionId connection_id); bool WriteLengthPrefixedConnectionId(QuicConnectionId connection_id); bool WriteRandomBytes(QuicRandom* random, size_t length); bool WriteInsecureRandomBytes(QuicRandom* random, size_t length); }; } #endif #include "quiche/quic/core/quic_data_writer.h" #include <algorithm> #include <limits> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_endian.h" namespace quic { QuicDataWriter::QuicDataWriter(size_t size, char* buffer) : quiche::QuicheDataWriter(size, buffer) {} QuicDataWriter::QuicDataWriter(size_t size, char* buffer, quiche::Endianness endianness) : quiche::QuicheDataWriter(size, buffer, endianness) {} QuicDataWriter::~QuicDataWriter() {} bool QuicDataWriter::WriteUFloat16(uint64_t value) { uint16_t result; if (value < (UINT64_C(1) << kUFloat16MantissaEffectiveBits)) { result = static_cast<uint16_t>(value); } else if (value >= kUFloat16MaxValue) { result = std::numeric_limits<uint16_t>::max(); } else { uint16_t exponent = 0; for (uint16_t offset = 16; offset > 0; offset /= 2) { if (value >= (UINT64_C(1) << (kUFloat16MantissaBits + offset))) { exponent += offset; value >>= offset; } } QUICHE_DCHECK_GE(exponent, 1); QUICHE_DCHECK_LE(exponent, kUFloat16MaxExponent); QUICHE_DCHECK_GE(value, UINT64_C(1) << kUFloat16MantissaBits); QUICHE_DCHECK_LT(value, UINT64_C(1) << kUFloat16MantissaEffectiveBits); result = static_cast<uint16_t>(value + (exponent << kUFloat16MantissaBits)); } if (endianness() == quiche::NETWORK_BYTE_ORDER) { result = quiche::QuicheEndian::HostToNet16(result); } return WriteBytes(&result, sizeof(result)); } bool QuicDataWriter::WriteConnectionId(QuicConnectionId connection_id) { if (connection_id.IsEmpty()) { return true; } return WriteBytes(connection_id.data(), connection_id.length()); } bool QuicDataWriter::WriteLengthPrefixedConnectionId( QuicConnectionId connection_id) { return WriteUInt8(connection_id.length()) && WriteConnectionId(connection_id); } bool QuicDataWriter::WriteRandomBytes(QuicRandom* random, size_t length) { char* dest = BeginWrite(length); if (!dest) { return false; } random->RandBytes(dest, length); IncreaseLength(length); return true; } bool QuicDataWriter::WriteInsecureRandomBytes(QuicRandom* random, size_t length) { char* dest = BeginWrite(length); if (!dest) { return false; } random->InsecureRandBytes(dest, length); IncreaseLength(length); return true; } }
#include "quiche/quic/core/quic_data_writer.h" #include <cstdint> #include <cstring> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { char* AsChars(unsigned char* data) { return reinterpret_cast<char*>(data); } struct TestParams { explicit TestParams(quiche::Endianness endianness) : endianness(endianness) {} quiche::Endianness endianness; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( (p.endianness == quiche::NETWORK_BYTE_ORDER ? "Network" : "Host"), "ByteOrder"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (quiche::Endianness endianness : {quiche::NETWORK_BYTE_ORDER, quiche::HOST_BYTE_ORDER}) { params.push_back(TestParams(endianness)); } return params; } class QuicDataWriterTest : public QuicTestWithParam<TestParams> {}; INSTANTIATE_TEST_SUITE_P(QuicDataWriterTests, QuicDataWriterTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicDataWriterTest, SanityCheckUFloat16Consts) { EXPECT_EQ(30, kUFloat16MaxExponent); EXPECT_EQ(11, kUFloat16MantissaBits); EXPECT_EQ(12, kUFloat16MantissaEffectiveBits); EXPECT_EQ(UINT64_C(0x3FFC0000000), kUFloat16MaxValue); } TEST_P(QuicDataWriterTest, WriteUFloat16) { struct TestCase { uint64_t decoded; uint16_t encoded; }; TestCase test_cases[] = { {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {15, 15}, {31, 31}, {42, 42}, {123, 123}, {1234, 1234}, {2046, 2046}, {2047, 2047}, {2048, 2048}, {2049, 2049}, {4094, 4094}, {4095, 4095}, {4096, 4096}, {4097, 4096}, {4098, 4097}, {4099, 4097}, {4100, 4098}, {4101, 4098}, {8190, 6143}, {8191, 6143}, {8192, 6144}, {8193, 6144}, {8194, 6144}, {8195, 6144}, {8196, 6145}, {8197, 6145}, {0x7FF8000, 0x87FF}, {0x7FFFFFF, 0x87FF}, {0x8000000, 0x8800}, {0xFFF0000, 0x8FFF}, {0xFFFFFFF, 0x8FFF}, {0x10000000, 0x9000}, {0x1FFFFFFFFFE, 0xF7FF}, {0x1FFFFFFFFFF, 0xF7FF}, {0x20000000000, 0xF800}, {0x20000000001, 0xF800}, {0x2003FFFFFFE, 0xF800}, {0x2003FFFFFFF, 0xF800}, {0x20040000000, 0xF801}, {0x20040000001, 0xF801}, {0x3FF80000000, 0xFFFE}, {0x3FFBFFFFFFF, 0xFFFE}, {0x3FFC0000000, 0xFFFF}, {0x3FFC0000001, 0xFFFF}, {0x3FFFFFFFFFF, 0xFFFF}, {0x40000000000, 0xFFFF}, {0xFFFFFFFFFFFFFFFF, 0xFFFF}, }; int num_test_cases = sizeof(test_cases) / sizeof(test_cases[0]); for (int i = 0; i < num_test_cases; ++i) { char buffer[2]; QuicDataWriter writer(2, buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUFloat16(test_cases[i].decoded)); uint16_t result = *reinterpret_cast<uint16_t*>(writer.data()); if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { result = quiche::QuicheEndian::HostToNet16(result); } EXPECT_EQ(test_cases[i].encoded, result); } } TEST_P(QuicDataWriterTest, ReadUFloat16) { struct TestCase { uint64_t decoded; uint16_t encoded; }; TestCase test_cases[] = { {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {15, 15}, {31, 31}, {42, 42}, {123, 123}, {1234, 1234}, {2046, 2046}, {2047, 2047}, {2048, 2048}, {2049, 2049}, {4094, 4094}, {4095, 4095}, {4096, 4096}, {4098, 4097}, {4100, 4098}, {8190, 6143}, {8192, 6144}, {8196, 6145}, {0x7FF8000, 0x87FF}, {0x8000000, 0x8800}, {0xFFF0000, 0x8FFF}, {0x10000000, 0x9000}, {0x1FFE0000000, 0xF7FF}, {0x20000000000, 0xF800}, {0x20040000000, 0xF801}, {0x3FF80000000, 0xFFFE}, {0x3FFC0000000, 0xFFFF}, }; int num_test_cases = sizeof(test_cases) / sizeof(test_cases[0]); for (int i = 0; i < num_test_cases; ++i) { uint16_t encoded_ufloat = test_cases[i].encoded; if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { encoded_ufloat = quiche::QuicheEndian::HostToNet16(encoded_ufloat); } QuicDataReader reader(reinterpret_cast<char*>(&encoded_ufloat), 2, GetParam().endianness); uint64_t value; EXPECT_TRUE(reader.ReadUFloat16(&value)); EXPECT_EQ(test_cases[i].decoded, value); } } TEST_P(QuicDataWriterTest, RoundTripUFloat16) { uint64_t previous_value = 0; for (uint16_t i = 1; i < 0xFFFF; ++i) { uint16_t read_number = i; if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { read_number = quiche::QuicheEndian::HostToNet16(read_number); } QuicDataReader reader(reinterpret_cast<char*>(&read_number), 2, GetParam().endianness); uint64_t value; EXPECT_TRUE(reader.ReadUFloat16(&value)); if (i < 4097) { EXPECT_EQ(i, value); } EXPECT_LT(previous_value, value); if (i > 2000) { EXPECT_GT(previous_value * 1005, value * 1000); } EXPECT_LT(value, UINT64_C(0x3FFC0000000)); previous_value = value; char buffer[6]; QuicDataWriter writer(6, buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUFloat16(value - 1)); EXPECT_TRUE(writer.WriteUFloat16(value)); EXPECT_TRUE(writer.WriteUFloat16(value + 1)); uint16_t encoded1 = *reinterpret_cast<uint16_t*>(writer.data()); uint16_t encoded2 = *reinterpret_cast<uint16_t*>(writer.data() + 2); uint16_t encoded3 = *reinterpret_cast<uint16_t*>(writer.data() + 4); if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { encoded1 = quiche::QuicheEndian::NetToHost16(encoded1); encoded2 = quiche::QuicheEndian::NetToHost16(encoded2); encoded3 = quiche::QuicheEndian::NetToHost16(encoded3); } EXPECT_EQ(i - 1, encoded1); EXPECT_EQ(i, encoded2); EXPECT_EQ(i < 4096 ? i + 1 : i, encoded3); } } TEST_P(QuicDataWriterTest, WriteConnectionId) { QuicConnectionId connection_id = TestConnectionId(UINT64_C(0x0011223344556677)); char big_endian[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, }; EXPECT_EQ(connection_id.length(), ABSL_ARRAYSIZE(big_endian)); ASSERT_LE(connection_id.length(), 255); char buffer[255]; QuicDataWriter writer(connection_id.length(), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "connection_id", buffer, connection_id.length(), big_endian, connection_id.length()); QuicConnectionId read_connection_id; QuicDataReader reader(buffer, connection_id.length(), GetParam().endianness); EXPECT_TRUE( reader.ReadConnectionId(&read_connection_id, ABSL_ARRAYSIZE(big_endian))); EXPECT_EQ(connection_id, read_connection_id); } TEST_P(QuicDataWriterTest, LengthPrefixedConnectionId) { QuicConnectionId connection_id = TestConnectionId(UINT64_C(0x0011223344556677)); char length_prefixed_connection_id[] = { 0x08, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, }; EXPECT_EQ(ABSL_ARRAYSIZE(length_prefixed_connection_id), kConnectionIdLengthSize + connection_id.length()); char buffer[kConnectionIdLengthSize + 255] = {}; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer); EXPECT_TRUE(writer.WriteLengthPrefixedConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "WriteLengthPrefixedConnectionId", buffer, writer.length(), length_prefixed_connection_id, ABSL_ARRAYSIZE(length_prefixed_connection_id)); memset(buffer, 0, ABSL_ARRAYSIZE(buffer)); QuicDataWriter writer2(ABSL_ARRAYSIZE(buffer), buffer); EXPECT_TRUE(writer2.WriteUInt8(connection_id.length())); EXPECT_TRUE(writer2.WriteConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "Write length then ConnectionId", buffer, writer2.length(), length_prefixed_connection_id, ABSL_ARRAYSIZE(length_prefixed_connection_id)); QuicConnectionId read_connection_id; QuicDataReader reader(buffer, ABSL_ARRAYSIZE(buffer)); EXPECT_TRUE(reader.ReadLengthPrefixedConnectionId(&read_connection_id)); EXPECT_EQ(connection_id, read_connection_id); uint8_t read_connection_id_length2 = 33; QuicConnectionId read_connection_id2; QuicDataReader reader2(buffer, ABSL_ARRAYSIZE(buffer)); ASSERT_TRUE(reader2.ReadUInt8(&read_connection_id_length2)); EXPECT_EQ(connection_id.length(), read_connection_id_length2); EXPECT_TRUE(reader2.ReadConnectionId(&read_connection_id2, read_connection_id_length2)); EXPECT_EQ(connection_id, read_connection_id2); } TEST_P(QuicDataWriterTest, EmptyConnectionIds) { QuicConnectionId empty_connection_id = EmptyQuicConnectionId(); char buffer[2]; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_TRUE(writer.WriteUInt8(1)); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_TRUE(writer.WriteUInt8(2)); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_FALSE(writer.WriteUInt8(3)); EXPECT_EQ(buffer[0], 1); EXPECT_EQ(buffer[1], 2); QuicConnectionId read_connection_id = TestConnectionId(); uint8_t read_byte; QuicDataReader reader(buffer, ABSL_ARRAYSIZE(buffer), GetParam().endianness); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_TRUE(reader.ReadUInt8(&read_byte)); EXPECT_EQ(read_byte, 1); read_connection_id = TestConnectionId(); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_TRUE(reader.ReadUInt8(&read_byte)); EXPECT_EQ(read_byte, 2); read_connection_id = TestConnectionId(); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_FALSE(reader.ReadUInt8(&read_byte)); } TEST_P(QuicDataWriterTest, WriteTag) { char CHLO[] = { 'C', 'H', 'L', 'O', }; const int kBufferLength = sizeof(QuicTag); char buffer[kBufferLength]; QuicDataWriter writer(kBufferLength, buffer, GetParam().endianness); writer.WriteTag(kCHLO); quiche::test::CompareCharArraysWithHexError("CHLO", buffer, kBufferLength, CHLO, kBufferLength); QuicTag read_chlo; QuicDataReader reader(buffer, kBufferLength, GetParam().endianness); reader.ReadTag(&read_chlo); EXPECT_EQ(kCHLO, read_chlo); } TEST_P(QuicDataWriterTest, Write16BitUnsignedIntegers) { char little_endian16[] = {0x22, 0x11}; char big_endian16[] = {0x11, 0x22}; char buffer16[2]; { uint16_t in_memory16 = 0x1122; QuicDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteUInt16(in_memory16); quiche::test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint16_t read_number16; QuicDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadUInt16(&read_number16); EXPECT_EQ(in_memory16, read_number16); } { uint64_t in_memory16 = 0x0000000000001122; QuicDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteBytesToUInt64(2, in_memory16); quiche::test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint64_t read_number16; QuicDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadBytesToUInt64(2, &read_number16); EXPECT_EQ(in_memory16, read_number16); } } TEST_P(QuicDataWriterTest, Write24BitUnsignedIntegers) { char little_endian24[] = {0x33, 0x22, 0x11}; char big_endian24[] = {0x11, 0x22, 0x33}; char buffer24[3]; uint64_t in_memory24 = 0x0000000000112233; QuicDataWriter writer(3, buffer24, GetParam().endianness); writer.WriteBytesToUInt64(3, in_memory24); quiche::test::CompareCharArraysWithHexError( "uint24", buffer24, 3, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian24 : little_endian24, 3); uint64_t read_number24; QuicDataReader reader(buffer24, 3, GetParam().endianness); reader.ReadBytesToUInt64(3, &read_number24); EXPECT_EQ(in_memory24, read_number24); } TEST_P(QuicDataWriterTest, Write32BitUnsignedIntegers) { char little_endian32[] = {0x44, 0x33, 0x22, 0x11}; char big_endian32[] = {0x11, 0x22, 0x33, 0x44}; char buffer32[4]; { uint32_t in_memory32 = 0x11223344; QuicDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteUInt32(in_memory32); quiche::test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint32_t read_number32; QuicDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadUInt32(&read_number32); EXPECT_EQ(in_memory32, read_number32); } { uint64_t in_memory32 = 0x11223344; QuicDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteBytesToUInt64(4, in_memory32); quiche::test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint64_t read_number32; QuicDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadBytesToUInt64(4, &read_number32); EXPECT_EQ(in_memory32, read_number32); } } TEST_P(QuicDataWriterTest, Write40BitUnsignedIntegers) { uint64_t in_memory40 = 0x0000001122334455; char little_endian40[] = {0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian40[] = {0x11, 0x22, 0x33, 0x44, 0x55}; char buffer40[5]; QuicDataWriter writer(5, buffer40, GetParam().endianness); writer.WriteBytesToUInt64(5, in_memory40); quiche::test::CompareCharArraysWithHexError( "uint40", buffer40, 5, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian40 : little_endian40, 5); uint64_t read_number40; QuicDataReader reader(buffer40, 5, GetParam().endianness); reader.ReadBytesToUInt64(5, &read_number40); EXPECT_EQ(in_memory40, read_number40); } TEST_P(QuicDataWriterTest, Write48BitUnsignedIntegers) { uint64_t in_memory48 = 0x0000112233445566; char little_endian48[] = {0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian48[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; char buffer48[6]; QuicDataWriter writer(6, buffer48, GetParam().endianness); writer.WriteBytesToUInt64(6, in_memory48); quiche::test::CompareCharArraysWithHexError( "uint48", buffer48, 6, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian48 : little_endian48, 6); uint64_t read_number48; QuicDataReader reader(buffer48, 6, GetParam().endianness); reader.ReadBytesToUInt64(6., &read_number48); EXPECT_EQ(in_memory48, read_number48); } TEST_P(QuicDataWriterTest, Write56BitUnsignedIntegers) { uint64_t in_memory56 = 0x0011223344556677; char little_endian56[] = {0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian56[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; char buffer56[7]; QuicDataWriter writer(7, buffer56, GetParam().endianness); writer.WriteBytesToUInt64(7, in_memory56); quiche::test::CompareCharArraysWithHexError( "uint56", buffer56, 7, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian56 : little_endian56, 7); uint64_t read_number56; QuicDataReader reader(buffer56, 7, GetParam().endianness); reader.ReadBytesToUInt64(7, &read_number56); EXPECT_EQ(in_memory56, read_number56); } TEST_P(QuicDataWriterTest, Write64BitUnsignedIntegers) { uint64_t in_memory64 = 0x1122334455667788; unsigned char little_endian64[] = {0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; unsigned char big_endian64[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; char buffer64[8]; QuicDataWriter writer(8, buffer64, GetParam().endianness); writer.WriteBytesToUInt64(8, in_memory64); quiche::test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); uint64_t read_number64; QuicDataReader reader(buffer64, 8, GetParam().endianness); reader.ReadBytesToUInt64(8, &read_number64); EXPECT_EQ(in_memory64, read_number64); QuicDataWriter writer2(8, buffer64, GetParam().endianness); writer2.WriteUInt64(in_memory64); quiche::test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); read_number64 = 0u; QuicDataReader reader2(buffer64, 8, GetParam().endianness); reader2.ReadUInt64(&read_number64); EXPECT_EQ(in_memory64, read_number64); } TEST_P(QuicDataWriterTest, WriteIntegers) { char buf[43]; uint8_t i8 = 0x01; uint16_t i16 = 0x0123; uint32_t i32 = 0x01234567; uint64_t i64 = 0x0123456789ABCDEF; QuicDataWriter writer(46, buf, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { switch (i) { case 0u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 1u: EXPECT_TRUE(writer.WriteUInt8(i8)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 2u: EXPECT_TRUE(writer.WriteUInt16(i16)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 3u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 4u: EXPECT_TRUE(writer.WriteUInt32(i32)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 5u: case 6u: case 7u: case 8u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; default: EXPECT_FALSE(writer.WriteBytesToUInt64(i, i64)); } } QuicDataReader reader(buf, 46, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { uint8_t read8; uint16_t read16; uint32_t read32; uint64_t read64; switch (i) { case 0u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0u, read64); break; case 1u: EXPECT_TRUE(reader.ReadUInt8(&read8)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i8, read8); EXPECT_EQ(0xEFu, read64); break; case 2u: EXPECT_TRUE(reader.ReadUInt16(&read16)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i16, read16); EXPECT_EQ(0xCDEFu, read64); break; case 3u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0xABCDEFu, read64); break; case 4u: EXPECT_TRUE(reader.ReadUInt32(&read32)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i32, read32); EXPECT_EQ(0x89ABCDEFu, read64); break; case 5u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x6789ABCDEFu, read64); break; case 6u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x456789ABCDEFu, read64); break; case 7u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x23456789ABCDEFu, read64); break; case 8u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x0123456789ABCDEFu, read64); break; default: EXPECT_FALSE(reader.ReadBytesToUInt64(i, &read64)); } } } TEST_P(QuicDataWriterTest, WriteBytes) { char bytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; char buf[ABSL_ARRAYSIZE(bytes)]; QuicDataWriter writer(ABSL_ARRAYSIZE(buf), buf, GetParam().endianness); EXPECT_TRUE(writer.WriteBytes(bytes, ABSL_ARRAYSIZE(bytes))); for (unsigned int i = 0; i < ABSL_ARRAYSIZE(bytes); ++i) { EXPECT_EQ(bytes[i], buf[i]); } } const int kMultiVarCount = 1000; void EncodeDecodeStreamId(uint64_t value_in) { char buffer[1 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(value_in)); QuicDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); QuicStreamId received_stream_id; uint64_t temp; EXPECT_TRUE(reader.ReadVarInt62(&temp)); received_stream_id = static_cast<QuicStreamId>(temp); EXPECT_EQ(value_in, received_stream_id); } TEST_P(QuicDataWriterTest, StreamId1) { EncodeDecodeStreamId(UINT64_C(0x15)); EncodeDecodeStreamId(UINT64_C(0x1567)); EncodeDecodeStreamId(UINT64_C(0x34567890)); EncodeDecodeStreamId(UINT64_C(0xf4567890)); } TEST_P(QuicDataWriterTest, WriteRandomBytes) { char buffer[20]; char expected[20]; for (size_t i = 0; i < 20; ++i) { expected[i] = 'r'; } MockRandom random; QuicDataWriter writer(20, buffer, GetParam().endianness); EXPECT_FALSE(writer.WriteRandomBytes(&random, 30)); EXPECT_TRUE(writer.WriteRandomBytes(&random, 20)); quiche::test::CompareCharArraysWithHexError("random", buffer, 20, expected, 20); } TEST_P(QuicDataWriterTest, WriteInsecureRandomBytes) { char buffer[20]; char expected[20]; for (size_t i = 0; i < 20; ++i) { expected[i] = 'r'; } MockRandom random; QuicDataWriter writer(20, buffer, GetParam().endianness); EXPECT_FALSE(writer.WriteInsecureRandomBytes(&random, 30)); EXPECT_TRUE(writer.WriteInsecureRandomBytes(&random, 20)); quiche::test::CompareCharArraysWithHexError("random", buffer, 20, expected, 20); } TEST_P(QuicDataWriterTest, PeekVarInt62Length) { char buffer[20]; QuicDataWriter writer(20, buffer, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(50)); QuicDataReader reader(buffer, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(1, reader.PeekVarInt62Length()); char buffer2[20]; QuicDataWriter writer2(20, buffer2, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer2.WriteVarInt62(100)); QuicDataReader reader2(buffer2, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(2, reader2.PeekVarInt62Length()); char buffer3[20]; QuicDataWriter writer3(20, buffer3, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer3.WriteVarInt62(20000)); QuicDataReader reader3(buffer3, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(4, reader3.PeekVarInt62Length()); char buffer4[20]; QuicDataWriter writer4(20, buffer4, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer4.WriteVarInt62(2000000000)); QuicDataReader reader4(buffer4, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(8, reader4.PeekVarInt62Length()); } TEST_P(QuicDataWriterTest, ValidStreamCount) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); QuicDataReader reader(buffer, sizeof(buffer)); const QuicStreamCount write_stream_count = 0xffeeddcc; EXPECT_TRUE(writer.WriteVarInt62(write_stream_count)); QuicStreamCount read_stream_count; uint64_t temp; EXPECT_TRUE(reader.ReadVarInt62(&temp)); read_stream_count = static_cast<QuicStreamId>(temp); EXPECT_EQ(write_stream_count, read_stream_count); } TEST_P(QuicDataWriterTest, Seek) { char buffer[3] = {}; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUInt8(42)); EXPECT_TRUE(writer.Seek(1)); EXPECT_TRUE(writer.WriteUInt8(3)); char expected[] = {42, 0, 3}; for (size_t i = 0; i < ABSL_ARRAYSIZE(expected); ++i) { EXPECT_EQ(buffer[i], expected[i]); } } TEST_P(QuicDataWriterTest, SeekTooFarFails) { char buffer[20]; { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(20)); EXPECT_FALSE(writer.Seek(1)); } { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_FALSE(writer.Seek(100)); } { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(10)); EXPECT_FALSE(writer.Seek(std::numeric_limits<size_t>::max())); } } TEST_P(QuicDataWriterTest, PayloadReads) { char buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; char expected_first_read[4] = {1, 2, 3, 4}; char expected_remaining[12] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; QuicDataReader reader(buffer, sizeof(buffer)); char first_read_buffer[4] = {}; EXPECT_TRUE(reader.ReadBytes(first_read_buffer, sizeof(first_read_buffer))); quiche::test::CompareCharArraysWithHexError( "first read", first_read_buffer, sizeof(first_read_buffer), expected_first_read, sizeof(expected_first_read)); absl::string_view peeked_remaining_payload = reader.PeekRemainingPayload(); quiche::test::CompareCharArraysWithHexError( "peeked_remaining_payload", peeked_remaining_payload.data(), peeked_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); absl::string_view full_payload = reader.FullPayload(); quiche::test::CompareCharArraysWithHexError( "full_payload", full_payload.data(), full_payload.length(), buffer, sizeof(buffer)); absl::string_view read_remaining_payload = reader.ReadRemainingPayload(); quiche::test::CompareCharArraysWithHexError( "read_remaining_payload", read_remaining_payload.data(), read_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); EXPECT_TRUE(reader.IsDoneReading()); absl::string_view full_payload2 = reader.FullPayload(); quiche::test::CompareCharArraysWithHexError( "full_payload2", full_payload2.data(), full_payload2.length(), buffer, sizeof(buffer)); } TEST_P(QuicDataWriterTest, StringPieceVarInt62) { char inner_buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; absl::string_view inner_payload_write(inner_buffer, sizeof(inner_buffer)); char buffer[sizeof(inner_buffer) + sizeof(uint8_t)] = {}; QuicDataWriter writer(sizeof(buffer), buffer); EXPECT_TRUE(writer.WriteStringPieceVarInt62(inner_payload_write)); EXPECT_EQ(0u, writer.remaining()); QuicDataReader reader(buffer, sizeof(buffer)); absl::string_view inner_payload_read; EXPECT_TRUE(reader.ReadStringPieceVarInt62(&inner_payload_read)); quiche::test::CompareCharArraysWithHexError( "inner_payload", inner_payload_write.data(), inner_payload_write.length(), inner_payload_read.data(), inner_payload_read.length()); } } } }
232
cpp
google/quiche
quic_idle_network_detector
quiche/quic/core/quic_idle_network_detector.cc
quiche/quic/core/quic_idle_network_detector_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_IDLE_NETWORK_DETECTOR_H_ #define QUICHE_QUIC_CORE_QUIC_IDLE_NETWORK_DETECTOR_H_ #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace test { class QuicConnectionPeer; class QuicIdleNetworkDetectorTestPeer; } class QUICHE_EXPORT QuicIdleNetworkDetector { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() {} virtual void OnHandshakeTimeout() = 0; virtual void OnIdleNetworkDetected() = 0; }; QuicIdleNetworkDetector(Delegate* delegate, QuicTime now, QuicAlarm* alarm); void OnAlarm(); void SetTimeouts(QuicTime::Delta handshake_timeout, QuicTime::Delta idle_network_timeout); void StopDetection(); void OnPacketSent(QuicTime now, QuicTime::Delta pto_delay); void OnPacketReceived(QuicTime now); void enable_shorter_idle_timeout_on_sent_packet() { shorter_idle_timeout_on_sent_packet_ = true; } QuicTime::Delta handshake_timeout() const { return handshake_timeout_; } QuicTime time_of_last_received_packet() const { return time_of_last_received_packet_; } QuicTime last_network_activity_time() const { return std::max(time_of_last_received_packet_, time_of_first_packet_sent_after_receiving_); } QuicTime::Delta idle_network_timeout() const { return idle_network_timeout_; } QuicTime GetIdleNetworkDeadline() const; private: friend class test::QuicConnectionPeer; friend class test::QuicIdleNetworkDetectorTestPeer; void SetAlarm(); void MaybeSetAlarmOnSentPacket(QuicTime::Delta pto_delay); QuicTime GetBandwidthUpdateDeadline() const; Delegate* delegate_; const QuicTime start_time_; QuicTime::Delta handshake_timeout_; QuicTime time_of_last_received_packet_; QuicTime time_of_first_packet_sent_after_receiving_; QuicTime::Delta idle_network_timeout_; QuicAlarm& alarm_; bool shorter_idle_timeout_on_sent_packet_ = false; bool stopped_ = false; }; } #endif #include "quiche/quic/core/quic_idle_network_detector.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { namespace { } QuicIdleNetworkDetector::QuicIdleNetworkDetector(Delegate* delegate, QuicTime now, QuicAlarm* alarm) : delegate_(delegate), start_time_(now), handshake_timeout_(QuicTime::Delta::Infinite()), time_of_last_received_packet_(now), time_of_first_packet_sent_after_receiving_(QuicTime::Zero()), idle_network_timeout_(QuicTime::Delta::Infinite()), alarm_(*alarm) {} void QuicIdleNetworkDetector::OnAlarm() { if (handshake_timeout_.IsInfinite()) { delegate_->OnIdleNetworkDetected(); return; } if (idle_network_timeout_.IsInfinite()) { delegate_->OnHandshakeTimeout(); return; } if (last_network_activity_time() + idle_network_timeout_ > start_time_ + handshake_timeout_) { delegate_->OnHandshakeTimeout(); return; } delegate_->OnIdleNetworkDetected(); } void QuicIdleNetworkDetector::SetTimeouts( QuicTime::Delta handshake_timeout, QuicTime::Delta idle_network_timeout) { handshake_timeout_ = handshake_timeout; idle_network_timeout_ = idle_network_timeout; SetAlarm(); } void QuicIdleNetworkDetector::StopDetection() { alarm_.PermanentCancel(); handshake_timeout_ = QuicTime::Delta::Infinite(); idle_network_timeout_ = QuicTime::Delta::Infinite(); handshake_timeout_ = QuicTime::Delta::Infinite(); stopped_ = true; } void QuicIdleNetworkDetector::OnPacketSent(QuicTime now, QuicTime::Delta pto_delay) { if (time_of_first_packet_sent_after_receiving_ > time_of_last_received_packet_) { return; } time_of_first_packet_sent_after_receiving_ = std::max(time_of_first_packet_sent_after_receiving_, now); if (shorter_idle_timeout_on_sent_packet_) { MaybeSetAlarmOnSentPacket(pto_delay); return; } SetAlarm(); } void QuicIdleNetworkDetector::OnPacketReceived(QuicTime now) { time_of_last_received_packet_ = std::max(time_of_last_received_packet_, now); SetAlarm(); } void QuicIdleNetworkDetector::SetAlarm() { if (stopped_) { QUIC_BUG(quic_idle_detector_set_alarm_after_stopped) << "SetAlarm called after stopped"; return; } QuicTime new_deadline = QuicTime::Zero(); if (!handshake_timeout_.IsInfinite()) { new_deadline = start_time_ + handshake_timeout_; } if (!idle_network_timeout_.IsInfinite()) { const QuicTime idle_network_deadline = GetIdleNetworkDeadline(); if (new_deadline.IsInitialized()) { new_deadline = std::min(new_deadline, idle_network_deadline); } else { new_deadline = idle_network_deadline; } } alarm_.Update(new_deadline, kAlarmGranularity); } void QuicIdleNetworkDetector::MaybeSetAlarmOnSentPacket( QuicTime::Delta pto_delay) { QUICHE_DCHECK(shorter_idle_timeout_on_sent_packet_); if (!handshake_timeout_.IsInfinite() || !alarm_.IsSet()) { SetAlarm(); return; } const QuicTime deadline = alarm_.deadline(); const QuicTime min_deadline = last_network_activity_time() + pto_delay; if (deadline > min_deadline) { return; } alarm_.Update(min_deadline, kAlarmGranularity); } QuicTime QuicIdleNetworkDetector::GetIdleNetworkDeadline() const { if (idle_network_timeout_.IsInfinite()) { return QuicTime::Zero(); } return last_network_activity_time() + idle_network_timeout_; } }
#include "quiche/quic/core/quic_idle_network_detector.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicIdleNetworkDetectorTestPeer { public: static QuicAlarm& GetAlarm(QuicIdleNetworkDetector* detector) { return detector->alarm_; } }; namespace { class MockDelegate : public QuicIdleNetworkDetector::Delegate { public: MOCK_METHOD(void, OnHandshakeTimeout, (), (override)); MOCK_METHOD(void, OnIdleNetworkDetected, (), (override)); }; class QuicIdleNetworkDetectorTest : public QuicTest { public: QuicIdleNetworkDetectorTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), detector_(&delegate_, clock_.Now() + QuicTimeDelta::FromSeconds(1), &alarms_.idle_network_detector_alarm()) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); alarm_ = static_cast<MockAlarmFactory::TestAlarm*>( &alarms_.idle_network_detector_alarm()); ON_CALL(connection_alarms_delegate_, OnIdleDetectorAlarm()) .WillByDefault([&] { detector_.OnAlarm(); }); } protected: testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; MockClock clock_; QuicIdleNetworkDetector detector_; MockAlarmFactory::TestAlarm* alarm_; }; TEST_F(QuicIdleNetworkDetectorTest, IdleNetworkDetectedBeforeHandshakeCompletes) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(20), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, HandshakeTimeout) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); detector_.OnPacketReceived(clock_.Now()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(15), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); EXPECT_CALL(delegate_, OnHandshakeTimeout()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, IdleNetworkDetectedAfterHandshakeCompletes) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(20), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketReceived(clock_.Now()); detector_.SetTimeouts( QuicTime::Delta::Infinite(), QuicTime::Delta::FromSeconds(600)); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(600)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, DoNotExtendIdleDeadlineOnConsecutiveSentPackets) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketReceived(clock_.Now()); detector_.SetTimeouts( QuicTime::Delta::Infinite(), QuicTime::Delta::FromSeconds(600)); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::Zero()); const QuicTime packet_sent_time = clock_.Now(); EXPECT_EQ(packet_sent_time + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::Zero()); EXPECT_EQ(packet_sent_time + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(600) - QuicTime::Delta::FromMilliseconds(200)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, ShorterIdleTimeoutOnSentPacket) { detector_.enable_shorter_idle_timeout_on_sent_packet(); QuicTime::Delta idle_network_timeout = QuicTime::Delta::Zero(); idle_network_timeout = QuicTime::Delta::FromSeconds(30); detector_.SetTimeouts( QuicTime::Delta::Infinite(), idle_network_timeout); EXPECT_TRUE(alarm_->IsSet()); const QuicTime deadline = alarm_->deadline(); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(30), deadline); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(deadline, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(14)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(deadline, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); detector_.OnPacketReceived(clock_.Now()); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(30), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(29)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(2), alarm_->deadline()); } TEST_F(QuicIdleNetworkDetectorTest, NoAlarmAfterStopped) { detector_.StopDetection(); EXPECT_QUIC_BUG( detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)), "SetAlarm called after stopped"); EXPECT_FALSE(alarm_->IsSet()); } } } }
233
cpp
google/quiche
quic_sustained_bandwidth_recorder
quiche/quic/core/quic_sustained_bandwidth_recorder.cc
quiche/quic/core/quic_sustained_bandwidth_recorder_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_SUSTAINED_BANDWIDTH_RECORDER_H_ #define QUICHE_QUIC_CORE_QUIC_SUSTAINED_BANDWIDTH_RECORDER_H_ #include <cstdint> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace test { class QuicSustainedBandwidthRecorderPeer; } class QUICHE_EXPORT QuicSustainedBandwidthRecorder { public: QuicSustainedBandwidthRecorder(); QuicSustainedBandwidthRecorder(const QuicSustainedBandwidthRecorder&) = delete; QuicSustainedBandwidthRecorder& operator=( const QuicSustainedBandwidthRecorder&) = delete; void RecordEstimate(bool in_recovery, bool in_slow_start, QuicBandwidth bandwidth, QuicTime estimate_time, QuicWallTime wall_time, QuicTime::Delta srtt); bool HasEstimate() const { return has_estimate_; } QuicBandwidth BandwidthEstimate() const { QUICHE_DCHECK(has_estimate_); return bandwidth_estimate_; } QuicBandwidth MaxBandwidthEstimate() const { QUICHE_DCHECK(has_estimate_); return max_bandwidth_estimate_; } int64_t MaxBandwidthTimestamp() const { QUICHE_DCHECK(has_estimate_); return max_bandwidth_timestamp_; } bool EstimateRecordedDuringSlowStart() const { QUICHE_DCHECK(has_estimate_); return bandwidth_estimate_recorded_during_slow_start_; } private: friend class test::QuicSustainedBandwidthRecorderPeer; bool has_estimate_; bool is_recording_; bool bandwidth_estimate_recorded_during_slow_start_; QuicBandwidth bandwidth_estimate_; QuicBandwidth max_bandwidth_estimate_; int64_t max_bandwidth_timestamp_; QuicTime start_time_; }; } #endif #include "quiche/quic/core/quic_sustained_bandwidth_recorder.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QuicSustainedBandwidthRecorder::QuicSustainedBandwidthRecorder() : has_estimate_(false), is_recording_(false), bandwidth_estimate_recorded_during_slow_start_(false), bandwidth_estimate_(QuicBandwidth::Zero()), max_bandwidth_estimate_(QuicBandwidth::Zero()), max_bandwidth_timestamp_(0), start_time_(QuicTime::Zero()) {} void QuicSustainedBandwidthRecorder::RecordEstimate( bool in_recovery, bool in_slow_start, QuicBandwidth bandwidth, QuicTime estimate_time, QuicWallTime wall_time, QuicTime::Delta srtt) { if (in_recovery) { is_recording_ = false; QUIC_DVLOG(1) << "Stopped recording at: " << estimate_time.ToDebuggingValue(); return; } if (!is_recording_) { start_time_ = estimate_time; is_recording_ = true; QUIC_DVLOG(1) << "Started recording at: " << start_time_.ToDebuggingValue(); return; } if (estimate_time - start_time_ >= 3 * srtt) { has_estimate_ = true; bandwidth_estimate_recorded_during_slow_start_ = in_slow_start; bandwidth_estimate_ = bandwidth; QUIC_DVLOG(1) << "New sustained bandwidth estimate (KBytes/s): " << bandwidth_estimate_.ToKBytesPerSecond(); } if (bandwidth > max_bandwidth_estimate_) { max_bandwidth_estimate_ = bandwidth; max_bandwidth_timestamp_ = wall_time.ToUNIXSeconds(); QUIC_DVLOG(1) << "New max bandwidth estimate (KBytes/s): " << max_bandwidth_estimate_.ToKBytesPerSecond(); } } }
#include "quiche/quic/core/quic_sustained_bandwidth_recorder.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicSustainedBandwidthRecorderTest : public QuicTest {}; TEST_F(QuicSustainedBandwidthRecorderTest, BandwidthEstimates) { QuicSustainedBandwidthRecorder recorder; EXPECT_FALSE(recorder.HasEstimate()); QuicTime estimate_time = QuicTime::Zero(); QuicWallTime wall_time = QuicWallTime::Zero(); QuicTime::Delta srtt = QuicTime::Delta::FromMilliseconds(150); const int kBandwidthBitsPerSecond = 12345678; QuicBandwidth bandwidth = QuicBandwidth::FromBitsPerSecond(kBandwidthBitsPerSecond); bool in_recovery = false; bool in_slow_start = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_FALSE(recorder.HasEstimate()); estimate_time = estimate_time + srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_FALSE(recorder.HasEstimate()); estimate_time = estimate_time + srtt; estimate_time = estimate_time + srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_EQ(recorder.BandwidthEstimate(), bandwidth); EXPECT_EQ(recorder.BandwidthEstimate(), recorder.MaxBandwidthEstimate()); QuicBandwidth second_bandwidth = QuicBandwidth::FromBitsPerSecond(2 * kBandwidthBitsPerSecond); in_recovery = true; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); in_recovery = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), bandwidth); estimate_time = estimate_time + 3 * srtt; const int64_t kSeconds = 556677; QuicWallTime second_bandwidth_wall_time = QuicWallTime::FromUNIXSeconds(kSeconds); recorder.RecordEstimate(in_recovery, in_slow_start, second_bandwidth, estimate_time, second_bandwidth_wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), second_bandwidth); EXPECT_EQ(recorder.BandwidthEstimate(), recorder.MaxBandwidthEstimate()); EXPECT_EQ(recorder.MaxBandwidthTimestamp(), kSeconds); QuicBandwidth third_bandwidth = QuicBandwidth::FromBitsPerSecond(0.5 * kBandwidthBitsPerSecond); recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), third_bandwidth); estimate_time = estimate_time + 3 * srtt; recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), third_bandwidth); EXPECT_LT(third_bandwidth, second_bandwidth); EXPECT_EQ(recorder.MaxBandwidthEstimate(), second_bandwidth); EXPECT_EQ(recorder.MaxBandwidthTimestamp(), kSeconds); } TEST_F(QuicSustainedBandwidthRecorderTest, SlowStart) { QuicSustainedBandwidthRecorder recorder; EXPECT_FALSE(recorder.HasEstimate()); QuicTime estimate_time = QuicTime::Zero(); QuicWallTime wall_time = QuicWallTime::Zero(); QuicTime::Delta srtt = QuicTime::Delta::FromMilliseconds(150); const int kBandwidthBitsPerSecond = 12345678; QuicBandwidth bandwidth = QuicBandwidth::FromBitsPerSecond(kBandwidthBitsPerSecond); bool in_recovery = false; bool in_slow_start = true; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); estimate_time = estimate_time + 3 * srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_TRUE(recorder.EstimateRecordedDuringSlowStart()); estimate_time = estimate_time + 3 * srtt; in_slow_start = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_FALSE(recorder.EstimateRecordedDuringSlowStart()); } } } }
234
cpp
google/quiche
quic_alarm
quiche/quic/core/quic_alarm.cc
quiche/quic/core/quic_alarm_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_ALARM_H_ #define QUICHE_QUIC_CORE_QUIC_ALARM_H_ #include "quiche/quic/core/quic_arena_scoped_ptr.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QuicAlarm { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() {} virtual QuicConnectionContext* GetConnectionContext() = 0; virtual void OnAlarm() = 0; }; class QUICHE_EXPORT DelegateWithContext : public Delegate { public: explicit DelegateWithContext(QuicConnectionContext* context) : context_(context) {} ~DelegateWithContext() override {} QuicConnectionContext* GetConnectionContext() override { return context_; } private: QuicConnectionContext* context_; }; class QUICHE_EXPORT DelegateWithoutContext : public Delegate { public: ~DelegateWithoutContext() override {} QuicConnectionContext* GetConnectionContext() override { return nullptr; } }; explicit QuicAlarm(QuicArenaScopedPtr<Delegate> delegate); QuicAlarm(const QuicAlarm&) = delete; QuicAlarm& operator=(const QuicAlarm&) = delete; virtual ~QuicAlarm(); void Set(QuicTime new_deadline); void PermanentCancel() { CancelInternal(true); } void Cancel() { CancelInternal(false); } bool IsPermanentlyCancelled() const; void Update(QuicTime new_deadline, QuicTime::Delta granularity); bool IsSet() const; QuicTime deadline() const { return deadline_; } protected: virtual void SetImpl() = 0; virtual void CancelImpl() = 0; virtual void UpdateImpl(); void Fire(); private: void CancelInternal(bool permanent); QuicArenaScopedPtr<Delegate> delegate_; QuicTime deadline_; }; } #endif #include "quiche/quic/core/quic_alarm.h" #include <atomic> #include <cstdlib> #include <utility> #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_stack_trace.h" namespace quic { QuicAlarm::QuicAlarm(QuicArenaScopedPtr<Delegate> delegate) : delegate_(std::move(delegate)), deadline_(QuicTime::Zero()) {} QuicAlarm::~QuicAlarm() { if (IsSet()) { QUIC_CODE_COUNT(quic_alarm_not_cancelled_in_dtor); } } void QuicAlarm::Set(QuicTime new_deadline) { QUICHE_DCHECK(!IsSet()); QUICHE_DCHECK(new_deadline.IsInitialized()); if (IsPermanentlyCancelled()) { QUIC_BUG(quic_alarm_illegal_set) << "Set called after alarm is permanently cancelled. new_deadline:" << new_deadline; return; } deadline_ = new_deadline; SetImpl(); } void QuicAlarm::CancelInternal(bool permanent) { if (IsSet()) { deadline_ = QuicTime::Zero(); CancelImpl(); } if (permanent) { delegate_.reset(); } } bool QuicAlarm::IsPermanentlyCancelled() const { return delegate_ == nullptr; } void QuicAlarm::Update(QuicTime new_deadline, QuicTime::Delta granularity) { if (IsPermanentlyCancelled()) { QUIC_BUG(quic_alarm_illegal_update) << "Update called after alarm is permanently cancelled. new_deadline:" << new_deadline << ", granularity:" << granularity; return; } if (!new_deadline.IsInitialized()) { Cancel(); return; } if (std::abs((new_deadline - deadline_).ToMicroseconds()) < granularity.ToMicroseconds()) { return; } const bool was_set = IsSet(); deadline_ = new_deadline; if (was_set) { UpdateImpl(); } else { SetImpl(); } } bool QuicAlarm::IsSet() const { return deadline_.IsInitialized(); } void QuicAlarm::Fire() { if (!IsSet()) { return; } deadline_ = QuicTime::Zero(); if (!IsPermanentlyCancelled()) { QuicConnectionContextSwitcher context_switcher( delegate_->GetConnectionContext()); delegate_->OnAlarm(); } } void QuicAlarm::UpdateImpl() { const QuicTime new_deadline = deadline_; deadline_ = QuicTime::Zero(); CancelImpl(); deadline_ = new_deadline; SetImpl(); } }
#include "quiche/quic/core/quic_alarm.h" #include <memory> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" using testing::ElementsAre; using testing::Invoke; using testing::Return; namespace quic { namespace test { namespace { class TraceCollector : public QuicConnectionTracer { public: ~TraceCollector() override = default; void PrintLiteral(const char* literal) override { trace_.push_back(literal); } void PrintString(absl::string_view s) override { trace_.push_back(std::string(s)); } const std::vector<std::string>& trace() const { return trace_; } private: std::vector<std::string> trace_; }; class MockDelegate : public QuicAlarm::Delegate { public: MOCK_METHOD(QuicConnectionContext*, GetConnectionContext, (), (override)); MOCK_METHOD(void, OnAlarm, (), (override)); }; class DestructiveDelegate : public QuicAlarm::DelegateWithoutContext { public: DestructiveDelegate() : alarm_(nullptr) {} void set_alarm(QuicAlarm* alarm) { alarm_ = alarm; } void OnAlarm() override { QUICHE_DCHECK(alarm_); delete alarm_; } private: QuicAlarm* alarm_; }; class TestAlarm : public QuicAlarm { public: explicit TestAlarm(QuicAlarm::Delegate* delegate) : QuicAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)) {} bool scheduled() const { return scheduled_; } void FireAlarm() { scheduled_ = false; Fire(); } protected: void SetImpl() override { QUICHE_DCHECK(deadline().IsInitialized()); scheduled_ = true; } void CancelImpl() override { QUICHE_DCHECK(!deadline().IsInitialized()); scheduled_ = false; } private: bool scheduled_; }; class DestructiveAlarm : public QuicAlarm { public: explicit DestructiveAlarm(DestructiveDelegate* delegate) : QuicAlarm(QuicArenaScopedPtr<DestructiveDelegate>(delegate)) {} void FireAlarm() { Fire(); } protected: void SetImpl() override {} void CancelImpl() override {} }; class QuicAlarmTest : public QuicTest { public: QuicAlarmTest() : delegate_(new MockDelegate()), alarm_(delegate_), deadline_(QuicTime::Zero() + QuicTime::Delta::FromSeconds(7)), deadline2_(QuicTime::Zero() + QuicTime::Delta::FromSeconds(14)), new_deadline_(QuicTime::Zero()) {} void ResetAlarm() { alarm_.Set(new_deadline_); } MockDelegate* delegate_; TestAlarm alarm_; QuicTime deadline_; QuicTime deadline2_; QuicTime new_deadline_; }; TEST_F(QuicAlarmTest, IsSet) { EXPECT_FALSE(alarm_.IsSet()); } TEST_F(QuicAlarmTest, Set) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); EXPECT_TRUE(alarm_.IsSet()); EXPECT_TRUE(alarm_.scheduled()); EXPECT_EQ(deadline, alarm_.deadline()); } TEST_F(QuicAlarmTest, Cancel) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); alarm_.Cancel(); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); } TEST_F(QuicAlarmTest, PermanentCancel) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); alarm_.PermanentCancel(); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); EXPECT_QUIC_BUG(alarm_.Set(deadline), "Set called after alarm is permanently cancelled"); EXPECT_TRUE(alarm_.IsPermanentlyCancelled()); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); EXPECT_QUIC_BUG(alarm_.Update(deadline, QuicTime::Delta::Zero()), "Update called after alarm is permanently cancelled"); EXPECT_TRUE(alarm_.IsPermanentlyCancelled()); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); } TEST_F(QuicAlarmTest, Update) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); QuicTime new_deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(8); alarm_.Update(new_deadline, QuicTime::Delta::Zero()); EXPECT_TRUE(alarm_.IsSet()); EXPECT_TRUE(alarm_.scheduled()); EXPECT_EQ(new_deadline, alarm_.deadline()); } TEST_F(QuicAlarmTest, UpdateWithZero) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); alarm_.Update(QuicTime::Zero(), QuicTime::Delta::Zero()); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); } TEST_F(QuicAlarmTest, Fire) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); EXPECT_CALL(*delegate_, OnAlarm()); alarm_.FireAlarm(); EXPECT_FALSE(alarm_.IsSet()); EXPECT_FALSE(alarm_.scheduled()); EXPECT_EQ(QuicTime::Zero(), alarm_.deadline()); } TEST_F(QuicAlarmTest, FireAndResetViaSet) { alarm_.Set(deadline_); new_deadline_ = deadline2_; EXPECT_CALL(*delegate_, OnAlarm()) .WillOnce(Invoke(this, &QuicAlarmTest::ResetAlarm)); alarm_.FireAlarm(); EXPECT_TRUE(alarm_.IsSet()); EXPECT_TRUE(alarm_.scheduled()); EXPECT_EQ(deadline2_, alarm_.deadline()); } TEST_F(QuicAlarmTest, FireDestroysAlarm) { DestructiveDelegate* delegate(new DestructiveDelegate); DestructiveAlarm* alarm = new DestructiveAlarm(delegate); delegate->set_alarm(alarm); QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm->Set(deadline); alarm->FireAlarm(); } TEST_F(QuicAlarmTest, NullAlarmContext) { QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(nullptr)); EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] { QUIC_TRACELITERAL("Alarm fired."); })); alarm_.FireAlarm(); } TEST_F(QuicAlarmTest, AlarmContextWithNullTracer) { QuicConnectionContext context; ASSERT_EQ(context.tracer, nullptr); QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(&context)); EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] { QUIC_TRACELITERAL("Alarm fired."); })); alarm_.FireAlarm(); } TEST_F(QuicAlarmTest, AlarmContextWithTracer) { QuicConnectionContext context; std::unique_ptr<TraceCollector> tracer = std::make_unique<TraceCollector>(); const TraceCollector& tracer_ref = *tracer; context.tracer = std::move(tracer); QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7); alarm_.Set(deadline); EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(&context)); EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] { QUIC_TRACELITERAL("Alarm fired."); })); QUIC_TRACELITERAL("Should not be collected before alarm."); alarm_.FireAlarm(); QUIC_TRACELITERAL("Should not be collected after alarm."); EXPECT_THAT(tracer_ref.trace(), ElementsAre("Alarm fired.")); } } } }
235
cpp
google/quiche
chlo_extractor
quiche/quic/core/chlo_extractor.cc
quiche/quic/core/chlo_extractor_test.cc
#ifndef QUICHE_QUIC_CORE_CHLO_EXTRACTOR_H_ #define QUICHE_QUIC_CORE_CHLO_EXTRACTOR_H_ #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/quic_packets.h" namespace quic { class QUICHE_EXPORT ChloExtractor { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() {} virtual void OnChlo(QuicTransportVersion version, QuicConnectionId connection_id, const CryptoHandshakeMessage& chlo) = 0; }; static bool Extract(const QuicEncryptedPacket& packet, ParsedQuicVersion version, const QuicTagVector& create_session_tag_indicators, Delegate* delegate, uint8_t connection_id_length); ChloExtractor(const ChloExtractor&) = delete; ChloExtractor operator=(const ChloExtractor&) = delete; }; } #endif #include "quiche/quic/core/chlo_extractor.h" #include <memory> #include <optional> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" namespace quic { namespace { class ChloFramerVisitor : public QuicFramerVisitorInterface, public CryptoFramerVisitorInterface { public: ChloFramerVisitor(QuicFramer* framer, const QuicTagVector& create_session_tag_indicators, ChloExtractor::Delegate* delegate); ~ChloFramerVisitor() override = default; void OnError(QuicFramer* ) override {} bool OnProtocolVersionMismatch(ParsedQuicVersion version) override; void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& ) override {} void OnRetryPacket(QuicConnectionId , QuicConnectionId , absl::string_view , absl::string_view , absl::string_view ) override {} bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; void OnDecryptedPacket(size_t , EncryptionLevel ) override {} bool OnPacketHeader(const QuicPacketHeader& header) override; void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override; bool OnStreamFrame(const QuicStreamFrame& frame) override; bool OnCryptoFrame(const QuicCryptoFrame& frame) override; bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override; bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override; bool OnAckFrameEnd(QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) override; bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; bool OnPingFrame(const QuicPingFrame& frame) override; bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override; bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; bool OnBlockedFrame(const QuicBlockedFrame& frame) override; bool OnPaddingFrame(const QuicPaddingFrame& frame) override; bool OnMessageFrame(const QuicMessageFrame& frame) override; bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& farme) override; bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override; void OnPacketComplete() override {} bool IsValidStatelessResetToken( const StatelessResetToken& token) const override; void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& ) override {} void OnKeyUpdate(KeyUpdateReason ) override; void OnDecryptedFirstPacketInKeyPhase() override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void OnError(CryptoFramer* framer) override; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override; bool OnHandshakeData(absl::string_view data); bool found_chlo() { return found_chlo_; } bool chlo_contains_tags() { return chlo_contains_tags_; } private: QuicFramer* framer_; const QuicTagVector& create_session_tag_indicators_; ChloExtractor::Delegate* delegate_; bool found_chlo_; bool chlo_contains_tags_; QuicConnectionId connection_id_; }; ChloFramerVisitor::ChloFramerVisitor( QuicFramer* framer, const QuicTagVector& create_session_tag_indicators, ChloExtractor::Delegate* delegate) : framer_(framer), create_session_tag_indicators_(create_session_tag_indicators), delegate_(delegate), found_chlo_(false), chlo_contains_tags_(false), connection_id_(EmptyQuicConnectionId()) {} bool ChloFramerVisitor::OnProtocolVersionMismatch(ParsedQuicVersion version) { if (!framer_->IsSupportedVersion(version)) { return false; } framer_->set_version(version); return true; } bool ChloFramerVisitor::OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) { connection_id_ = header.destination_connection_id; framer_->SetInitialObfuscators(header.destination_connection_id); return true; } bool ChloFramerVisitor::OnUnauthenticatedHeader( const QuicPacketHeader& ) { return true; } bool ChloFramerVisitor::OnPacketHeader(const QuicPacketHeader& ) { return true; } void ChloFramerVisitor::OnCoalescedPacket( const QuicEncryptedPacket& ) {} void ChloFramerVisitor::OnUndecryptablePacket( const QuicEncryptedPacket& , EncryptionLevel , bool ) {} bool ChloFramerVisitor::OnStreamFrame(const QuicStreamFrame& frame) { if (QuicVersionUsesCryptoFrames(framer_->transport_version())) { return false; } absl::string_view data(frame.data_buffer, frame.data_length); if (QuicUtils::IsCryptoStreamId(framer_->transport_version(), frame.stream_id) && frame.offset == 0 && absl::StartsWith(data, "CHLO")) { return OnHandshakeData(data); } return true; } bool ChloFramerVisitor::OnCryptoFrame(const QuicCryptoFrame& frame) { if (!QuicVersionUsesCryptoFrames(framer_->transport_version())) { return false; } absl::string_view data(frame.data_buffer, frame.data_length); if (frame.offset == 0 && absl::StartsWith(data, "CHLO")) { return OnHandshakeData(data); } return true; } bool ChloFramerVisitor::OnHandshakeData(absl::string_view data) { CryptoFramer crypto_framer; crypto_framer.set_visitor(this); if (!crypto_framer.ProcessInput(data)) { return false; } for (const QuicTag tag : create_session_tag_indicators_) { if (crypto_framer.HasTag(tag)) { chlo_contains_tags_ = true; } } if (chlo_contains_tags_ && delegate_) { crypto_framer.ForceHandshake(); } return true; } bool ChloFramerVisitor::OnAckFrameStart(QuicPacketNumber , QuicTime::Delta ) { return true; } bool ChloFramerVisitor::OnResetStreamAtFrame( const QuicResetStreamAtFrame& ) { return true; } bool ChloFramerVisitor::OnAckRange(QuicPacketNumber , QuicPacketNumber ) { return true; } bool ChloFramerVisitor::OnAckTimestamp(QuicPacketNumber , QuicTime ) { return true; } bool ChloFramerVisitor::OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) { return true; } bool ChloFramerVisitor::OnStopWaitingFrame( const QuicStopWaitingFrame& ) { return true; } bool ChloFramerVisitor::OnPingFrame(const QuicPingFrame& ) { return true; } bool ChloFramerVisitor::OnRstStreamFrame(const QuicRstStreamFrame& ) { return true; } bool ChloFramerVisitor::OnConnectionCloseFrame( const QuicConnectionCloseFrame& ) { return true; } bool ChloFramerVisitor::OnStopSendingFrame( const QuicStopSendingFrame& ) { return true; } bool ChloFramerVisitor::OnPathChallengeFrame( const QuicPathChallengeFrame& ) { return true; } bool ChloFramerVisitor::OnPathResponseFrame( const QuicPathResponseFrame& ) { return true; } bool ChloFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& ) { return true; } bool ChloFramerVisitor::OnWindowUpdateFrame( const QuicWindowUpdateFrame& ) { return true; } bool ChloFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& ) { return true; } bool ChloFramerVisitor::OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& ) { return true; } bool ChloFramerVisitor::OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& ) { return true; } bool ChloFramerVisitor::OnNewTokenFrame(const QuicNewTokenFrame& ) { return true; } bool ChloFramerVisitor::OnPaddingFrame(const QuicPaddingFrame& ) { return true; } bool ChloFramerVisitor::OnMessageFrame(const QuicMessageFrame& ) { return true; } bool ChloFramerVisitor::OnHandshakeDoneFrame( const QuicHandshakeDoneFrame& ) { return true; } bool ChloFramerVisitor::OnAckFrequencyFrame( const QuicAckFrequencyFrame& ) { return true; } bool ChloFramerVisitor::IsValidStatelessResetToken( const StatelessResetToken& ) const { return false; } bool ChloFramerVisitor::OnMaxStreamsFrame( const QuicMaxStreamsFrame& ) { return true; } bool ChloFramerVisitor::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& ) { return true; } void ChloFramerVisitor::OnKeyUpdate(KeyUpdateReason ) {} void ChloFramerVisitor::OnDecryptedFirstPacketInKeyPhase() {} std::unique_ptr<QuicDecrypter> ChloFramerVisitor::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return nullptr; } std::unique_ptr<QuicEncrypter> ChloFramerVisitor::CreateCurrentOneRttEncrypter() { return nullptr; } void ChloFramerVisitor::OnError(CryptoFramer* ) {} void ChloFramerVisitor::OnHandshakeMessage( const CryptoHandshakeMessage& message) { if (delegate_ != nullptr) { delegate_->OnChlo(framer_->transport_version(), connection_id_, message); } found_chlo_ = true; } } bool ChloExtractor::Extract(const QuicEncryptedPacket& packet, ParsedQuicVersion version, const QuicTagVector& create_session_tag_indicators, Delegate* delegate, uint8_t connection_id_length) { QUIC_DVLOG(1) << "Extracting CHLO using version " << version; QuicFramer framer({version}, QuicTime::Zero(), Perspective::IS_SERVER, connection_id_length); ChloFramerVisitor visitor(&framer, create_session_tag_indicators, delegate); framer.set_visitor(&visitor); if (!framer.ProcessPacket(packet)) { return false; } return visitor.found_chlo() || visitor.chlo_contains_tags(); } }
#include "quiche/quic/core/chlo_extractor.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/first_flight.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class TestDelegate : public ChloExtractor::Delegate { public: TestDelegate() = default; ~TestDelegate() override = default; void OnChlo(QuicTransportVersion version, QuicConnectionId connection_id, const CryptoHandshakeMessage& chlo) override { version_ = version; connection_id_ = connection_id; chlo_ = chlo.DebugString(); absl::string_view alpn_value; if (chlo.GetStringPiece(kALPN, &alpn_value)) { alpn_ = std::string(alpn_value); } } QuicConnectionId connection_id() const { return connection_id_; } QuicTransportVersion transport_version() const { return version_; } const std::string& chlo() const { return chlo_; } const std::string& alpn() const { return alpn_; } private: QuicConnectionId connection_id_; QuicTransportVersion version_; std::string chlo_; std::string alpn_; }; class ChloExtractorTest : public QuicTestWithParam<ParsedQuicVersion> { public: ChloExtractorTest() : version_(GetParam()) {} void MakePacket(absl::string_view data, bool munge_offset, bool munge_stream_id) { QuicPacketHeader header; header.destination_connection_id = TestConnectionId(); header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.version_flag = true; header.version = version_; header.reset_flag = false; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header.packet_number = QuicPacketNumber(1); if (version_.HasLongHeaderLengths()) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; size_t offset = 0; if (munge_offset) { offset++; } QuicFramer framer(SupportedVersions(version_), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength); framer.SetInitialObfuscators(TestConnectionId()); if (!version_.UsesCryptoFrames() || munge_stream_id) { QuicStreamId stream_id = QuicUtils::GetCryptoStreamId(version_.transport_version); if (munge_stream_id) { stream_id++; } frames.push_back( QuicFrame(QuicStreamFrame(stream_id, false, offset, data))); } else { frames.push_back( QuicFrame(new QuicCryptoFrame(ENCRYPTION_INITIAL, offset, data))); } std::unique_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); size_t encrypted_length = framer.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *packet, buffer_, ABSL_ARRAYSIZE(buffer_)); ASSERT_NE(0u, encrypted_length); packet_ = std::make_unique<QuicEncryptedPacket>(buffer_, encrypted_length); EXPECT_TRUE(packet_ != nullptr); DeleteFrames(&frames); } protected: ParsedQuicVersion version_; TestDelegate delegate_; std::unique_ptr<QuicEncryptedPacket> packet_; char buffer_[kMaxOutgoingPacketSize]; }; INSTANTIATE_TEST_SUITE_P( ChloExtractorTests, ChloExtractorTest, ::testing::ValuesIn(AllSupportedVersionsWithQuicCrypto()), ::testing::PrintToStringParamName()); TEST_P(ChloExtractorTest, FindsValidChlo) { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, false, false); EXPECT_TRUE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); EXPECT_EQ(version_.transport_version, delegate_.transport_version()); EXPECT_EQ(TestConnectionId(), delegate_.connection_id()); EXPECT_EQ(client_hello.DebugString(), delegate_.chlo()); } TEST_P(ChloExtractorTest, DoesNotFindValidChloOnWrongStream) { if (version_.UsesCryptoFrames()) { return; } CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, false, true); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, DoesNotFindValidChloOnWrongOffset) { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, true, false); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, DoesNotFindInvalidChlo) { MakePacket("foo", false, false); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, FirstFlight) { std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_); ASSERT_EQ(packets.size(), 1u); EXPECT_TRUE(ChloExtractor::Extract(*packets[0], version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); EXPECT_EQ(version_.transport_version, delegate_.transport_version()); EXPECT_EQ(TestConnectionId(), delegate_.connection_id()); EXPECT_EQ(AlpnForVersion(version_), delegate_.alpn()); } } } }
236
cpp
google/quiche
legacy_quic_stream_id_manager
quiche/quic/core/legacy_quic_stream_id_manager.cc
quiche/quic/core/legacy_quic_stream_id_manager_test.cc
#ifndef QUICHE_QUIC_CORE_LEGACY_QUIC_STREAM_ID_MANAGER_H_ #define QUICHE_QUIC_CORE_LEGACY_QUIC_STREAM_ID_MANAGER_H_ #include "absl/container/flat_hash_set.h" #include "quiche/quic/core/quic_stream_id_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" namespace quic { namespace test { class QuicSessionPeer; } class QuicSession; class QUICHE_EXPORT LegacyQuicStreamIdManager { public: LegacyQuicStreamIdManager(Perspective perspective, QuicTransportVersion transport_version, size_t max_open_outgoing_streams, size_t max_open_incoming_streams); ~LegacyQuicStreamIdManager(); bool CanOpenNextOutgoingStream() const; bool CanOpenIncomingStream() const; bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId id); bool IsAvailableStream(QuicStreamId id) const; QuicStreamId GetNextOutgoingStreamId(); void ActivateStream(bool is_incoming); void OnStreamClosed(bool is_incoming); bool IsIncomingStream(QuicStreamId id) const; size_t MaxAvailableStreams() const; void set_max_open_incoming_streams(size_t max_open_incoming_streams) { max_open_incoming_streams_ = max_open_incoming_streams; } void set_max_open_outgoing_streams(size_t max_open_outgoing_streams) { max_open_outgoing_streams_ = max_open_outgoing_streams; } void set_largest_peer_created_stream_id( QuicStreamId largest_peer_created_stream_id) { largest_peer_created_stream_id_ = largest_peer_created_stream_id; } size_t max_open_incoming_streams() const { return max_open_incoming_streams_; } size_t max_open_outgoing_streams() const { return max_open_outgoing_streams_; } QuicStreamId next_outgoing_stream_id() const { return next_outgoing_stream_id_; } QuicStreamId largest_peer_created_stream_id() const { return largest_peer_created_stream_id_; } size_t GetNumAvailableStreams() const; size_t num_open_incoming_streams() const { return num_open_incoming_streams_; } size_t num_open_outgoing_streams() const { return num_open_outgoing_streams_; } private: friend class test::QuicSessionPeer; const Perspective perspective_; const QuicTransportVersion transport_version_; size_t max_open_outgoing_streams_; size_t max_open_incoming_streams_; QuicStreamId next_outgoing_stream_id_; absl::flat_hash_set<QuicStreamId> available_streams_; QuicStreamId largest_peer_created_stream_id_; size_t num_open_incoming_streams_; size_t num_open_outgoing_streams_; }; } #endif #include "quiche/quic/core/legacy_quic_stream_id_manager.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" namespace quic { LegacyQuicStreamIdManager::LegacyQuicStreamIdManager( Perspective perspective, QuicTransportVersion transport_version, size_t max_open_outgoing_streams, size_t max_open_incoming_streams) : perspective_(perspective), transport_version_(transport_version), max_open_outgoing_streams_(max_open_outgoing_streams), max_open_incoming_streams_(max_open_incoming_streams), next_outgoing_stream_id_(QuicUtils::GetFirstBidirectionalStreamId( transport_version_, perspective_)), largest_peer_created_stream_id_( perspective_ == Perspective::IS_SERVER ? (QuicVersionUsesCryptoFrames(transport_version_) ? QuicUtils::GetInvalidStreamId(transport_version_) : QuicUtils::GetCryptoStreamId(transport_version_)) : QuicUtils::GetInvalidStreamId(transport_version_)), num_open_incoming_streams_(0), num_open_outgoing_streams_(0) {} LegacyQuicStreamIdManager::~LegacyQuicStreamIdManager() {} bool LegacyQuicStreamIdManager::CanOpenNextOutgoingStream() const { QUICHE_DCHECK_LE(num_open_outgoing_streams_, max_open_outgoing_streams_); QUIC_DLOG_IF(INFO, num_open_outgoing_streams_ == max_open_outgoing_streams_) << "Failed to create a new outgoing stream. " << "Already " << num_open_outgoing_streams_ << " open."; return num_open_outgoing_streams_ < max_open_outgoing_streams_; } bool LegacyQuicStreamIdManager::CanOpenIncomingStream() const { return num_open_incoming_streams_ < max_open_incoming_streams_; } bool LegacyQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id) { available_streams_.erase(stream_id); if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(transport_version_) && stream_id <= largest_peer_created_stream_id_) { return true; } size_t additional_available_streams = (stream_id - largest_peer_created_stream_id_) / 2 - 1; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { additional_available_streams = (stream_id + 1) / 2 - 1; } size_t new_num_available_streams = GetNumAvailableStreams() + additional_available_streams; if (new_num_available_streams > MaxAvailableStreams()) { QUIC_DLOG(INFO) << perspective_ << "Failed to create a new incoming stream with id:" << stream_id << ". There are already " << GetNumAvailableStreams() << " streams available, which would become " << new_num_available_streams << ", which exceeds the limit " << MaxAvailableStreams() << "."; return false; } QuicStreamId first_available_stream = largest_peer_created_stream_id_ + 2; if (largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_)) { first_available_stream = QuicUtils::GetFirstBidirectionalStreamId( transport_version_, QuicUtils::InvertPerspective(perspective_)); } for (QuicStreamId id = first_available_stream; id < stream_id; id += 2) { available_streams_.insert(id); } largest_peer_created_stream_id_ = stream_id; return true; } QuicStreamId LegacyQuicStreamIdManager::GetNextOutgoingStreamId() { QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += 2; return id; } void LegacyQuicStreamIdManager::ActivateStream(bool is_incoming) { if (is_incoming) { ++num_open_incoming_streams_; return; } ++num_open_outgoing_streams_; } void LegacyQuicStreamIdManager::OnStreamClosed(bool is_incoming) { if (is_incoming) { QUIC_BUG_IF(quic_bug_12720_1, num_open_incoming_streams_ == 0); --num_open_incoming_streams_; return; } QUIC_BUG_IF(quic_bug_12720_2, num_open_outgoing_streams_ == 0); --num_open_outgoing_streams_; } bool LegacyQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { if (!IsIncomingStream(id)) { return id >= next_outgoing_stream_id_; } return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(transport_version_) || id > largest_peer_created_stream_id_ || available_streams_.contains(id); } bool LegacyQuicStreamIdManager::IsIncomingStream(QuicStreamId id) const { return id % 2 != next_outgoing_stream_id_ % 2; } size_t LegacyQuicStreamIdManager::GetNumAvailableStreams() const { return available_streams_.size(); } size_t LegacyQuicStreamIdManager::MaxAvailableStreams() const { return max_open_incoming_streams_ * kMaxAvailableStreamsMultiplier; } }
#include "quiche/quic/core/legacy_quic_stream_id_manager.h" #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { using testing::_; using testing::StrictMock; struct TestParams { TestParams(ParsedQuicVersion version, Perspective perspective) : version(version), perspective(perspective) {} ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), (p.perspective == Perspective::IS_CLIENT ? "Client" : "Server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (ParsedQuicVersion version : AllSupportedVersions()) { for (auto perspective : {Perspective::IS_CLIENT, Perspective::IS_SERVER}) { if (!VersionHasIetfQuicFrames(version.transport_version)) { params.push_back(TestParams(version, perspective)); } } } return params; } class LegacyQuicStreamIdManagerTest : public QuicTestWithParam<TestParams> { public: LegacyQuicStreamIdManagerTest() : manager_(GetParam().perspective, GetParam().version.transport_version, kDefaultMaxStreamsPerConnection, kDefaultMaxStreamsPerConnection) {} protected: QuicStreamId GetNthPeerInitiatedId(int n) { if (GetParam().perspective == Perspective::IS_SERVER) { return QuicUtils::GetFirstBidirectionalStreamId( GetParam().version.transport_version, Perspective::IS_CLIENT) + 2 * n; } else { return 2 + 2 * n; } } LegacyQuicStreamIdManager manager_; }; INSTANTIATE_TEST_SUITE_P(Tests, LegacyQuicStreamIdManagerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(LegacyQuicStreamIdManagerTest, CanOpenNextOutgoingStream) { for (size_t i = 0; i < manager_.max_open_outgoing_streams() - 1; ++i) { manager_.ActivateStream(false); } EXPECT_TRUE(manager_.CanOpenNextOutgoingStream()); manager_.ActivateStream(false); EXPECT_FALSE(manager_.CanOpenNextOutgoingStream()); } TEST_P(LegacyQuicStreamIdManagerTest, CanOpenIncomingStream) { for (size_t i = 0; i < manager_.max_open_incoming_streams() - 1; ++i) { manager_.ActivateStream(true); } EXPECT_TRUE(manager_.CanOpenIncomingStream()); manager_.ActivateStream(true); EXPECT_FALSE(manager_.CanOpenIncomingStream()); } TEST_P(LegacyQuicStreamIdManagerTest, AvailableStreams) { ASSERT_TRUE( manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(3))); EXPECT_TRUE(manager_.IsAvailableStream(GetNthPeerInitiatedId(1))); EXPECT_TRUE(manager_.IsAvailableStream(GetNthPeerInitiatedId(2))); ASSERT_TRUE( manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(2))); ASSERT_TRUE( manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(1))); } TEST_P(LegacyQuicStreamIdManagerTest, MaxAvailableStreams) { const size_t kMaxStreamsForTest = 10; const size_t kAvailableStreamLimit = manager_.MaxAvailableStreams(); EXPECT_EQ( manager_.max_open_incoming_streams() * kMaxAvailableStreamsMultiplier, manager_.MaxAvailableStreams()); EXPECT_LE(10 * kMaxStreamsForTest, kAvailableStreamLimit); EXPECT_TRUE( manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(0))); const int kLimitingStreamId = GetNthPeerInitiatedId(kAvailableStreamLimit + 1); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(kLimitingStreamId)); EXPECT_FALSE( manager_.MaybeIncreaseLargestPeerStreamId(kLimitingStreamId + 2 * 2)); } TEST_P(LegacyQuicStreamIdManagerTest, MaximumAvailableOpenedStreams) { QuicStreamId stream_id = GetNthPeerInitiatedId(0); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id)); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( stream_id + 2 * (manager_.max_open_incoming_streams() - 1))); } TEST_P(LegacyQuicStreamIdManagerTest, TooManyAvailableStreams) { QuicStreamId stream_id = GetNthPeerInitiatedId(0); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id)); QuicStreamId stream_id2 = GetNthPeerInitiatedId(2 * manager_.MaxAvailableStreams() + 4); EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id2)); } TEST_P(LegacyQuicStreamIdManagerTest, ManyAvailableStreams) { manager_.set_max_open_incoming_streams(200); QuicStreamId stream_id = GetNthPeerInitiatedId(0); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id)); EXPECT_TRUE( manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(199))); } TEST_P(LegacyQuicStreamIdManagerTest, TestMaxIncomingAndOutgoingStreamsAllowed) { EXPECT_EQ(manager_.max_open_incoming_streams(), kDefaultMaxStreamsPerConnection); EXPECT_EQ(manager_.max_open_outgoing_streams(), kDefaultMaxStreamsPerConnection); } } } }
237
cpp
google/quiche
quic_framer
quiche/quic/core/quic_framer.cc
quiche/quic/core/quic_framer_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_FRAMER_H_ #define QUICHE_QUIC_CORE_QUIC_FRAMER_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicFramerPeer; } class QuicDataReader; class QuicDataWriter; class QuicFramer; class QuicStreamFrameDataProducer; inline constexpr size_t kQuicFrameTypeSize = 1; inline constexpr size_t kQuicErrorCodeSize = 4; inline constexpr size_t kQuicErrorDetailsLengthSize = 2; inline constexpr size_t kQuicMaxStreamIdSize = 4; inline constexpr size_t kQuicMaxStreamOffsetSize = 8; inline constexpr size_t kQuicStreamPayloadLengthSize = 2; inline constexpr size_t kQuicIetfQuicErrorCodeSize = 2; inline constexpr size_t kIetfQuicMinErrorPhraseLengthSize = 1; inline constexpr size_t kQuicDeltaTimeLargestObservedSize = 2; inline constexpr size_t kQuicNumTimestampsSize = 1; inline constexpr size_t kNumberOfNackRangesSize = 1; inline constexpr size_t kNumberOfAckBlocksSize = 1; inline constexpr size_t kMaxNackRanges = (1 << (kNumberOfNackRangesSize * 8)) - 1; inline constexpr size_t kMaxAckBlocks = (1 << (kNumberOfAckBlocksSize * 8)) - 1; class QUICHE_EXPORT QuicFramerVisitorInterface { public: virtual ~QuicFramerVisitorInterface() {} virtual void OnError(QuicFramer* framer) = 0; virtual bool OnProtocolVersionMismatch( ParsedQuicVersion received_version) = 0; virtual void OnPacket() = 0; virtual void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) = 0; virtual void OnRetryPacket(QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag) = 0; virtual bool OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) = 0; virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0; virtual void OnDecryptedPacket(size_t length, EncryptionLevel level) = 0; virtual bool OnPacketHeader(const QuicPacketHeader& header) = 0; virtual void OnCoalescedPacket(const QuicEncryptedPacket& packet) = 0; virtual void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) = 0; virtual bool OnStreamFrame(const QuicStreamFrame& frame) = 0; virtual bool OnCryptoFrame(const QuicCryptoFrame& frame) = 0; virtual bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) = 0; virtual bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) = 0; virtual bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) = 0; virtual bool OnAckFrameEnd( QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) = 0; virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) = 0; virtual bool OnPaddingFrame(const QuicPaddingFrame& frame) = 0; virtual bool OnPingFrame(const QuicPingFrame& frame) = 0; virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0; virtual bool OnConnectionCloseFrame( const QuicConnectionCloseFrame& frame) = 0; virtual bool OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0; virtual bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) = 0; virtual bool OnPathResponseFrame(const QuicPathResponseFrame& frame) = 0; virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0; virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0; virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) = 0; virtual bool OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& frame) = 0; virtual bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) = 0; virtual bool OnNewTokenFrame(const QuicNewTokenFrame& frame) = 0; virtual bool OnMessageFrame(const QuicMessageFrame& frame) = 0; virtual bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) = 0; virtual bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) = 0; virtual bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) = 0; virtual void OnPacketComplete() = 0; virtual bool IsValidStatelessResetToken( const StatelessResetToken& token) const = 0; virtual void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) = 0; virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0; virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0; virtual void OnKeyUpdate(KeyUpdateReason reason) = 0; virtual void OnDecryptedFirstPacketInKeyPhase() = 0; virtual std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; }; class QUICHE_EXPORT QuicFramer { public: QuicFramer(const ParsedQuicVersionVector& supported_versions, QuicTime creation_time, Perspective perspective, uint8_t expected_server_connection_id_length); QuicFramer(const QuicFramer&) = delete; QuicFramer& operator=(const QuicFramer&) = delete; virtual ~QuicFramer(); bool IsSupportedVersion(const ParsedQuicVersion version) const; void set_visitor(QuicFramerVisitorInterface* visitor) { visitor_ = visitor; } const ParsedQuicVersionVector& supported_versions() const { return supported_versions_; } QuicTransportVersion transport_version() const { return version_.transport_version; } ParsedQuicVersion version() const { return version_; } void set_version(const ParsedQuicVersion version); void set_version_for_tests(const ParsedQuicVersion version) { version_ = version; } QuicErrorCode error() const { return error_; } void set_process_timestamps(bool process_timestamps) const { process_timestamps_ = process_timestamps; } void set_max_receive_timestamps_per_ack(uint32_t max_timestamps) const { max_receive_timestamps_per_ack_ = max_timestamps; } void set_receive_timestamps_exponent(uint32_t exponent) const { receive_timestamps_exponent_ = exponent; } void set_process_reset_stream_at(bool process_reset_stream_at) { process_reset_stream_at_ = process_reset_stream_at; } bool ProcessPacket(const QuicEncryptedPacket& packet); bool is_processing_packet() const { return is_processing_packet_; } static size_t GetMinStreamFrameSize(QuicTransportVersion version, QuicStreamId stream_id, QuicStreamOffset offset, bool last_frame_in_packet, size_t data_length); static size_t GetMinCryptoFrameSize(QuicStreamOffset offset, QuicPacketLength data_length); static size_t GetMessageFrameSize(bool last_frame_in_packet, QuicByteCount length); static size_t GetMinAckFrameSize(QuicTransportVersion version, const QuicAckFrame& ack_frame, uint32_t local_ack_delay_exponent, bool use_ietf_ack_with_receive_timestamp); static size_t GetStopWaitingFrameSize( QuicPacketNumberLength packet_number_length); static size_t GetRstStreamFrameSize(QuicTransportVersion version, const QuicRstStreamFrame& frame); static size_t GetAckFrequencyFrameSize(const QuicAckFrequencyFrame& frame); static size_t GetResetStreamAtFrameSize(const QuicResetStreamAtFrame& frame); static size_t GetConnectionCloseFrameSize( QuicTransportVersion version, const QuicConnectionCloseFrame& frame); static size_t GetMinGoAwayFrameSize(); static size_t GetWindowUpdateFrameSize(QuicTransportVersion version, const QuicWindowUpdateFrame& frame); static size_t GetMaxStreamsFrameSize(QuicTransportVersion version, const QuicMaxStreamsFrame& frame); static size_t GetStreamsBlockedFrameSize( QuicTransportVersion version, const QuicStreamsBlockedFrame& frame); static size_t GetBlockedFrameSize(QuicTransportVersion version, const QuicBlockedFrame& frame); static size_t GetPathChallengeFrameSize(const QuicPathChallengeFrame& frame); static size_t GetPathResponseFrameSize(const QuicPathResponseFrame& frame); static size_t GetStreamIdSize(QuicStreamId stream_id); static size_t GetStreamOffsetSize(QuicStreamOffset offset); static size_t GetNewConnectionIdFrameSize( const QuicNewConnectionIdFrame& frame); static size_t GetRetireConnectionIdFrameSize( const QuicRetireConnectionIdFrame& frame); static size_t GetNewTokenFrameSize(const QuicNewTokenFrame& frame); static size_t GetStopSendingFrameSize(const QuicStopSendingFrame& frame); static size_t GetRetransmittableControlFrameSize(QuicTransportVersion version, const QuicFrame& frame); size_t GetSerializedFrameLength(const QuicFrame& frame, size_t free_bytes, bool first_frame_in_packet, bool last_frame_in_packet, QuicPacketNumberLength packet_number_length); static absl::string_view GetAssociatedDataFromEncryptedPacket( QuicTransportVersion version, const QuicEncryptedPacket& encrypted, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool includes_version, bool includes_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, uint64_t retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length); static QuicErrorCode ParsePublicHeader( QuicDataReader* reader, uint8_t expected_destination_connection_id_length, bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, QuicLongHeaderType* long_packet_type, quiche::QuicheVariableLengthIntegerLength* retry_token_length_length, absl::string_view* retry_token, std::string* detailed_error); static QuicErrorCode ParsePublicHeaderDispatcher( const QuicEncryptedPacket& packet, uint8_t expected_destination_connection_id_length, PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, std::optional<absl::string_view>* retry_token, std::string* detailed_error); static QuicErrorCode ParsePublicHeaderDispatcherShortHeaderLengthUnknown( const QuicEncryptedPacket& packet, PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, std::optional<absl::string_view>* retry_token, std::string* detailed_error, ConnectionIdGeneratorInterface& generator); static QuicErrorCode TryDecryptInitialPacketDispatcher( const QuicEncryptedPacket& packet, const ParsedQuicVersion& version, PacketHeaderFormat format, QuicLongHeaderType long_packet_type, const QuicConnectionId& destination_connection_id, const QuicConnectionId& source_connection_id, const std::optional<absl::string_view>& retry_token, QuicPacketNumber largest_decrypted_inital_packet_number, QuicDecrypter& decrypter, std::optional<uint64_t>* packet_number); size_t BuildDataPacket(const QuicPacketHeader& header, const QuicFrames& frames, char* buffer, size_t packet_length, EncryptionLevel level); static std::unique_ptr<QuicEncryptedPacket> BuildPublicResetPacket( const QuicPublicResetPacket& packet); static size_t GetMinStatelessResetPacketLength(); static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length, StatelessResetToken stateless_reset_token); static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length, StatelessResetToken stateless_reset_token, QuicRandom* random); static std::unique_ptr<QuicEncryptedPacket> BuildVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& versions); static std::unique_ptr<QuicEncryptedPacket> BuildIetfVersionNegotiationPacket( bool use_length_prefix, QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, const ParsedQuicVersionVector& versions); bool AppendIetfHeaderTypeByte(const QuicPacketHeader& header, QuicDataWriter* writer); bool AppendIetfPacketHeader(const QuicPacketHeader& header, QuicDataWriter* writer, size_t* length_field_offset); bool WriteIetfLongHeaderLength(const QuicPacketHeader& header, QuicDataWriter* writer, size_t length_field_offset, EncryptionLevel level); bool AppendTypeByte(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer); bool AppendIetfFrameType(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer); size_t AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer); bool AppendStreamFrame(const QuicStreamFrame& frame, bool no_stream_frame_length, QuicDataWriter* writer); bool AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer); bool AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame, QuicDataWriter* writer); bool AppendResetFrameAtFrame(const QuicResetStreamAtFrame& frame, QuicDataWriter& writer); void SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter); void SetAlternativeDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool latch_once_used); void InstallDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter); void RemoveDecrypter(EncryptionLevel level); void SetKeyUpdateSupportForConnection(bool enabled); void DiscardPreviousOneRttKeys(); bool DoKeyUpdate(KeyUpdateReason reason); QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const; const QuicDecrypter* GetDecrypter(EncryptionLevel level) const; const QuicDecrypter* decrypter() const; const QuicDecrypter* alternative_decrypter() const; void SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter); void RemoveEncrypter(EncryptionLevel level); void SetInitialObfuscators(QuicConnectionId connection_id); size_t EncryptInPlace(EncryptionLevel level, QuicPacketNumber packet_number, size_t ad_len, size_t total_len, size_t buffer_len, char* buffer); size_t EncryptPayload(EncryptionLevel level, QuicPacketNumber packet_number, const QuicPacket& packet, char* buffer, size_t buffer_len); size_t GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const; size_t GetMaxPlaintextSize(size_t ciphertext_size); QuicPacketCount GetOneRttEncrypterConfidentialityLimit() const; const std::string& detailed_error() { return detailed_error_; } static QuicPacketNumberLength GetMinPacketNumberLength( QuicPacketNumber packet_number); void SetSupportedVersions(const ParsedQuicVersionVector& versions) { supported_versions_ = versions; version_ = versions[0]; } bool IsIetfStatelessResetPacket(const QuicPacketHeader& header) const; bool HasEncrypterOfEncryptionLevel(EncryptionLevel level) const; bool HasDecrypterOfEncryptionLevel(EncryptionLevel level) const; bool HasAnEncrypterForSpace(PacketNumberSpace space) const;
#include "quiche/quic/core/quic_framer.h" #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; using testing::ContainerEq; using testing::Optional; using testing::Return; namespace quic { namespace test { namespace { const uint64_t kEpoch = UINT64_C(1) << 32; const uint64_t kMask = kEpoch - 1; const uint8_t kPacket0ByteConnectionId = 0; const uint8_t kPacket8ByteConnectionId = 8; constexpr size_t kTagSize = 16; const StatelessResetToken kTestStatelessResetToken{ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}; QuicConnectionId FramerTestConnectionId() { return TestConnectionId(UINT64_C(0xFEDCBA9876543210)); } QuicConnectionId FramerTestConnectionIdPlusOne() { return TestConnectionId(UINT64_C(0xFEDCBA9876543211)); } QuicConnectionId FramerTestConnectionIdNineBytes() { uint8_t connection_id_bytes[9] = {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}; return QuicConnectionId(reinterpret_cast<char*>(connection_id_bytes), sizeof(connection_id_bytes)); } const QuicPacketNumber kPacketNumber = QuicPacketNumber(UINT64_C(0x12345678)); const QuicPacketNumber kSmallLargestObserved = QuicPacketNumber(UINT16_C(0x1234)); const QuicPacketNumber kSmallMissingPacket = QuicPacketNumber(UINT16_C(0x1233)); const QuicPacketNumber kLeastUnacked = QuicPacketNumber(UINT64_C(0x012345670)); const QuicStreamId kStreamId = UINT64_C(0x01020304); const QuicStreamOffset kStreamOffset = UINT64_C(0x3A98FEDC32107654); const QuicPublicResetNonceProof kNonceProof = UINT64_C(0xABCDEF0123456789); const QuicPacketNumber kLargestIetfLargestObserved = QuicPacketNumber(UINT64_C(0x3fffffffffffffff)); const uint8_t kVarInt62OneByte = 0x00; const uint8_t kVarInt62TwoBytes = 0x40; const uint8_t kVarInt62FourBytes = 0x80; const uint8_t kVarInt62EightBytes = 0xc0; class TestEncrypter : public QuicEncrypter { public: ~TestEncrypter() override {} bool SetKey(absl::string_view ) override { return true; } bool SetNoncePrefix(absl::string_view ) override { return true; } bool SetIV(absl::string_view ) override { return true; } bool SetHeaderProtectionKey(absl::string_view ) override { return true; } bool EncryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view plaintext, char* output, size_t* output_length, size_t ) override { packet_number_ = QuicPacketNumber(packet_number); associated_data_ = std::string(associated_data); plaintext_ = std::string(plaintext); memcpy(output, plaintext.data(), plaintext.length()); *output_length = plaintext.length(); return true; } std::string GenerateHeaderProtectionMask( absl::string_view ) override { return std::string(5, 0); } size_t GetKeySize() const override { return 0; } size_t GetNoncePrefixSize() const override { return 0; } size_t GetIVSize() const override { return 0; } size_t GetMaxPlaintextSize(size_t ciphertext_size) const override { return ciphertext_size; } size_t GetCiphertextSize(size_t plaintext_size) const override { return plaintext_size; } QuicPacketCount GetConfidentialityLimit() const override { return std::numeric_limits<QuicPacketCount>::max(); } absl::string_view GetKey() const override { return absl::string_view(); } absl::string_view GetNoncePrefix() const override { return absl::string_view(); } QuicPacketNumber packet_number_; std::string associated_data_; std::string plaintext_; }; class TestDecrypter : public QuicDecrypter { public: ~TestDecrypter() override {} bool SetKey(absl::string_view ) override { return true; } bool SetNoncePrefix(absl::string_view ) override { return true; } bool SetIV(absl::string_view ) override { return true; } bool SetHeaderProtectionKey(absl::string_view ) override { return true; } bool SetPreliminaryKey(absl::string_view ) override { QUIC_BUG(quic_bug_10486_1) << "should not be called"; return false; } bool SetDiversificationNonce(const DiversificationNonce& ) override { return true; } bool DecryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view ciphertext, char* output, size_t* output_length, size_t ) override { packet_number_ = QuicPacketNumber(packet_number); associated_data_ = std::string(associated_data); ciphertext_ = std::string(ciphertext); memcpy(output, ciphertext.data(), ciphertext.length()); *output_length = ciphertext.length(); return true; } std::string GenerateHeaderProtectionMask( QuicDataReader* ) override { return std::string(5, 0); } size_t GetKeySize() const override { return 0; } size_t GetNoncePrefixSize() const override { return 0; } size_t GetIVSize() const override { return 0; } absl::string_view GetKey() const override { return absl::string_view(); } absl::string_view GetNoncePrefix() const override { return absl::string_view(); } uint32_t cipher_id() const override { return 0xFFFFFFF2; } QuicPacketCount GetIntegrityLimit() const override { return std::numeric_limits<QuicPacketCount>::max(); } QuicPacketNumber packet_number_; std::string associated_data_; std::string ciphertext_; }; std::unique_ptr<QuicEncryptedPacket> EncryptPacketWithTagAndPhase( const QuicPacket& packet, uint8_t tag, bool phase) { std::string packet_data = std::string(packet.AsStringPiece()); if (phase) { packet_data[0] |= FLAGS_KEY_PHASE_BIT; } else { packet_data[0] &= ~FLAGS_KEY_PHASE_BIT; } TaggingEncrypter crypter(tag); const size_t packet_size = crypter.GetCiphertextSize(packet_data.size()); char* buffer = new char[packet_size]; size_t buf_len = 0; if (!crypter.EncryptPacket(0, absl::string_view(), packet_data, buffer, &buf_len, packet_size)) { delete[] buffer; return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer, buf_len, true); } class TestQuicVisitor : public QuicFramerVisitorInterface { public: TestQuicVisitor() : error_count_(0), version_mismatch_(0), packet_count_(0), frame_count_(0), complete_packets_(0), derive_next_key_count_(0), decrypted_first_packet_in_key_phase_count_(0), accept_packet_(true), accept_public_header_(true) {} ~TestQuicVisitor() override {} void OnError(QuicFramer* f) override { QUIC_DLOG(INFO) << "QuicFramer Error: " << QuicErrorCodeToString(f->error()) << " (" << f->error() << ")"; ++error_count_; } void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) override { version_negotiation_packet_ = std::make_unique<QuicVersionNegotiationPacket>((packet)); EXPECT_EQ(0u, framer_->current_received_frame_type()); } void OnRetryPacket(QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag) override { on_retry_packet_called_ = true; retry_original_connection_id_ = std::make_unique<QuicConnectionId>(original_connection_id); retry_new_connection_id_ = std::make_unique<QuicConnectionId>(new_connection_id); retry_token_ = std::make_unique<std::string>(std::string(retry_token)); retry_token_integrity_tag_ = std::make_unique<std::string>(std::string(retry_integrity_tag)); retry_without_tag_ = std::make_unique<std::string>(std::string(retry_without_tag)); EXPECT_EQ(0u, framer_->current_received_frame_type()); } bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override { QUIC_DLOG(INFO) << "QuicFramer Version Mismatch, version: " << received_version; ++version_mismatch_; EXPECT_EQ(0u, framer_->current_received_frame_type()); return false; } bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override { header_ = std::make_unique<QuicPacketHeader>((header)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return accept_public_header_; } bool OnUnauthenticatedHeader(const QuicPacketHeader& ) override { EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } void OnDecryptedPacket(size_t , EncryptionLevel ) override { EXPECT_EQ(0u, framer_->current_received_frame_type()); } bool OnPacketHeader(const QuicPacketHeader& header) override { ++packet_count_; header_ = std::make_unique<QuicPacketHeader>((header)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return accept_packet_; } void OnCoalescedPacket(const QuicEncryptedPacket& packet) override { coalesced_packets_.push_back(packet.Clone()); } void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override { undecryptable_packets_.push_back(packet.Clone()); undecryptable_decryption_levels_.push_back(decryption_level); undecryptable_has_decryption_keys_.push_back(has_decryption_key); } bool OnStreamFrame(const QuicStreamFrame& frame) override { ++frame_count_; std::string* string_data = new std::string(frame.data_buffer, frame.data_length); stream_data_.push_back(absl::WrapUnique(string_data)); stream_frames_.push_back(std::make_unique<QuicStreamFrame>( frame.stream_id, frame.fin, frame.offset, *string_data)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IS_IETF_STREAM_FRAME(framer_->current_received_frame_type())); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnCryptoFrame(const QuicCryptoFrame& frame) override { ++frame_count_; std::string* string_data = new std::string(frame.data_buffer, frame.data_length); crypto_data_.push_back(absl::WrapUnique(string_data)); crypto_frames_.push_back(std::make_unique<QuicCryptoFrame>( frame.level, frame.offset, *string_data)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_CRYPTO, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override { ++frame_count_; QuicAckFrame ack_frame; ack_frame.largest_acked = largest_acked; ack_frame.ack_delay_time = ack_delay_time; ack_frames_.push_back(std::make_unique<QuicAckFrame>(ack_frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override { QUICHE_DCHECK(!ack_frames_.empty()); ack_frames_[ack_frames_.size() - 1]->packets.AddRange(start, end); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override { ack_frames_[ack_frames_.size() - 1]->received_packet_times.push_back( std::make_pair(packet_number, timestamp)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) override { return true; } bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override { ++frame_count_; stop_waiting_frames_.push_back( std::make_unique<QuicStopWaitingFrame>(frame)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } bool OnPaddingFrame(const QuicPaddingFrame& frame) override { padding_frames_.push_back(std::make_unique<QuicPaddingFrame>(frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_PADDING, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnPingFrame(const QuicPingFrame& frame) override { ++frame_count_; ping_frames_.push_back(std::make_unique<QuicPingFrame>(frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_PING, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnMessageFrame(const QuicMessageFrame& frame) override { ++frame_count_; message_frames_.push_back( std::make_unique<QuicMessageFrame>(frame.data, frame.message_length)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_EXTENSION_MESSAGE_NO_LENGTH_V99 == framer_->current_received_frame_type() || IETF_EXTENSION_MESSAGE_V99 == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override { ++frame_count_; handshake_done_frames_.push_back( std::make_unique<QuicHandshakeDoneFrame>(frame)); QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_HANDSHAKE_DONE, framer_->current_received_frame_type()); return true; } bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override { ++frame_count_; ack_frequency_frames_.emplace_back( std::make_unique<QuicAckFrequencyFrame>(frame)); QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_ACK_FREQUENCY, framer_->current_received_frame_type()); return true; } bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override { ++frame_count_; reset_stream_at_frames_.push_back( std::make_unique<QuicResetStreamAtFrame>(frame)); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_RESET_STREAM_AT, framer_->current_received_frame_type()); return true; } void OnPacketComplete() override { ++complete_packets_; } bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override { rst_stream_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_RST_STREAM, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override { connection_close_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_NE(GOOGLE_QUIC_CONNECTION_CLOSE, frame.close_type); if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { EXPECT_EQ(IETF_CONNECTION_CLOSE, framer_->current_received_frame_type()); } else { EXPECT_EQ(IETF_APPLICATION_CLOSE, framer_->current_received_frame_type()); } } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override { stop_sending_frame_ = frame; EXPECT_EQ(IETF_STOP_SENDING, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override { path_challenge_frame_ = frame; EXPECT_EQ(IETF_PATH_CHALLENGE, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override { path_response_frame_ = frame; EXPECT_EQ(IETF_PATH_RESPONSE, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override { goaway_frame_ = frame; EXPECT_FALSE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override { max_streams_frame_ = frame; EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_TRUE(IETF_MAX_STREAMS_UNIDIRECTIONAL == framer_->current_received_frame_type() || IETF_MAX_STREAMS_BIDIRECTIONAL == framer_->current_received_frame_type()); return true; } bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override { streams_blocked_frame_ = frame; EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_TRUE(IETF_STREAMS_BLOCKED_UNIDIRECTIONAL == framer_->current_received_frame_type() || IETF_STREAMS_BLOCKED_BIDIRECTIONAL == framer_->current_received_frame_type()); return true; } bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override { window_update_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_MAX_DATA == framer_->current_received_frame_type() || IETF_MAX_STREAM_DATA == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnBlockedFrame(const QuicBlockedFrame& frame) override { blocked_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_DATA_BLOCKED == framer_->current_received_frame_type() || IETF_STREAM_DATA_BLOCKED == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override { new_connection_id_ = frame; EXPECT_EQ(IETF_NEW_CONNECTION_ID, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override { EXPECT_EQ(IETF_RETIRE_CONNECTION_ID, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); retire_connection_id_ = frame; return true; } bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override { new_token_ = frame; EXPECT_EQ(IETF_NEW_TOKEN, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool IsValidStatelessResetToken( const StatelessResetToken& token) const override { EXPECT_EQ(0u, framer_->current_received_frame_type()); return token == kTestStatelessResetToken; } void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) override { stateless_reset_packet_ = std::make_unique<QuicIetfStatelessResetPacket>(packet); EXPECT_EQ(0u, framer_->current_received_frame_type()); } void OnKeyUpdate(KeyUpdateReason reason) override { key_update_reasons_.push_back(reason); } void OnDecryptedFirstPacketInKeyPhase() override { decrypted_first_packet_in_key_phase_count_++; } std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { derive_next_key_count_++; return std::make_unique<StrictTaggingDecrypter>(derive_next_key_count_); } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return std::make_unique<TaggingEncrypter>(derive_next_key_count_); } void set_framer(QuicFramer* framer) { framer_ = framer; transport_version_ = framer->transport_version(); } size_t key_update_count() const { return key_update_reasons_.size(); } int error_count_; int version_mismatch_; int packet_count_; int frame_count_; int complete_packets_; std::vector<KeyUpdateReason> key_update_reasons_; int derive_next_key_count_; int decrypted_first_packet_in_key_phase_count_; bool accept_packet_; bool accept_public_header_; std::unique_ptr<QuicPacketHeader> header_; std::unique_ptr<QuicIetfStatelessResetPacket> stateless_reset_packet_; std::unique_ptr<QuicVersionNegotiationPacket> version_negotiation_packet_; std::unique_ptr<QuicConnectionId> retry_original_connection_id_; std::unique_ptr<QuicConnectionId> retry_new_connection_id_; std::unique_ptr<std::string> retry_token_; std::unique_ptr<std::string> retry_token_integrity_tag_; std::unique_ptr<std::string> retry_without_tag_; bool on_retry_packet_called_ = false; std::vector<std::unique_ptr<QuicStreamFrame>> stream_frames_; std::vector<std::unique_ptr<QuicCryptoFrame>> crypto_frames_; std::vector<std::unique_ptr<QuicAckFrame>> ack_frames_; std::vector<std::unique_ptr<QuicStopWaitingFrame>> stop_waiting_frames_; std::vector<std::unique_ptr<QuicPaddingFrame>> padding_frames_; std::vector<std::unique_ptr<QuicPingFrame>> ping_frames_; std::vector<std::unique_ptr<QuicMessageFrame>> message_frames_; std::vector<std::unique_ptr<QuicHandshakeDoneFrame>> handshake_done_frames_; std::vector<std::unique_ptr<QuicAckFrequencyFrame>> ack_frequency_frames_; std::vector<std::unique_ptr<QuicResetStreamAtFrame>> reset_stream_at_frames_; std::vector<std::unique_ptr<QuicEncryptedPacket>> coalesced_packets_; std::vector<std::unique_ptr<QuicEncryptedPacket>> undecryptable_packets_; std::vector<EncryptionLevel> undecryptable_decryption_levels_; std::vector<bool> undecryptable_has_decryption_keys_; QuicRstStreamFrame rst_stream_frame_; QuicConnectionCloseFrame connection_close_frame_; QuicStopSendingFrame stop_sending_frame_; QuicGoAwayFrame goaway_frame_; QuicPathChallengeFrame path_challenge_frame_; QuicPathResponseFrame path_response_frame_; QuicWindowUpdateFrame window_update_frame_; QuicBlockedFrame blocked_frame_; QuicStreamsBlockedFrame streams_blocked_frame_; QuicMaxStreamsFrame max_streams_frame_; QuicNewConnectionIdFrame new_connection_id_; QuicRetireConnectionIdFrame retire_connection_id_; QuicNewTokenFrame new_token_; std::vector<std::unique_ptr<std::string>> stream_data_; std::vector<std::unique_ptr<std::string>> crypto_data_; QuicTransportVersion transport_version_; QuicFramer* framer_; }; struct PacketFragment { std::string error_if_missing; std::vector<unsigned char> fragment; }; using PacketFragments = std::vector<struct PacketFragment>; class QuicFramerTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicFramerTest() : encrypter_(new test::TestEncrypter()), decrypter_(new test::TestDecrypter()), version_(GetParam()), start_(QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(0x10)), framer_(AllSupportedVersions(), start_, Perspective::IS_SERVER, kQuicDefaultConnectionIdLength) { framer_.set_version(version_); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicDecrypter>(decrypter_)); } else { framer_.SetDecrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicDecrypter>(decrypter_)); } framer_.SetEncrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicEncrypter>(encrypter_)); framer_.set_visitor(&visitor_); visitor_.set_framer(&framer_); } void SetDecrypterLevel(EncryptionLevel level) { if (!framer_.version().KnowsWhichDecrypterToUse()) { return; } decrypter_ = new TestDecrypter(); framer_.InstallDecrypter(level, std::unique_ptr<QuicDecrypter>(decrypter_)); } unsigned char GetQuicVersionByte(int pos) { return (CreateQuicVersionLabel(version_) >> 8 * (3 - pos)) & 0xff; } inline void ReviseFirstByteByVersion(unsigned char packet_ietf[]) { if (version_.UsesV2PacketTypes() && (packet_ietf[0] >= 0x80)) { packet_ietf[0] = (packet_ietf[0] + 0x10) | 0xc0; } } inline void ReviseFirstByteByVersion(PacketFragments& packet_ietf) { ReviseFirstByteByVersion(&packet_ietf[0].fragment[0]); } bool CheckEncryption(QuicPacketNumber packet_number, QuicPacket* packet) { if (packet_number != encrypter_->packet_number_) { QUIC_LOG(ERROR) << "Encrypted incorrect packet number. expected " << packet_number << " actual: " << encrypter_->packet_number_; return false; } if (packet->AssociatedData(framer_.transport_version()) != encrypter_->associated_data_) { QUIC_LOG(ERROR) << "Encrypted incorrect associated data. expected " << packet->AssociatedData(framer_.transport_version()) << " actual: " << encrypter_->associated_data_; return false; } if (packet->Plaintext(framer_.transport_version()) != encrypter_->plaintext_) { QUIC_LOG(ERROR) << "Encrypted incorrect plaintext data. expected " << packet->Plaintext(framer_.transport_version()) << " actual: " << encrypter_->plaintext_; return false; } return true; } bool CheckDecryption(const QuicEncryptedPacket& encrypted, bool includes_version, bool includes_diversification_nonce, uint8_t destination_connection_id_length, uint8_t source_connection_id_length) { return CheckDecryption( encrypted, includes_version, includes_diversification_nonce, destination_connection_id_length, source_connection_id_length, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); } bool CheckDecryption( const QuicEncryptedPacket& encrypted, bool includes_version, bool includes_diversification_nonce, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, size_t retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) { if (visitor_.header_->packet_number != decrypter_->packet_number_) { QUIC_LOG(ERROR) << "Decrypted incorrect packet number. expected " << visitor_.header_->packet_number << " actual: " << decrypter_->packet_number_; return false; } absl::string_view associated_data = QuicFramer::GetAssociatedDataFromEncryptedPacket( framer_.transport_version(), encrypted, destination_connection_id_length, source_connection_id_length, includes_version, includes_diversification_nonce, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, retry_token_length, length_length); if (associated_data != decrypter_->associated_data_) { QUIC_LOG(ERROR) << "Decrypted incorrect associated data. expected " << absl::BytesToHexString(associated_data) << " actual: " << absl::BytesToHexString(decrypter_->associated_data_); return false; } absl::string_view ciphertext( encrypted.AsStringPiece().substr(GetStartOfEncryptedData( framer_.transport_version(), destination_connection_id_length, source_connection_id_length, includes_version, includes_diversification_nonce, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, retry_token_length, length_length))); if (ciphertext != decrypter_->ciphertext_) { QUIC_LOG(ERROR) << "Decrypted incorrect ciphertext data. expected " << absl::BytesToHexString(ciphertext) << " actual: " << absl::BytesToHexString(decrypter_->ciphertext_)
238
cpp
google/quiche
quic_bandwidth
quiche/quic/core/quic_bandwidth.cc
quiche/quic/core/quic_bandwidth_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_BANDWIDTH_H_ #define QUICHE_QUIC_CORE_QUIC_BANDWIDTH_H_ #include <cmath> #include <cstdint> #include <limits> #include <ostream> #include <string> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flag_utils.h" namespace quic { class QUICHE_EXPORT QuicBandwidth { public: static constexpr QuicBandwidth Zero() { return QuicBandwidth(0); } static constexpr QuicBandwidth Infinite() { return QuicBandwidth(std::numeric_limits<int64_t>::max()); } static constexpr QuicBandwidth FromBitsPerSecond(int64_t bits_per_second) { return QuicBandwidth(bits_per_second); } static constexpr QuicBandwidth FromKBitsPerSecond(int64_t k_bits_per_second) { return QuicBandwidth(k_bits_per_second * 1000); } static constexpr QuicBandwidth FromBytesPerSecond(int64_t bytes_per_second) { return QuicBandwidth(bytes_per_second * 8); } static constexpr QuicBandwidth FromKBytesPerSecond( int64_t k_bytes_per_second) { return QuicBandwidth(k_bytes_per_second * 8000); } static QuicBandwidth FromBytesAndTimeDelta(QuicByteCount bytes, QuicTime::Delta delta) { if (bytes == 0) { return QuicBandwidth(0); } int64_t num_micro_bits = 8 * bytes * kNumMicrosPerSecond; if (num_micro_bits < delta.ToMicroseconds()) { return QuicBandwidth(1); } return QuicBandwidth(num_micro_bits / delta.ToMicroseconds()); } int64_t ToBitsPerSecond() const { return bits_per_second_; } int64_t ToKBitsPerSecond() const { return bits_per_second_ / 1000; } int64_t ToBytesPerSecond() const { return bits_per_second_ / 8; } int64_t ToKBytesPerSecond() const { return bits_per_second_ / 8000; } constexpr QuicByteCount ToBytesPerPeriod(QuicTime::Delta time_period) const { return bits_per_second_ * time_period.ToMicroseconds() / 8 / kNumMicrosPerSecond; } int64_t ToKBytesPerPeriod(QuicTime::Delta time_period) const { return bits_per_second_ * time_period.ToMicroseconds() / 8000 / kNumMicrosPerSecond; } bool IsZero() const { return bits_per_second_ == 0; } bool IsInfinite() const { return bits_per_second_ == Infinite().ToBitsPerSecond(); } constexpr QuicTime::Delta TransferTime(QuicByteCount bytes) const { if (bits_per_second_ == 0) { return QuicTime::Delta::Zero(); } return QuicTime::Delta::FromMicroseconds(bytes * 8 * kNumMicrosPerSecond / bits_per_second_); } std::string ToDebuggingValue() const; private: explicit constexpr QuicBandwidth(int64_t bits_per_second) : bits_per_second_(bits_per_second >= 0 ? bits_per_second : 0) {} int64_t bits_per_second_; friend constexpr QuicBandwidth operator+(QuicBandwidth lhs, QuicBandwidth rhs); friend constexpr QuicBandwidth operator-(QuicBandwidth lhs, QuicBandwidth rhs); friend QuicBandwidth operator*(QuicBandwidth lhs, float rhs); }; inline bool operator==(QuicBandwidth lhs, QuicBandwidth rhs) { return lhs.ToBitsPerSecond() == rhs.ToBitsPerSecond(); } inline bool operator!=(QuicBandwidth lhs, QuicBandwidth rhs) { return !(lhs == rhs); } inline bool operator<(QuicBandwidth lhs, QuicBandwidth rhs) { return lhs.ToBitsPerSecond() < rhs.ToBitsPerSecond(); } inline bool operator>(QuicBandwidth lhs, QuicBandwidth rhs) { return rhs < lhs; } inline bool operator<=(QuicBandwidth lhs, QuicBandwidth rhs) { return !(rhs < lhs); } inline bool operator>=(QuicBandwidth lhs, QuicBandwidth rhs) { return !(lhs < rhs); } inline constexpr QuicBandwidth operator+(QuicBandwidth lhs, QuicBandwidth rhs) { return QuicBandwidth(lhs.bits_per_second_ + rhs.bits_per_second_); } inline constexpr QuicBandwidth operator-(QuicBandwidth lhs, QuicBandwidth rhs) { return QuicBandwidth(lhs.bits_per_second_ - rhs.bits_per_second_); } inline QuicBandwidth operator*(QuicBandwidth lhs, float rhs) { return QuicBandwidth( static_cast<int64_t>(std::llround(lhs.bits_per_second_ * rhs))); } inline QuicBandwidth operator*(float lhs, QuicBandwidth rhs) { return rhs * lhs; } inline constexpr QuicByteCount operator*(QuicBandwidth lhs, QuicTime::Delta rhs) { return lhs.ToBytesPerPeriod(rhs); } inline constexpr QuicByteCount operator*(QuicTime::Delta lhs, QuicBandwidth rhs) { return rhs * lhs; } inline std::ostream& operator<<(std::ostream& output, const QuicBandwidth bandwidth) { output << bandwidth.ToDebuggingValue(); return output; } } #endif #include "quiche/quic/core/quic_bandwidth.h" #include <cinttypes> #include <string> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" namespace quic { std::string QuicBandwidth::ToDebuggingValue() const { if (bits_per_second_ < 80000) { return absl::StrFormat("%d bits/s (%d bytes/s)", bits_per_second_, bits_per_second_ / 8); } double divisor; char unit; if (bits_per_second_ < 8 * 1000 * 1000) { divisor = 1e3; unit = 'k'; } else if (bits_per_second_ < INT64_C(8) * 1000 * 1000 * 1000) { divisor = 1e6; unit = 'M'; } else { divisor = 1e9; unit = 'G'; } double bits_per_second_with_unit = bits_per_second_ / divisor; double bytes_per_second_with_unit = bits_per_second_with_unit / 8; return absl::StrFormat("%.2f %cbits/s (%.2f %cbytes/s)", bits_per_second_with_unit, unit, bytes_per_second_with_unit, unit); } }
#include "quiche/quic/core/quic_bandwidth.h" #include <limits> #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QuicBandwidthTest : public QuicTest {}; TEST_F(QuicBandwidthTest, FromTo) { EXPECT_EQ(QuicBandwidth::FromKBitsPerSecond(1), QuicBandwidth::FromBitsPerSecond(1000)); EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1), QuicBandwidth::FromBytesPerSecond(1000)); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(8000), QuicBandwidth::FromBytesPerSecond(1000)); EXPECT_EQ(QuicBandwidth::FromKBitsPerSecond(8), QuicBandwidth::FromKBytesPerSecond(1)); EXPECT_EQ(0, QuicBandwidth::Zero().ToBitsPerSecond()); EXPECT_EQ(0, QuicBandwidth::Zero().ToKBitsPerSecond()); EXPECT_EQ(0, QuicBandwidth::Zero().ToBytesPerSecond()); EXPECT_EQ(0, QuicBandwidth::Zero().ToKBytesPerSecond()); EXPECT_EQ(1, QuicBandwidth::FromBitsPerSecond(1000).ToKBitsPerSecond()); EXPECT_EQ(1000, QuicBandwidth::FromKBitsPerSecond(1).ToBitsPerSecond()); EXPECT_EQ(1, QuicBandwidth::FromBytesPerSecond(1000).ToKBytesPerSecond()); EXPECT_EQ(1000, QuicBandwidth::FromKBytesPerSecond(1).ToBytesPerSecond()); } TEST_F(QuicBandwidthTest, Add) { QuicBandwidth bandwidht_1 = QuicBandwidth::FromKBitsPerSecond(1); QuicBandwidth bandwidht_2 = QuicBandwidth::FromKBytesPerSecond(1); EXPECT_EQ(9000, (bandwidht_1 + bandwidht_2).ToBitsPerSecond()); EXPECT_EQ(9000, (bandwidht_2 + bandwidht_1).ToBitsPerSecond()); } TEST_F(QuicBandwidthTest, Subtract) { QuicBandwidth bandwidht_1 = QuicBandwidth::FromKBitsPerSecond(1); QuicBandwidth bandwidht_2 = QuicBandwidth::FromKBytesPerSecond(1); EXPECT_EQ(7000, (bandwidht_2 - bandwidht_1).ToBitsPerSecond()); } TEST_F(QuicBandwidthTest, TimeDelta) { EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1000), QuicBandwidth::FromBytesAndTimeDelta( 1000, QuicTime::Delta::FromMilliseconds(1))); EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(10), QuicBandwidth::FromBytesAndTimeDelta( 1000, QuicTime::Delta::FromMilliseconds(100))); EXPECT_EQ(QuicBandwidth::Zero(), QuicBandwidth::FromBytesAndTimeDelta( 0, QuicTime::Delta::FromSeconds(9))); EXPECT_EQ( QuicBandwidth::FromBitsPerSecond(1), QuicBandwidth::FromBytesAndTimeDelta(1, QuicTime::Delta::FromSeconds(9))); } TEST_F(QuicBandwidthTest, Scale) { EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(500), QuicBandwidth::FromKBytesPerSecond(1000) * 0.5f); EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(750), 0.75f * QuicBandwidth::FromKBytesPerSecond(1000)); EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1250), QuicBandwidth::FromKBytesPerSecond(1000) * 1.25f); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(5), QuicBandwidth::FromBitsPerSecond(9) * 0.5f); EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(2), QuicBandwidth::FromBitsPerSecond(12) * 0.2f); } TEST_F(QuicBandwidthTest, BytesPerPeriod) { EXPECT_EQ(2000, QuicBandwidth::FromKBytesPerSecond(2000).ToBytesPerPeriod( QuicTime::Delta::FromMilliseconds(1))); EXPECT_EQ(2, QuicBandwidth::FromKBytesPerSecond(2000).ToKBytesPerPeriod( QuicTime::Delta::FromMilliseconds(1))); EXPECT_EQ(200000, QuicBandwidth::FromKBytesPerSecond(2000).ToBytesPerPeriod( QuicTime::Delta::FromMilliseconds(100))); EXPECT_EQ(200, QuicBandwidth::FromKBytesPerSecond(2000).ToKBytesPerPeriod( QuicTime::Delta::FromMilliseconds(100))); EXPECT_EQ(200, QuicBandwidth::FromBitsPerSecond(1599).ToBytesPerPeriod( QuicTime::Delta::FromMilliseconds(1001))); EXPECT_EQ(200, QuicBandwidth::FromBitsPerSecond(1599).ToKBytesPerPeriod( QuicTime::Delta::FromSeconds(1001))); } TEST_F(QuicBandwidthTest, TransferTime) { EXPECT_EQ(QuicTime::Delta::FromSeconds(1), QuicBandwidth::FromKBytesPerSecond(1).TransferTime(1000)); EXPECT_EQ(QuicTime::Delta::Zero(), QuicBandwidth::Zero().TransferTime(1000)); } TEST_F(QuicBandwidthTest, RelOps) { const QuicBandwidth b1 = QuicBandwidth::FromKBitsPerSecond(1); const QuicBandwidth b2 = QuicBandwidth::FromKBytesPerSecond(2); EXPECT_EQ(b1, b1); EXPECT_NE(b1, b2); EXPECT_LT(b1, b2); EXPECT_GT(b2, b1); EXPECT_LE(b1, b1); EXPECT_LE(b1, b2); EXPECT_GE(b1, b1); EXPECT_GE(b2, b1); } TEST_F(QuicBandwidthTest, DebuggingValue) { EXPECT_EQ("128 bits/s (16 bytes/s)", QuicBandwidth::FromBytesPerSecond(16).ToDebuggingValue()); EXPECT_EQ("4096 bits/s (512 bytes/s)", QuicBandwidth::FromBytesPerSecond(512).ToDebuggingValue()); QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1000 * 50); EXPECT_EQ("400.00 kbits/s (50.00 kbytes/s)", bandwidth.ToDebuggingValue()); bandwidth = bandwidth * 1000; EXPECT_EQ("400.00 Mbits/s (50.00 Mbytes/s)", bandwidth.ToDebuggingValue()); bandwidth = bandwidth * 1000; EXPECT_EQ("400.00 Gbits/s (50.00 Gbytes/s)", bandwidth.ToDebuggingValue()); } TEST_F(QuicBandwidthTest, SpecialValues) { EXPECT_EQ(0, QuicBandwidth::Zero().ToBitsPerSecond()); EXPECT_EQ(std::numeric_limits<int64_t>::max(), QuicBandwidth::Infinite().ToBitsPerSecond()); EXPECT_TRUE(QuicBandwidth::Zero().IsZero()); EXPECT_FALSE(QuicBandwidth::Zero().IsInfinite()); EXPECT_TRUE(QuicBandwidth::Infinite().IsInfinite()); EXPECT_FALSE(QuicBandwidth::Infinite().IsZero()); } } }
239
cpp
google/quiche
quic_control_frame_manager
quiche/quic/core/quic_control_frame_manager.cc
quiche/quic/core/quic_control_frame_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONTROL_FRAME_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_CONTROL_FRAME_MANAGER_H_ #include <cstdint> #include <string> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { class QuicSession; namespace test { class QuicControlFrameManagerPeer; } class QUICHE_EXPORT QuicControlFrameManager { public: class QUICHE_EXPORT DelegateInterface { public: virtual ~DelegateInterface() = default; virtual void OnControlFrameManagerError(QuicErrorCode error_code, std::string error_details) = 0; virtual bool WriteControlFrame(const QuicFrame& frame, TransmissionType type) = 0; }; explicit QuicControlFrameManager(QuicSession* session); QuicControlFrameManager(const QuicControlFrameManager& other) = delete; QuicControlFrameManager(QuicControlFrameManager&& other) = delete; ~QuicControlFrameManager(); void WriteOrBufferRstStream(QuicControlFrameId id, QuicResetStreamError error, QuicStreamOffset bytes_written); void WriteOrBufferGoAway(QuicErrorCode error, QuicStreamId last_good_stream_id, const std::string& reason); void WriteOrBufferWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset); void WriteOrBufferBlocked(QuicStreamId id, QuicStreamOffset byte_offset); void WriteOrBufferStreamsBlocked(QuicStreamCount count, bool unidirectional); void WriteOrBufferMaxStreams(QuicStreamCount count, bool unidirectional); void WriteOrBufferStopSending(QuicResetStreamError error, QuicStreamId stream_id); void WriteOrBufferHandshakeDone(); void WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame); void WriteOrBufferNewConnectionId( const QuicConnectionId& connection_id, uint64_t sequence_number, uint64_t retire_prior_to, const StatelessResetToken& stateless_reset_token); void WriteOrBufferRetireConnectionId(uint64_t sequence_number); void WriteOrBufferNewToken(absl::string_view token); bool OnControlFrameAcked(const QuicFrame& frame); void OnControlFrameLost(const QuicFrame& frame); void OnCanWrite(); bool RetransmitControlFrame(const QuicFrame& frame, TransmissionType type); bool IsControlFrameOutstanding(const QuicFrame& frame) const; bool HasPendingRetransmission() const; bool WillingToWrite() const; size_t NumBufferedMaxStreams() const; private: friend class test::QuicControlFrameManagerPeer; void WriteBufferedFrames(); void OnControlFrameSent(const QuicFrame& frame); void WritePendingRetransmission(); bool OnControlFrameIdAcked(QuicControlFrameId id); QuicFrame NextPendingRetransmission() const; bool HasBufferedFrames() const; void WriteOrBufferQuicFrame(QuicFrame frame); quiche::QuicheCircularDeque<QuicFrame> control_frames_; QuicControlFrameId last_control_frame_id_; QuicControlFrameId least_unacked_; QuicControlFrameId least_unsent_; quiche::QuicheLinkedHashMap<QuicControlFrameId, bool> pending_retransmissions_; DelegateInterface* delegate_; absl::flat_hash_map<QuicStreamId, QuicControlFrameId> window_update_frames_; size_t num_buffered_max_stream_frames_; }; } #endif #include "quiche/quic/core/quic_control_frame_manager.h" #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_retire_connection_id_frame.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const size_t kMaxNumControlFrames = 1000; } QuicControlFrameManager::QuicControlFrameManager(QuicSession* session) : last_control_frame_id_(kInvalidControlFrameId), least_unacked_(1), least_unsent_(1), delegate_(session), num_buffered_max_stream_frames_(0) {} QuicControlFrameManager::~QuicControlFrameManager() { while (!control_frames_.empty()) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); } } void QuicControlFrameManager::WriteOrBufferQuicFrame(QuicFrame frame) { const bool had_buffered_frames = HasBufferedFrames(); control_frames_.emplace_back(frame); if (control_frames_.size() > kMaxNumControlFrames) { delegate_->OnControlFrameManagerError( QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, absl::StrCat("More than ", kMaxNumControlFrames, "buffered control frames, least_unacked: ", least_unacked_, ", least_unsent_: ", least_unsent_)); return; } if (had_buffered_frames) { return; } WriteBufferedFrames(); } void QuicControlFrameManager::WriteOrBufferRstStream( QuicStreamId id, QuicResetStreamError error, QuicStreamOffset bytes_written) { QUIC_DVLOG(1) << "Writing RST_STREAM_FRAME"; WriteOrBufferQuicFrame((QuicFrame(new QuicRstStreamFrame( ++last_control_frame_id_, id, error, bytes_written)))); } void QuicControlFrameManager::WriteOrBufferGoAway( QuicErrorCode error, QuicStreamId last_good_stream_id, const std::string& reason) { QUIC_DVLOG(1) << "Writing GOAWAY_FRAME"; WriteOrBufferQuicFrame(QuicFrame(new QuicGoAwayFrame( ++last_control_frame_id_, error, last_good_stream_id, reason))); } void QuicControlFrameManager::WriteOrBufferWindowUpdate( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing WINDOW_UPDATE_FRAME"; WriteOrBufferQuicFrame(QuicFrame( QuicWindowUpdateFrame(++last_control_frame_id_, id, byte_offset))); } void QuicControlFrameManager::WriteOrBufferBlocked( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing BLOCKED_FRAME"; WriteOrBufferQuicFrame( QuicFrame(QuicBlockedFrame(++last_control_frame_id_, id, byte_offset))); } void QuicControlFrameManager::WriteOrBufferStreamsBlocked(QuicStreamCount count, bool unidirectional) { QUIC_DVLOG(1) << "Writing STREAMS_BLOCKED Frame"; QUIC_CODE_COUNT(quic_streams_blocked_transmits); WriteOrBufferQuicFrame(QuicFrame(QuicStreamsBlockedFrame( ++last_control_frame_id_, count, unidirectional))); } void QuicControlFrameManager::WriteOrBufferMaxStreams(QuicStreamCount count, bool unidirectional) { QUIC_DVLOG(1) << "Writing MAX_STREAMS Frame"; QUIC_CODE_COUNT(quic_max_streams_transmits); WriteOrBufferQuicFrame(QuicFrame( QuicMaxStreamsFrame(++last_control_frame_id_, count, unidirectional))); ++num_buffered_max_stream_frames_; } void QuicControlFrameManager::WriteOrBufferStopSending( QuicResetStreamError error, QuicStreamId stream_id) { QUIC_DVLOG(1) << "Writing STOP_SENDING_FRAME"; WriteOrBufferQuicFrame(QuicFrame( QuicStopSendingFrame(++last_control_frame_id_, stream_id, error))); } void QuicControlFrameManager::WriteOrBufferHandshakeDone() { QUIC_DVLOG(1) << "Writing HANDSHAKE_DONE"; WriteOrBufferQuicFrame( QuicFrame(QuicHandshakeDoneFrame(++last_control_frame_id_))); } void QuicControlFrameManager::WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame) { QUIC_DVLOG(1) << "Writing ACK_FREQUENCY frame"; QuicControlFrameId control_frame_id = ++last_control_frame_id_; WriteOrBufferQuicFrame( QuicFrame(new QuicAckFrequencyFrame(control_frame_id, control_frame_id, ack_frequency_frame.packet_tolerance, ack_frequency_frame.max_ack_delay))); } void QuicControlFrameManager::WriteOrBufferNewConnectionId( const QuicConnectionId& connection_id, uint64_t sequence_number, uint64_t retire_prior_to, const StatelessResetToken& stateless_reset_token) { QUIC_DVLOG(1) << "Writing NEW_CONNECTION_ID frame"; WriteOrBufferQuicFrame(QuicFrame(new QuicNewConnectionIdFrame( ++last_control_frame_id_, connection_id, sequence_number, stateless_reset_token, retire_prior_to))); } void QuicControlFrameManager::WriteOrBufferRetireConnectionId( uint64_t sequence_number) { QUIC_DVLOG(1) << "Writing RETIRE_CONNECTION_ID frame"; WriteOrBufferQuicFrame(QuicFrame(new QuicRetireConnectionIdFrame( ++last_control_frame_id_, sequence_number))); } void QuicControlFrameManager::WriteOrBufferNewToken(absl::string_view token) { QUIC_DVLOG(1) << "Writing NEW_TOKEN frame"; WriteOrBufferQuicFrame( QuicFrame(new QuicNewTokenFrame(++last_control_frame_id_, token))); } void QuicControlFrameManager::OnControlFrameSent(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { QUIC_BUG(quic_bug_12727_1) << "Send or retransmit a control frame with invalid control frame id"; return; } if (frame.type == WINDOW_UPDATE_FRAME) { QuicStreamId stream_id = frame.window_update_frame.stream_id; if (window_update_frames_.contains(stream_id) && id > window_update_frames_[stream_id]) { OnControlFrameIdAcked(window_update_frames_[stream_id]); } window_update_frames_[stream_id] = id; } if (pending_retransmissions_.contains(id)) { pending_retransmissions_.erase(id); return; } if (id > least_unsent_) { QUIC_BUG(quic_bug_10517_1) << "Try to send control frames out of order, id: " << id << " least_unsent: " << least_unsent_; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to send control frames out of order"); return; } ++least_unsent_; } bool QuicControlFrameManager::OnControlFrameAcked(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (!OnControlFrameIdAcked(id)) { return false; } if (frame.type == WINDOW_UPDATE_FRAME) { QuicStreamId stream_id = frame.window_update_frame.stream_id; if (window_update_frames_.contains(stream_id) && window_update_frames_[stream_id] == id) { window_update_frames_.erase(stream_id); } } if (frame.type == MAX_STREAMS_FRAME) { if (num_buffered_max_stream_frames_ == 0) { QUIC_BUG(invalid_num_buffered_max_stream_frames); } else { --num_buffered_max_stream_frames_; } } return true; } void QuicControlFrameManager::OnControlFrameLost(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_2) << "Try to mark unsent control frame as lost"; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to mark unsent control frame as lost"); return; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return; } if (!pending_retransmissions_.contains(id)) { pending_retransmissions_[id] = true; QUIC_BUG_IF(quic_bug_12727_2, pending_retransmissions_.size() > control_frames_.size()) << "least_unacked_: " << least_unacked_ << ", least_unsent_: " << least_unsent_; } } bool QuicControlFrameManager::IsControlFrameOutstanding( const QuicFrame& frame) const { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } return id < least_unacked_ + control_frames_.size() && id >= least_unacked_ && GetControlFrameId(control_frames_.at(id - least_unacked_)) != kInvalidControlFrameId; } bool QuicControlFrameManager::HasPendingRetransmission() const { return !pending_retransmissions_.empty(); } bool QuicControlFrameManager::WillingToWrite() const { return HasPendingRetransmission() || HasBufferedFrames(); } size_t QuicControlFrameManager::NumBufferedMaxStreams() const { return num_buffered_max_stream_frames_; } QuicFrame QuicControlFrameManager::NextPendingRetransmission() const { QUIC_BUG_IF(quic_bug_12727_3, pending_retransmissions_.empty()) << "Unexpected call to NextPendingRetransmission() with empty pending " << "retransmission list."; QuicControlFrameId id = pending_retransmissions_.begin()->first; return control_frames_.at(id - least_unacked_); } void QuicControlFrameManager::OnCanWrite() { if (HasPendingRetransmission()) { WritePendingRetransmission(); return; } WriteBufferedFrames(); } bool QuicControlFrameManager::RetransmitControlFrame(const QuicFrame& frame, TransmissionType type) { QUICHE_DCHECK(type == PTO_RETRANSMISSION); QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return true; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_3) << "Try to retransmit unsent control frame"; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to retransmit unsent control frame"); return false; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return true; } QuicFrame copy = CopyRetransmittableControlFrame(frame); QUIC_DVLOG(1) << "control frame manager is forced to retransmit frame: " << frame; if (delegate_->WriteControlFrame(copy, type)) { return true; } DeleteFrame(&copy); return false; } void QuicControlFrameManager::WriteBufferedFrames() { while (HasBufferedFrames()) { QuicFrame frame_to_send = control_frames_.at(least_unsent_ - least_unacked_); QuicFrame copy = CopyRetransmittableControlFrame(frame_to_send); if (!delegate_->WriteControlFrame(copy, NOT_RETRANSMISSION)) { DeleteFrame(&copy); break; } OnControlFrameSent(frame_to_send); } } void QuicControlFrameManager::WritePendingRetransmission() { while (HasPendingRetransmission()) { QuicFrame pending = NextPendingRetransmission(); QuicFrame copy = CopyRetransmittableControlFrame(pending); if (!delegate_->WriteControlFrame(copy, LOSS_RETRANSMISSION)) { DeleteFrame(&copy); break; } OnControlFrameSent(pending); } } bool QuicControlFrameManager::OnControlFrameIdAcked(QuicControlFrameId id) { if (id == kInvalidControlFrameId) { return false; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_4) << "Try to ack unsent control frame"; delegate_->OnControlFrameManagerError(QUIC_INTERNAL_ERROR, "Try to ack unsent control frame"); return false; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return false; } SetControlFrameId(kInvalidControlFrameId, &control_frames_.at(id - least_unacked_)); pending_retransmissions_.erase(id); while (!control_frames_.empty() && GetControlFrameId(control_frames_.front()) == kInvalidControlFrameId) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); ++least_unacked_; } return true; } bool QuicControlFrameManager::HasBufferedFrames() const { return least_unsent_ < least_unacked_ + control_frames_.size(); } }
#include "quiche/quic/core/quic_control_frame_manager.h" #include <memory> #include <utility> #include <vector> #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_retire_connection_id_frame.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::StrictMock; namespace quic { namespace test { class QuicControlFrameManagerPeer { public: static size_t QueueSize(QuicControlFrameManager* manager) { return manager->control_frames_.size(); } }; namespace { const QuicStreamId kTestStreamId = 5; const QuicRstStreamErrorCode kTestStopSendingCode = QUIC_STREAM_ENCODER_STREAM_ERROR; class QuicControlFrameManagerTest : public QuicTest { public: QuicControlFrameManagerTest() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_SERVER)), session_(std::make_unique<StrictMock<MockQuicSession>>(connection_)), manager_(std::make_unique<QuicControlFrameManager>(session_.get())) { connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<StrictMock<MockQuicSession>> session_; std::unique_ptr<QuicControlFrameManager> manager_; }; TEST_F(QuicControlFrameManagerTest, InitialState) { EXPECT_EQ(0u, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferRstStream) { QuicRstStreamFrame rst_stream = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&rst_stream](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); EXPECT_EQ(rst_stream, *frame.rst_stream_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferRstStream( rst_stream.stream_id, QuicResetStreamError::FromInternal(rst_stream.error_code), rst_stream.byte_offset); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&rst_stream))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferGoAway) { QuicGoAwayFrame goaway = {1, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&goaway](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(GOAWAY_FRAME, frame.type); EXPECT_EQ(goaway, *frame.goaway_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferGoAway(goaway.error_code, goaway.last_good_stream_id, goaway.reason_phrase); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&goaway))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferWindowUpdate) { QuicWindowUpdateFrame window_update = {1, kTestStreamId, 100}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&window_update](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(window_update, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferWindowUpdate(window_update.stream_id, window_update.max_data); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(window_update))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferBlocked) { QuicBlockedFrame blocked = {1, kTestStreamId, 10}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&blocked](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(blocked, frame.blocked_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferBlocked(blocked.stream_id, blocked.offset); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(blocked))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferStopSending) { QuicStopSendingFrame stop_sending = {1, kTestStreamId, kTestStopSendingCode}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&stop_sending](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); EXPECT_EQ(stop_sending, frame.stop_sending_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(stop_sending.error_code), stop_sending.stream_id); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(stop_sending))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, BufferWhenWriteControlFrameReturnsFalse) { QuicBlockedFrame blocked = {1, kTestStreamId, 0}; EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(blocked.stream_id, blocked.offset); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(blocked))); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, BufferThenSendThenBuffer) { InSequence s; QuicBlockedFrame frame1 = {1, kTestStreamId, 0}; QuicBlockedFrame frame2 = {2, kTestStreamId + 1, 1}; EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(frame1.stream_id, frame1.offset); manager_->WriteOrBufferBlocked(frame2.stream_id, frame2.offset); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame2))); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->OnCanWrite(); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, OnControlFrameAcked) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; QuicStopSendingFrame frame5 = {5, kTestStreamId, kTestStopSendingCode}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(5) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(frame5.error_code), frame5.stream_id); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame4))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame5))); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame3))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); EXPECT_EQ(5, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(&frame2))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_EQ(5, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(&frame1))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_EQ(2, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_FALSE(manager_->OnControlFrameAcked(QuicFrame(&frame2))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_EQ(2, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame4))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame4))); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame5))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame5))); EXPECT_EQ(0, QuicControlFrameManagerPeer::QueueSize(manager_.get())); } TEST_F(QuicControlFrameManagerTest, OnControlFrameLost) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; QuicStopSendingFrame frame5 = {5, kTestStreamId, kTestStopSendingCode}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(3) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(frame5.error_code), frame5.stream_id); manager_->OnControlFrameLost(QuicFrame(&frame1)); manager_->OnControlFrameLost(QuicFrame(&frame2)); manager_->OnControlFrameLost(QuicFrame(frame3)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); manager_->OnControlFrameAcked(QuicFrame(&frame2)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame1](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); EXPECT_EQ(frame1, *frame.rst_stream_frame); ClearControlFrame(frame); return true; })); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame3](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(frame3, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame4](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(frame4, frame.blocked_frame); ClearControlFrame(frame); return true; })); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame5](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); EXPECT_EQ(frame5, frame.stop_sending_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, RetransmitControlFrame) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(4) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->OnControlFrameAcked(QuicFrame(&frame2)); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(0); EXPECT_TRUE( manager_->RetransmitControlFrame(QuicFrame(&frame2), PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame3](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(frame3, frame.window_update_frame); ClearControlFrame(frame); return true; })); EXPECT_TRUE( manager_->RetransmitControlFrame(QuicFrame(frame3), PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame4](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(frame4, frame.blocked_frame); return false; })); EXPECT_FALSE( manager_->RetransmitControlFrame(QuicFrame(frame4), PTO_RETRANSMISSION)); } TEST_F(QuicControlFrameManagerTest, SendAndAckAckFrequencyFrame) { QuicAckFrequencyFrame frame_to_send; frame_to_send.packet_tolerance = 10; frame_to_send.max_ack_delay = QuicTime::Delta::FromMilliseconds(24); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferAckFrequency(frame_to_send); QuicAckFrequencyFrame expected_ack_frequency = frame_to_send; expected_ack_frequency.control_frame_id = 1; expected_ack_frequency.sequence_number = 1; EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&expected_ack_frequency))); } TEST_F(QuicControlFrameManagerTest, NewAndRetireConnectionIdFrames) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); QuicNewConnectionIdFrame new_connection_id_frame( 1, TestConnectionId(3), 1, {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, 1); manager_->WriteOrBufferNewConnectionId( new_connection_id_frame.connection_id, new_connection_id_frame.sequence_number, new_connection_id_frame.retire_prior_to, new_connection_id_frame.stateless_reset_token); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); QuicRetireConnectionIdFrame retire_connection_id_frame(2, 0); manager_->WriteOrBufferRetireConnectionId( retire_connection_id_frame.sequence_number); EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&new_connection_id_frame))); EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&retire_connection_id_frame))); } TEST_F(QuicControlFrameManagerTest, DonotRetransmitOldWindowUpdates) { QuicWindowUpdateFrame window_update1(1, kTestStreamId, 200); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update1.stream_id, window_update1.max_data); QuicWindowUpdateFrame window_update2(2, kTestStreamId, 300); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update2.stream_id, window_update2.max_data); manager_->OnControlFrameLost(QuicFrame(window_update1)); manager_->OnControlFrameLost(QuicFrame(window_update2)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&window_update2](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(window_update2, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, RetransmitWindowUpdateOfDifferentStreams) { QuicWindowUpdateFrame window_update1(1, kTestStreamId + 2, 200); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update1.stream_id, window_update1.max_data); QuicWindowUpdateFrame window_update2(2, kTestStreamId + 4, 300); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update2.stream_id, window_update2.max_data); manager_->OnControlFrameLost(QuicFrame(window_update1)); manager_->OnControlFrameLost(QuicFrame(window_update2)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, TooManyBufferedControlFrames) { EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); for (size_t i = 0; i < 1000; ++i) { manager_->WriteOrBufferRstStream( kTestStreamId, QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), 0); } EXPECT_CALL( *connection_, CloseConnection(QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, _, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)); manager_->WriteOrBufferRstStream( kTestStreamId, QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), 0); } TEST_F(QuicControlFrameManagerTest, NumBufferedMaxStreams) { std::vector<QuicMaxStreamsFrame> max_streams_frames; size_t expected_buffered_frames = 0; for (int i = 0; i < 5; ++i) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke([&max_streams_frames](const QuicFrame& frame, TransmissionType ) { max_streams_frames.push_back(frame.max_streams_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferMaxStreams(0, false); EXPECT_EQ(++expected_buffered_frames, manager_->NumBufferedMaxStreams()); } for (const QuicMaxStreamsFrame& frame : max_streams_frames) { manager_->OnControlFrameAcked(QuicFrame(frame)); EXPECT_EQ(--expected_buffered_frames, manager_->NumBufferedMaxStreams()); } EXPECT_EQ(0, manager_->NumBufferedMaxStreams()); } } } }
240
cpp
google/quiche
quic_packet_number
quiche/quic/core/quic_packet_number.cc
quiche/quic/core/quic_packet_number_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_PACKET_NUMBER_H_ #define QUICHE_QUIC_CORE_QUIC_PACKET_NUMBER_H_ #include <limits> #include <ostream> #include <string> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { class QUICHE_EXPORT QuicPacketNumber { public: constexpr QuicPacketNumber() : packet_number_(UninitializedPacketNumber()) {} explicit constexpr QuicPacketNumber(uint64_t packet_number) : packet_number_(packet_number) { QUICHE_DCHECK_NE(UninitializedPacketNumber(), packet_number) << "Use default constructor for uninitialized packet number"; } static constexpr uint64_t UninitializedPacketNumber() { return std::numeric_limits<uint64_t>::max(); } void Clear(); void UpdateMax(QuicPacketNumber new_value); uint64_t Hash() const; uint64_t ToUint64() const; bool IsInitialized() const; QuicPacketNumber& operator++(); QuicPacketNumber operator++(int); QuicPacketNumber& operator--(); QuicPacketNumber operator--(int); QuicPacketNumber& operator+=(uint64_t delta); QuicPacketNumber& operator-=(uint64_t delta); std::string ToString() const; QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os, const QuicPacketNumber& p); private: friend inline bool operator==(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline bool operator!=(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline bool operator<(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline bool operator<=(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline bool operator>(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline bool operator>=(QuicPacketNumber lhs, QuicPacketNumber rhs); friend inline QuicPacketNumber operator+(QuicPacketNumber lhs, uint64_t delta); friend inline QuicPacketNumber operator-(QuicPacketNumber lhs, uint64_t delta); friend inline uint64_t operator-(QuicPacketNumber lhs, QuicPacketNumber rhs); uint64_t packet_number_; }; class QUICHE_EXPORT QuicPacketNumberHash { public: uint64_t operator()(QuicPacketNumber packet_number) const noexcept { return packet_number.Hash(); } }; inline bool operator==(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ == rhs.packet_number_; } inline bool operator!=(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ != rhs.packet_number_; } inline bool operator<(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ < rhs.packet_number_; } inline bool operator<=(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ <= rhs.packet_number_; } inline bool operator>(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ > rhs.packet_number_; } inline bool operator>=(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized()) << lhs << " vs. " << rhs; return lhs.packet_number_ >= rhs.packet_number_; } inline QuicPacketNumber operator+(QuicPacketNumber lhs, uint64_t delta) { #ifndef NDEBUG QUICHE_DCHECK(lhs.IsInitialized()); QUICHE_DCHECK_GT(std::numeric_limits<uint64_t>::max() - lhs.ToUint64(), delta); #endif return QuicPacketNumber(lhs.packet_number_ + delta); } inline QuicPacketNumber operator-(QuicPacketNumber lhs, uint64_t delta) { #ifndef NDEBUG QUICHE_DCHECK(lhs.IsInitialized()); QUICHE_DCHECK_GE(lhs.ToUint64(), delta); #endif return QuicPacketNumber(lhs.packet_number_ - delta); } inline uint64_t operator-(QuicPacketNumber lhs, QuicPacketNumber rhs) { QUICHE_DCHECK(lhs.IsInitialized() && rhs.IsInitialized() && lhs >= rhs) << lhs << " vs. " << rhs; return lhs.packet_number_ - rhs.packet_number_; } } #endif #include "quiche/quic/core/quic_packet_number.h" #include <algorithm> #include <limits> #include <ostream> #include <string> #include "absl/strings/str_cat.h" namespace quic { void QuicPacketNumber::Clear() { packet_number_ = UninitializedPacketNumber(); } void QuicPacketNumber::UpdateMax(QuicPacketNumber new_value) { if (!new_value.IsInitialized()) { return; } if (!IsInitialized()) { packet_number_ = new_value.ToUint64(); } else { packet_number_ = std::max(packet_number_, new_value.ToUint64()); } } uint64_t QuicPacketNumber::Hash() const { QUICHE_DCHECK(IsInitialized()); return packet_number_; } uint64_t QuicPacketNumber::ToUint64() const { QUICHE_DCHECK(IsInitialized()); return packet_number_; } bool QuicPacketNumber::IsInitialized() const { return packet_number_ != UninitializedPacketNumber(); } QuicPacketNumber& QuicPacketNumber::operator++() { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_LT(ToUint64(), std::numeric_limits<uint64_t>::max() - 1); #endif packet_number_++; return *this; } QuicPacketNumber QuicPacketNumber::operator++(int) { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_LT(ToUint64(), std::numeric_limits<uint64_t>::max() - 1); #endif QuicPacketNumber previous(*this); packet_number_++; return previous; } QuicPacketNumber& QuicPacketNumber::operator--() { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_GE(ToUint64(), 1UL); #endif packet_number_--; return *this; } QuicPacketNumber QuicPacketNumber::operator--(int) { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_GE(ToUint64(), 1UL); #endif QuicPacketNumber previous(*this); packet_number_--; return previous; } QuicPacketNumber& QuicPacketNumber::operator+=(uint64_t delta) { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_GT(std::numeric_limits<uint64_t>::max() - ToUint64(), delta); #endif packet_number_ += delta; return *this; } QuicPacketNumber& QuicPacketNumber::operator-=(uint64_t delta) { #ifndef NDEBUG QUICHE_DCHECK(IsInitialized()); QUICHE_DCHECK_GE(ToUint64(), delta); #endif packet_number_ -= delta; return *this; } std::string QuicPacketNumber::ToString() const { if (!IsInitialized()) { return "uninitialized"; } return absl::StrCat(ToUint64()); } std::ostream& operator<<(std::ostream& os, const QuicPacketNumber& p) { os << p.ToString(); return os; } }
#include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { TEST(QuicPacketNumberTest, BasicTest) { QuicPacketNumber num; EXPECT_FALSE(num.IsInitialized()); QuicPacketNumber num2(10); EXPECT_TRUE(num2.IsInitialized()); EXPECT_EQ(10u, num2.ToUint64()); EXPECT_EQ(10u, num2.Hash()); num2.UpdateMax(num); EXPECT_EQ(10u, num2.ToUint64()); num2.UpdateMax(QuicPacketNumber(9)); EXPECT_EQ(10u, num2.ToUint64()); num2.UpdateMax(QuicPacketNumber(11)); EXPECT_EQ(11u, num2.ToUint64()); num2.Clear(); EXPECT_FALSE(num2.IsInitialized()); num2.UpdateMax(QuicPacketNumber(9)); EXPECT_EQ(9u, num2.ToUint64()); QuicPacketNumber num4(0); EXPECT_TRUE(num4.IsInitialized()); EXPECT_EQ(0u, num4.ToUint64()); EXPECT_EQ(0u, num4.Hash()); num4.Clear(); EXPECT_FALSE(num4.IsInitialized()); } TEST(QuicPacketNumberTest, Operators) { QuicPacketNumber num(100); EXPECT_EQ(QuicPacketNumber(100), num++); EXPECT_EQ(QuicPacketNumber(101), num); EXPECT_EQ(QuicPacketNumber(101), num--); EXPECT_EQ(QuicPacketNumber(100), num); EXPECT_EQ(QuicPacketNumber(101), ++num); EXPECT_EQ(QuicPacketNumber(100), --num); QuicPacketNumber num3(0); EXPECT_EQ(QuicPacketNumber(0), num3++); EXPECT_EQ(QuicPacketNumber(1), num3); EXPECT_EQ(QuicPacketNumber(2), ++num3); EXPECT_EQ(QuicPacketNumber(2), num3--); EXPECT_EQ(QuicPacketNumber(1), num3); EXPECT_EQ(QuicPacketNumber(0), --num3); } } } }
241
cpp
google/quiche
quic_tag
quiche/quic/core/quic_tag.cc
quiche/quic/core/quic_tag_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_TAG_H_ #define QUICHE_QUIC_CORE_QUIC_TAG_H_ #include <cstdint> #include <map> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { using QuicTag = uint32_t; using QuicTagValueMap = std::map<QuicTag, std::string>; using QuicTagVector = std::vector<QuicTag>; QUICHE_EXPORT QuicTag MakeQuicTag(uint8_t a, uint8_t b, uint8_t c, uint8_t d); QUICHE_EXPORT bool ContainsQuicTag(const QuicTagVector& tag_vector, QuicTag tag); QUICHE_EXPORT bool FindMutualQuicTag(const QuicTagVector& our_tags, const QuicTagVector& their_tags, QuicTag* out_result, size_t* out_index); QUICHE_EXPORT std::string QuicTagToString(QuicTag tag); QUICHE_EXPORT QuicTag ParseQuicTag(absl::string_view tag_string); QUICHE_EXPORT QuicTagVector ParseQuicTagVector(absl::string_view tags_string); } #endif #include "quiche/quic/core/quic_tag.h" #include <algorithm> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_split.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_text_utils.h" namespace quic { bool FindMutualQuicTag(const QuicTagVector& our_tags, const QuicTagVector& their_tags, QuicTag* out_result, size_t* out_index) { const size_t num_our_tags = our_tags.size(); const size_t num_their_tags = their_tags.size(); for (size_t i = 0; i < num_our_tags; i++) { for (size_t j = 0; j < num_their_tags; j++) { if (our_tags[i] == their_tags[j]) { *out_result = our_tags[i]; if (out_index != nullptr) { *out_index = j; } return true; } } } return false; } std::string QuicTagToString(QuicTag tag) { if (tag == 0) { return "0"; } char chars[sizeof tag]; bool ascii = true; const QuicTag orig_tag = tag; for (size_t i = 0; i < ABSL_ARRAYSIZE(chars); i++) { chars[i] = static_cast<char>(tag); if ((chars[i] == 0 || chars[i] == '\xff') && i == ABSL_ARRAYSIZE(chars) - 1) { chars[i] = ' '; } if (!absl::ascii_isprint(static_cast<unsigned char>(chars[i]))) { ascii = false; break; } tag >>= 8; } if (ascii) { return std::string(chars, sizeof(chars)); } return absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(&orig_tag), sizeof(orig_tag))); } uint32_t MakeQuicTag(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { return static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 | static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24; } bool ContainsQuicTag(const QuicTagVector& tag_vector, QuicTag tag) { return std::find(tag_vector.begin(), tag_vector.end(), tag) != tag_vector.end(); } QuicTag ParseQuicTag(absl::string_view tag_string) { quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&tag_string); std::string tag_bytes; if (tag_string.length() == 8) { tag_bytes = absl::HexStringToBytes(tag_string); tag_string = tag_bytes; } QuicTag tag = 0; for (auto it = tag_string.rbegin(); it != tag_string.rend(); ++it) { unsigned char token_char = static_cast<unsigned char>(*it); tag <<= 8; tag |= token_char; } return tag; } QuicTagVector ParseQuicTagVector(absl::string_view tags_string) { QuicTagVector tag_vector; quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&tags_string); if (!tags_string.empty()) { std::vector<absl::string_view> tag_strings = absl::StrSplit(tags_string, ','); for (absl::string_view tag_string : tag_strings) { tag_vector.push_back(ParseQuicTag(tag_string)); } } return tag_vector; } }
#include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicTagTest : public QuicTest {}; TEST_F(QuicTagTest, TagToString) { EXPECT_EQ("SCFG", QuicTagToString(kSCFG)); EXPECT_EQ("SNO ", QuicTagToString(kServerNonceTag)); EXPECT_EQ("CRT ", QuicTagToString(kCertificateTag)); EXPECT_EQ("CHLO", QuicTagToString(MakeQuicTag('C', 'H', 'L', 'O'))); EXPECT_EQ("43484c1f", QuicTagToString(MakeQuicTag('C', 'H', 'L', '\x1f'))); } TEST_F(QuicTagTest, MakeQuicTag) { QuicTag tag = MakeQuicTag('A', 'B', 'C', 'D'); char bytes[4]; memcpy(bytes, &tag, 4); EXPECT_EQ('A', bytes[0]); EXPECT_EQ('B', bytes[1]); EXPECT_EQ('C', bytes[2]); EXPECT_EQ('D', bytes[3]); } TEST_F(QuicTagTest, ParseQuicTag) { QuicTag tag_abcd = MakeQuicTag('A', 'B', 'C', 'D'); EXPECT_EQ(ParseQuicTag("ABCD"), tag_abcd); EXPECT_EQ(ParseQuicTag("ABCDE"), tag_abcd); QuicTag tag_efgh = MakeQuicTag('E', 'F', 'G', 'H'); EXPECT_EQ(ParseQuicTag("EFGH"), tag_efgh); QuicTag tag_ijk = MakeQuicTag('I', 'J', 'K', 0); EXPECT_EQ(ParseQuicTag("IJK"), tag_ijk); QuicTag tag_l = MakeQuicTag('L', 0, 0, 0); EXPECT_EQ(ParseQuicTag("L"), tag_l); QuicTag tag_hex = MakeQuicTag('M', 'N', 'O', static_cast<char>(255)); EXPECT_EQ(ParseQuicTag("4d4e4fff"), tag_hex); EXPECT_EQ(ParseQuicTag("4D4E4FFF"), tag_hex); QuicTag tag_with_numbers = MakeQuicTag('P', 'Q', '1', '2'); EXPECT_EQ(ParseQuicTag("PQ12"), tag_with_numbers); QuicTag tag_with_custom_chars = MakeQuicTag('r', '$', '_', '7'); EXPECT_EQ(ParseQuicTag("r$_7"), tag_with_custom_chars); QuicTag tag_zero = 0; EXPECT_EQ(ParseQuicTag(""), tag_zero); QuicTagVector tag_vector; EXPECT_EQ(ParseQuicTagVector(""), tag_vector); EXPECT_EQ(ParseQuicTagVector(" "), tag_vector); tag_vector.push_back(tag_abcd); EXPECT_EQ(ParseQuicTagVector("ABCD"), tag_vector); tag_vector.push_back(tag_efgh); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH"), tag_vector); tag_vector.push_back(tag_ijk); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK"), tag_vector); tag_vector.push_back(tag_l); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L"), tag_vector); tag_vector.push_back(tag_hex); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff"), tag_vector); tag_vector.push_back(tag_with_numbers); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12"), tag_vector); tag_vector.push_back(tag_with_custom_chars); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12,r$_7"), tag_vector); tag_vector.push_back(tag_zero); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12,r$_7,"), tag_vector); } } } }
242
cpp
google/quiche
quic_server_id
quiche/quic/core/quic_server_id.cc
quiche/quic/core/quic_server_id_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_SERVER_ID_H_ #define QUICHE_QUIC_CORE_QUIC_SERVER_ID_H_ #include <cstdint> #include <optional> #include <string> #include "absl/hash/hash.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QuicServerId { public: static std::optional<QuicServerId> ParseFromHostPortString( absl::string_view host_port_string); QuicServerId(); QuicServerId(std::string host, uint16_t port); QuicServerId(std::string host, uint16_t port, bool privacy_mode_enabled); ~QuicServerId(); bool operator<(const QuicServerId& other) const; bool operator==(const QuicServerId& other) const; bool operator!=(const QuicServerId& other) const; const std::string& host() const { return host_; } uint16_t port() const { return port_; } bool privacy_mode_enabled() const { return privacy_mode_enabled_; } std::string ToHostPortString() const; absl::string_view GetHostWithoutIpv6Brackets() const; std::string GetHostWithIpv6Brackets() const; template <typename H> friend H AbslHashValue(H h, const QuicServerId& server_id) { return H::combine(std::move(h), server_id.host(), server_id.port(), server_id.privacy_mode_enabled()); } private: std::string host_; uint16_t port_; bool privacy_mode_enabled_; }; using QuicServerIdHash = absl::Hash<QuicServerId>; } #endif #include "quiche/quic/core/quic_server_id.h" #include <optional> #include <string> #include <tuple> #include <utility> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { std::optional<QuicServerId> QuicServerId::ParseFromHostPortString( absl::string_view host_port_string) { url::Component username_component; url::Component password_component; url::Component host_component; url::Component port_component; url::ParseAuthority(host_port_string.data(), url::Component(0, host_port_string.size()), &username_component, &password_component, &host_component, &port_component); if (username_component.is_valid() || password_component.is_valid() || !host_component.is_nonempty() || !port_component.is_nonempty()) { QUICHE_DVLOG(1) << "QuicServerId could not be parsed: " << host_port_string; return std::nullopt; } std::string hostname(host_port_string.data() + host_component.begin, host_component.len); int parsed_port_number = url::ParsePort(host_port_string.data(), port_component); if (parsed_port_number <= 0) { QUICHE_DVLOG(1) << "Port could not be parsed while parsing QuicServerId from: " << host_port_string; return std::nullopt; } QUICHE_DCHECK_LE(parsed_port_number, std::numeric_limits<uint16_t>::max()); return QuicServerId(std::move(hostname), static_cast<uint16_t>(parsed_port_number)); } QuicServerId::QuicServerId() : QuicServerId("", 0, false) {} QuicServerId::QuicServerId(std::string host, uint16_t port) : QuicServerId(std::move(host), port, false) {} QuicServerId::QuicServerId(std::string host, uint16_t port, bool privacy_mode_enabled) : host_(std::move(host)), port_(port), privacy_mode_enabled_(privacy_mode_enabled) {} QuicServerId::~QuicServerId() {} bool QuicServerId::operator<(const QuicServerId& other) const { return std::tie(port_, host_, privacy_mode_enabled_) < std::tie(other.port_, other.host_, other.privacy_mode_enabled_); } bool QuicServerId::operator==(const QuicServerId& other) const { return privacy_mode_enabled_ == other.privacy_mode_enabled_ && host_ == other.host_ && port_ == other.port_; } bool QuicServerId::operator!=(const QuicServerId& other) const { return !(*this == other); } std::string QuicServerId::ToHostPortString() const { return absl::StrCat(GetHostWithIpv6Brackets(), ":", port_); } absl::string_view QuicServerId::GetHostWithoutIpv6Brackets() const { if (host_.length() > 2 && host_.front() == '[' && host_.back() == ']') { return absl::string_view(host_.data() + 1, host_.length() - 2); } else { return host_; } } std::string QuicServerId::GetHostWithIpv6Brackets() const { if (!absl::StrContains(host_, ':') || host_.length() <= 2 || (host_.front() == '[' && host_.back() == ']')) { return host_; } else { return absl::StrCat("[", host_, "]"); } } }
#include "quiche/quic/core/quic_server_id.h" #include <optional> #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic::test { namespace { using ::testing::Optional; using ::testing::Property; class QuicServerIdTest : public QuicTest {}; TEST_F(QuicServerIdTest, Constructor) { QuicServerId google_server_id("google.com", 10, false); EXPECT_EQ("google.com", google_server_id.host()); EXPECT_EQ(10, google_server_id.port()); EXPECT_FALSE(google_server_id.privacy_mode_enabled()); QuicServerId private_server_id("mail.google.com", 12, true); EXPECT_EQ("mail.google.com", private_server_id.host()); EXPECT_EQ(12, private_server_id.port()); EXPECT_TRUE(private_server_id.privacy_mode_enabled()); } TEST_F(QuicServerIdTest, LessThan) { QuicServerId a_10_https("a.com", 10, false); QuicServerId a_11_https("a.com", 11, false); QuicServerId b_10_https("b.com", 10, false); QuicServerId b_11_https("b.com", 11, false); QuicServerId a_10_https_private("a.com", 10, true); QuicServerId a_11_https_private("a.com", 11, true); QuicServerId b_10_https_private("b.com", 10, true); QuicServerId b_11_https_private("b.com", 11, true); EXPECT_FALSE(a_10_https < a_10_https); EXPECT_TRUE(a_10_https < a_10_https_private); EXPECT_FALSE(a_10_https_private < a_10_https); EXPECT_FALSE(a_10_https_private < a_10_https_private); bool left_privacy; bool right_privacy; for (int i = 0; i < 4; i++) { left_privacy = (i / 2 == 0); right_privacy = (i % 2 == 0); QuicServerId a_10_https_left_private("a.com", 10, left_privacy); QuicServerId a_10_https_right_private("a.com", 10, right_privacy); QuicServerId a_11_https_left_private("a.com", 11, left_privacy); QuicServerId a_11_https_right_private("a.com", 11, right_privacy); QuicServerId b_10_https_left_private("b.com", 10, left_privacy); QuicServerId b_10_https_right_private("b.com", 10, right_privacy); QuicServerId b_11_https_left_private("b.com", 11, left_privacy); QuicServerId b_11_https_right_private("b.com", 11, right_privacy); EXPECT_TRUE(a_10_https_left_private < a_11_https_right_private); EXPECT_TRUE(a_10_https_left_private < b_10_https_right_private); EXPECT_TRUE(a_10_https_left_private < b_11_https_right_private); EXPECT_FALSE(a_11_https_left_private < a_10_https_right_private); EXPECT_FALSE(a_11_https_left_private < b_10_https_right_private); EXPECT_TRUE(a_11_https_left_private < b_11_https_right_private); EXPECT_FALSE(b_10_https_left_private < a_10_https_right_private); EXPECT_TRUE(b_10_https_left_private < a_11_https_right_private); EXPECT_TRUE(b_10_https_left_private < b_11_https_right_private); EXPECT_FALSE(b_11_https_left_private < a_10_https_right_private); EXPECT_FALSE(b_11_https_left_private < a_11_https_right_private); EXPECT_FALSE(b_11_https_left_private < b_10_https_right_private); } } TEST_F(QuicServerIdTest, Equals) { bool left_privacy; bool right_privacy; for (int i = 0; i < 2; i++) { left_privacy = right_privacy = (i == 0); QuicServerId a_10_https_right_private("a.com", 10, right_privacy); QuicServerId a_11_https_right_private("a.com", 11, right_privacy); QuicServerId b_10_https_right_private("b.com", 10, right_privacy); QuicServerId b_11_https_right_private("b.com", 11, right_privacy); EXPECT_NE(a_10_https_right_private, a_11_https_right_private); EXPECT_NE(a_10_https_right_private, b_10_https_right_private); EXPECT_NE(a_10_https_right_private, b_11_https_right_private); QuicServerId new_a_10_https_left_private("a.com", 10, left_privacy); QuicServerId new_a_11_https_left_private("a.com", 11, left_privacy); QuicServerId new_b_10_https_left_private("b.com", 10, left_privacy); QuicServerId new_b_11_https_left_private("b.com", 11, left_privacy); EXPECT_EQ(new_a_10_https_left_private, a_10_https_right_private); EXPECT_EQ(new_a_11_https_left_private, a_11_https_right_private); EXPECT_EQ(new_b_10_https_left_private, b_10_https_right_private); EXPECT_EQ(new_b_11_https_left_private, b_11_https_right_private); } for (int i = 0; i < 2; i++) { right_privacy = (i == 0); QuicServerId a_10_https_right_private("a.com", 10, right_privacy); QuicServerId a_11_https_right_private("a.com", 11, right_privacy); QuicServerId b_10_https_right_private("b.com", 10, right_privacy); QuicServerId b_11_https_right_private("b.com", 11, right_privacy); QuicServerId new_a_10_https_left_private("a.com", 10, false); EXPECT_NE(new_a_10_https_left_private, a_11_https_right_private); EXPECT_NE(new_a_10_https_left_private, b_10_https_right_private); EXPECT_NE(new_a_10_https_left_private, b_11_https_right_private); } QuicServerId a_10_https_private("a.com", 10, true); QuicServerId new_a_10_https_no_private("a.com", 10, false); EXPECT_NE(new_a_10_https_no_private, a_10_https_private); } TEST_F(QuicServerIdTest, Parse) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test:500"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "host.test"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 500))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::privacy_mode_enabled, false))); } TEST_F(QuicServerIdTest, CannotParseMissingPort) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseEmptyPort) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test:"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseEmptyHost) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString(":500"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseUserInfo) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("[email protected]:500"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, ParseIpv6Literal) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("[::1]:400"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "[::1]"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 400))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::privacy_mode_enabled, false))); } TEST_F(QuicServerIdTest, ParseUnbracketedIpv6Literal) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("::1:400"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "::1"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 400))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::privacy_mode_enabled, false))); } TEST_F(QuicServerIdTest, AddBracketsToIpv6) { QuicServerId server_id("::1", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "[::1]"); EXPECT_EQ(server_id.ToHostPortString(), "[::1]:100"); } TEST_F(QuicServerIdTest, AddBracketsAlreadyIncluded) { QuicServerId server_id("[::1]", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "[::1]"); EXPECT_EQ(server_id.ToHostPortString(), "[::1]:100"); } TEST_F(QuicServerIdTest, AddBracketsNotAddedToNonIpv6) { QuicServerId server_id("host.test", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "host.test"); EXPECT_EQ(server_id.ToHostPortString(), "host.test:100"); } TEST_F(QuicServerIdTest, RemoveBracketsFromIpv6) { QuicServerId server_id("[::1]", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "::1"); } TEST_F(QuicServerIdTest, RemoveBracketsNotIncluded) { QuicServerId server_id("::1", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "::1"); } TEST_F(QuicServerIdTest, RemoveBracketsFromNonIpv6) { QuicServerId server_id("host.test", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "host.test"); } } }
243
cpp
google/quiche
quic_crypto_stream
quiche/quic/core/quic_crypto_stream.cc
quiche/quic/core/quic_crypto_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CRYPTO_STREAM_H_ #define QUICHE_QUIC_CORE_QUIC_CRYPTO_STREAM_H_ #include <array> #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class CachedNetworkParameters; class QuicSession; class QUICHE_EXPORT QuicCryptoStream : public QuicStream { public: explicit QuicCryptoStream(QuicSession* session); QuicCryptoStream(const QuicCryptoStream&) = delete; QuicCryptoStream& operator=(const QuicCryptoStream&) = delete; ~QuicCryptoStream() override; static QuicByteCount CryptoMessageFramingOverhead( QuicTransportVersion version, QuicConnectionId connection_id); void OnStreamFrame(const QuicStreamFrame& frame) override; void OnDataAvailable() override; void OnCryptoFrame(const QuicCryptoFrame& frame); bool OnCryptoFrameAcked(const QuicCryptoFrame& frame, QuicTime::Delta ack_delay_time); void OnStreamReset(const QuicRstStreamFrame& frame) override; virtual bool ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) = 0; virtual void WriteCryptoData(EncryptionLevel level, absl::string_view data); virtual ssl_early_data_reason_t EarlyDataReason() const = 0; virtual bool encryption_established() const = 0; virtual bool one_rtt_keys_available() const = 0; virtual const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const = 0; virtual CryptoMessageParser* crypto_message_parser() = 0; virtual void OnPacketDecrypted(EncryptionLevel level) = 0; virtual void OnOneRttPacketAcknowledged() = 0; virtual void OnHandshakePacketSent() = 0; virtual void OnHandshakeDoneReceived() = 0; virtual void OnNewTokenReceived(absl::string_view token) = 0; virtual std::string GetAddressToken( const CachedNetworkParameters* cached_network_params) const = 0; virtual bool ValidateAddressToken(absl::string_view token) const = 0; virtual const CachedNetworkParameters* PreviousCachedNetworkParams() const = 0; virtual void SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) = 0; virtual HandshakeState GetHandshakeState() const = 0; virtual void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> state) = 0; virtual size_t BufferSizeLimitForLevel(EncryptionLevel level) const; virtual std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; virtual SSL* GetSsl() const = 0; void NeuterUnencryptedStreamData(); void NeuterStreamDataOfEncryptionLevel(EncryptionLevel level); void OnStreamDataConsumed(QuicByteCount bytes_consumed) override; virtual bool HasPendingCryptoRetransmission() const; void WritePendingCryptoRetransmission(); void WritePendingRetransmission() override; bool RetransmitStreamData(QuicStreamOffset offset, QuicByteCount data_length, bool fin, TransmissionType type) override; QuicConsumedData RetransmitStreamDataAtLevel( QuicStreamOffset retransmission_offset, QuicByteCount retransmission_length, EncryptionLevel encryption_level, TransmissionType type); uint64_t crypto_bytes_read() const; QuicByteCount BytesReadOnLevel(EncryptionLevel level) const; QuicByteCount BytesSentOnLevel(EncryptionLevel level) const; bool WriteCryptoFrame(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer); void OnCryptoFrameLost(QuicCryptoFrame* crypto_frame); bool RetransmitData(QuicCryptoFrame* crypto_frame, TransmissionType type); void WriteBufferedCryptoFrames(); bool HasBufferedCryptoFrames() const; bool IsFrameOutstanding(EncryptionLevel level, size_t offset, size_t length) const; bool IsWaitingForAcks() const; virtual void OnDataAvailableInSequencer(QuicStreamSequencer* sequencer, EncryptionLevel level); QuicStreamSequencer* GetStreamSequencerForPacketNumberSpace( PacketNumberSpace packet_number_space) { return &substreams_[packet_number_space].sequencer; } virtual bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const = 0; virtual EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const = 0; private: struct QUICHE_EXPORT CryptoSubstream { CryptoSubstream(QuicCryptoStream* crypto_stream); QuicStreamSequencer sequencer; QuicStreamSendBuffer send_buffer; }; QuicIntervalSet<QuicStreamOffset> bytes_consumed_[NUM_ENCRYPTION_LEVELS]; std::array<CryptoSubstream, NUM_PACKET_NUMBER_SPACES> substreams_; }; } #endif #include "quiche/quic/core/quic_crypto_stream.h" #include <algorithm> #include <optional> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (session()->perspective() == Perspective::IS_SERVER ? "Server: " \ : "Client:" \ " ") QuicCryptoStream::QuicCryptoStream(QuicSession* session) : QuicStream( QuicVersionUsesCryptoFrames(session->transport_version()) ? QuicUtils::GetInvalidStreamId(session->transport_version()) : QuicUtils::GetCryptoStreamId(session->transport_version()), session, true, QuicVersionUsesCryptoFrames(session->transport_version()) ? CRYPTO : BIDIRECTIONAL), substreams_{{{this}, {this}, {this}}} { DisableConnectionFlowControlForThisStream(); } QuicCryptoStream::~QuicCryptoStream() {} QuicByteCount QuicCryptoStream::CryptoMessageFramingOverhead( QuicTransportVersion version, QuicConnectionId connection_id) { QUICHE_DCHECK( QuicUtils::IsConnectionIdValidForVersion(connection_id, version)); quiche::QuicheVariableLengthIntegerLength retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; quiche::QuicheVariableLengthIntegerLength length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; if (!QuicVersionHasLongHeaderLengths(version)) { retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; } return QuicPacketCreator::StreamFramePacketOverhead( version, connection_id.length(), 0, true, true, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, length_length, 0); } void QuicCryptoStream::OnCryptoFrame(const QuicCryptoFrame& frame) { QUIC_BUG_IF(quic_bug_12573_1, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 shouldn't receive CRYPTO frames"; EncryptionLevel level = session()->connection()->last_decrypted_level(); if (!IsCryptoFrameExpectedForEncryptionLevel(level)) { OnUnrecoverableError( IETF_QUIC_PROTOCOL_VIOLATION, absl::StrCat("CRYPTO_FRAME is unexpectedly received at level ", level)); return; } CryptoSubstream& substream = substreams_[QuicUtils::GetPacketNumberSpace(level)]; substream.sequencer.OnCryptoFrame(frame); EncryptionLevel frame_level = level; if (substream.sequencer.NumBytesBuffered() > BufferSizeLimitForLevel(frame_level)) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Too much crypto data received"); } } void QuicCryptoStream::OnStreamFrame(const QuicStreamFrame& frame) { if (QuicVersionUsesCryptoFrames(session()->transport_version())) { QUIC_PEER_BUG(quic_peer_bug_12573_2) << "Crypto data received in stream frame instead of crypto frame"; OnUnrecoverableError(QUIC_INVALID_STREAM_DATA, "Unexpected stream frame"); } QuicStream::OnStreamFrame(frame); } void QuicCryptoStream::OnDataAvailable() { EncryptionLevel level = session()->connection()->last_decrypted_level(); if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { OnDataAvailableInSequencer(sequencer(), level); return; } OnDataAvailableInSequencer( &substreams_[QuicUtils::GetPacketNumberSpace(level)].sequencer, level); } void QuicCryptoStream::OnDataAvailableInSequencer( QuicStreamSequencer* sequencer, EncryptionLevel level) { struct iovec iov; while (sequencer->GetReadableRegion(&iov)) { absl::string_view data(static_cast<char*>(iov.iov_base), iov.iov_len); if (!crypto_message_parser()->ProcessInput(data, level)) { OnUnrecoverableError(crypto_message_parser()->error(), crypto_message_parser()->error_detail()); return; } sequencer->MarkConsumed(iov.iov_len); if (one_rtt_keys_available() && crypto_message_parser()->InputBytesRemaining() == 0) { sequencer->ReleaseBufferIfEmpty(); } } } void QuicCryptoStream::WriteCryptoData(EncryptionLevel level, absl::string_view data) { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { WriteOrBufferDataAtLevel(data, false, level, nullptr); return; } if (data.empty()) { QUIC_BUG(quic_bug_10322_1) << "Empty crypto data being written"; return; } const bool had_buffered_data = HasBufferedCryptoFrames(); QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(level)].send_buffer; QuicStreamOffset offset = send_buffer->stream_offset(); if (GetQuicFlag(quic_bounded_crypto_send_buffer)) { QUIC_BUG_IF(quic_crypto_stream_offset_lt_bytes_written, offset < send_buffer->stream_bytes_written()); uint64_t current_buffer_size = offset - std::min(offset, send_buffer->stream_bytes_written()); if (current_buffer_size > 0) { QUIC_CODE_COUNT(quic_received_crypto_data_with_non_empty_send_buffer); if (BufferSizeLimitForLevel(level) < (current_buffer_size + data.length())) { QUIC_BUG(quic_crypto_send_buffer_overflow) << absl::StrCat("Too much data for crypto send buffer with level: ", EncryptionLevelToString(level), ", current_buffer_size: ", current_buffer_size, ", data length: ", data.length(), ", SNI: ", crypto_negotiated_params().sni); OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Too much data for crypto send buffer"); return; } } } send_buffer->SaveStreamData(data); if (kMaxStreamLength - offset < data.length()) { QUIC_BUG(quic_bug_10322_2) << "Writing too much crypto handshake data"; OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Writing too much crypto handshake data"); return; } if (had_buffered_data) { return; } size_t bytes_consumed = stream_delegate()->SendCryptoData( level, data.length(), offset, NOT_RETRANSMISSION); send_buffer->OnStreamDataConsumed(bytes_consumed); } size_t QuicCryptoStream::BufferSizeLimitForLevel(EncryptionLevel) const { return GetQuicFlag(quic_max_buffered_crypto_bytes); } bool QuicCryptoStream::OnCryptoFrameAcked(const QuicCryptoFrame& frame, QuicTime::Delta ) { QuicByteCount newly_acked_length = 0; if (!substreams_[QuicUtils::GetPacketNumberSpace(frame.level)] .send_buffer.OnStreamDataAcked(frame.offset, frame.data_length, &newly_acked_length)) { OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Trying to ack unsent crypto data."); return false; } return newly_acked_length > 0; } void QuicCryptoStream::OnStreamReset(const QuicRstStreamFrame& ) { stream_delegate()->OnStreamError(QUIC_INVALID_STREAM_ID, "Attempt to reset crypto stream"); } void QuicCryptoStream::NeuterUnencryptedStreamData() { NeuterStreamDataOfEncryptionLevel(ENCRYPTION_INITIAL); } void QuicCryptoStream::NeuterStreamDataOfEncryptionLevel( EncryptionLevel level) { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { for (const auto& interval : bytes_consumed_[level]) { QuicByteCount newly_acked_length = 0; send_buffer().OnStreamDataAcked( interval.min(), interval.max() - interval.min(), &newly_acked_length); } return; } QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(level)].send_buffer; QuicIntervalSet<QuicStreamOffset> to_ack = send_buffer->bytes_acked(); to_ack.Complement(0, send_buffer->stream_offset()); for (const auto& interval : to_ack) { QuicByteCount newly_acked_length = 0; send_buffer->OnStreamDataAcked( interval.min(), interval.max() - interval.min(), &newly_acked_length); } } void QuicCryptoStream::OnStreamDataConsumed(QuicByteCount bytes_consumed) { if (QuicVersionUsesCryptoFrames(session()->transport_version())) { QUIC_BUG(quic_bug_10322_3) << "Stream data consumed when CRYPTO frames should be in use"; } if (bytes_consumed > 0) { bytes_consumed_[session()->connection()->encryption_level()].Add( stream_bytes_written(), stream_bytes_written() + bytes_consumed); } QuicStream::OnStreamDataConsumed(bytes_consumed); } bool QuicCryptoStream::HasPendingCryptoRetransmission() const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return false; } for (const auto& substream : substreams_) { if (substream.send_buffer.HasPendingRetransmission()) { return true; } } return false; } void QuicCryptoStream::WritePendingCryptoRetransmission() { QUIC_BUG_IF(quic_bug_12573_3, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't write CRYPTO frames"; for (uint8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) { auto packet_number_space = static_cast<PacketNumberSpace>(i); QuicStreamSendBuffer* send_buffer = &substreams_[packet_number_space].send_buffer; while (send_buffer->HasPendingRetransmission()) { auto pending = send_buffer->NextPendingRetransmission(); size_t bytes_consumed = stream_delegate()->SendCryptoData( GetEncryptionLevelToSendCryptoDataOfSpace(packet_number_space), pending.length, pending.offset, HANDSHAKE_RETRANSMISSION); send_buffer->OnStreamDataRetransmitted(pending.offset, bytes_consumed); if (bytes_consumed < pending.length) { return; } } } } void QuicCryptoStream::WritePendingRetransmission() { while (HasPendingRetransmission()) { StreamPendingRetransmission pending = send_buffer().NextPendingRetransmission(); QuicIntervalSet<QuicStreamOffset> retransmission( pending.offset, pending.offset + pending.length); EncryptionLevel retransmission_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(bytes_consumed_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(bytes_consumed_[i]); break; } } pending.offset = retransmission.begin()->min(); pending.length = retransmission.begin()->max() - retransmission.begin()->min(); QuicConsumedData consumed = RetransmitStreamDataAtLevel( pending.offset, pending.length, retransmission_encryption_level, HANDSHAKE_RETRANSMISSION); if (consumed.bytes_consumed < pending.length) { break; } } } bool QuicCryptoStream::RetransmitStreamData(QuicStreamOffset offset, QuicByteCount data_length, bool , TransmissionType type) { QUICHE_DCHECK(type == HANDSHAKE_RETRANSMISSION || type == PTO_RETRANSMISSION); QuicIntervalSet<QuicStreamOffset> retransmission(offset, offset + data_length); EncryptionLevel send_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(bytes_consumed_[i])) { send_encryption_level = static_cast<EncryptionLevel>(i); break; } } retransmission.Difference(bytes_acked()); for (const auto& interval : retransmission) { QuicStreamOffset retransmission_offset = interval.min(); QuicByteCount retransmission_length = interval.max() - interval.min(); QuicConsumedData consumed = RetransmitStreamDataAtLevel( retransmission_offset, retransmission_length, send_encryption_level, type); if (consumed.bytes_consumed < retransmission_length) { return false; } } return true; } QuicConsumedData QuicCryptoStream::RetransmitStreamDataAtLevel( QuicStreamOffset retransmission_offset, QuicByteCount retransmission_length, EncryptionLevel encryption_level, TransmissionType type) { QUICHE_DCHECK(type == HANDSHAKE_RETRANSMISSION || type == PTO_RETRANSMISSION); const auto consumed = stream_delegate()->WritevData( id(), retransmission_length, retransmission_offset, NO_FIN, type, encryption_level); QUIC_DVLOG(1) << ENDPOINT << "stream " << id() << " is forced to retransmit stream data [" << retransmission_offset << ", " << retransmission_offset + retransmission_length << "), with encryption level: " << encryption_level << ", consumed: " << consumed; OnStreamFrameRetransmitted(retransmission_offset, consumed.bytes_consumed, consumed.fin_consumed); return consumed; } uint64_t QuicCryptoStream::crypto_bytes_read() const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return stream_bytes_read(); } uint64_t bytes_read = 0; for (const CryptoSubstream& substream : substreams_) { bytes_read += substream.sequencer.NumBytesConsumed(); } return bytes_read; } uint64_t QuicCryptoStream::BytesReadOnLevel(EncryptionLevel level) const { return substreams_[QuicUtils::GetPacketNumberSpace(level)] .sequencer.NumBytesConsumed(); } uint64_t QuicCryptoStream::BytesSentOnLevel(EncryptionLevel level) const { return substreams_[QuicUtils::GetPacketNumberSpace(level)] .send_buffer.stream_bytes_written(); } bool QuicCryptoStream::WriteCryptoFrame(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { QUIC_BUG_IF(quic_bug_12573_4, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't write CRYPTO frames (2)"; return substreams_[QuicUtils::GetPacketNumberSpace(level)] .send_buffer.WriteStreamData(offset, data_length, writer); } void QuicCryptoStream::OnCryptoFrameLost(QuicCryptoFrame* crypto_frame) { QUIC_BUG_IF(quic_bug_12573_5, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't lose CRYPTO frames"; substreams_[QuicUtils::GetPacketNumberSpace(crypto_frame->level)] .send_buffer.OnStreamDataLost(crypto_frame->offset, crypto_frame->data_length); } bool QuicCryptoStream::RetransmitData(QuicCryptoFrame* crypto_frame, TransmissionType type) { QUIC_BUG_IF(quic_bug_12573_6, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't retransmit CRYPTO frames"; QuicIntervalSet<QuicStreamOffset> retransmission( crypto_frame->offset, crypto_frame->offset + crypto_frame->data_length); QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(crypto_frame->level)] .send_buffer; retransmission.Difference(send_buffer->bytes_acked()); if (retransmission.Empty()) { return true; } for (const auto& interval : retransmission) { size_t retransmission_offset = interval.min(); size_t retransmission_length = interval.max() - interval.min(); EncryptionLevel retransmission_encryption_level = GetEncryptionLevelToSendCryptoDataOfSpace( QuicUtils::GetPacketNumberSpace(crypto_frame->level)); size_t bytes_consumed = stream_delegate()->SendCryptoData( retransmission_encryption_level, retransmission_length, retransmission_offset, type); send_buffer->OnStreamDataRetransmitted(retransmission_offset, bytes_consumed); if (bytes_consumed < retransmission_length) { return false; } } return true; } void QuicCryptoStream::WriteBufferedCryptoFrames() { QUIC_BUG_IF(quic_bug_12573_7, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't use CRYPTO frames"; for (uint8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) { auto packet_number_space = static_cast<PacketNumberSpace>(i); QuicStreamSendBuffer* send_buffer = &substreams_[packet_number_space].send_buffer; const size_t data_length = send_buffer->stream_offset() - send_buffer->stream_bytes_written(); if (data_length == 0) { continue; } size_t bytes_consumed = stream_delegate()->SendCryptoData( GetEncryptionLevelToSendCryptoDataOfSpace(packet_number_space), data_length, send_buffer->stream_bytes_written(), NOT_RETRANSMISSION); send_buffer->OnStreamDataConsumed(bytes_consumed); if (bytes_consumed < data_length) { break; } } } bool QuicCryptoStream::HasBufferedCryptoFrames() const { QUIC_BUG_IF(quic_bug_12573_8, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't use CRYPTO frames"; for (const CryptoSubstream& substream : substreams_) { const QuicStreamSendBuffer& send_buffer = substream.send_buffer; QUICHE_DCHECK_GE(send_buffer.stream_offset(), send_buffer.stream_bytes_written()); if (send_buffer.stream_offset() > send_buffer.stream_bytes_written()) { return true; } } return false; } bool QuicCryptoStream::IsFrameOutstanding(EncryptionLevel level, size_t offset, size_t length) const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) {
#include "quiche/quic/core/quic_crypto_stream.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Return; namespace quic { namespace test { namespace { class MockQuicCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit MockQuicCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), params_(new QuicCryptoNegotiatedParameters) {} MockQuicCryptoStream(const MockQuicCryptoStream&) = delete; MockQuicCryptoStream& operator=(const MockQuicCryptoStream&) = delete; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } std::vector<CryptoHandshakeMessage>* messages() { return &messages_; } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return false; } bool one_rtt_keys_available() const override { return false; } const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override { return *params_; } CryptoMessageParser* crypto_message_parser() override { return QuicCryptoHandshaker::crypto_message_parser(); } void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view ) override {} std::string GetAddressToken( const CachedNetworkParameters* ) const override { return ""; } bool ValidateAddressToken(absl::string_view ) const override { return true; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters ) override {} HandshakeState GetHandshakeState() const override { return HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { return false; } SSL* GetSsl() const override { return nullptr; } bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return QuicCryptoStream::session() ->GetEncryptionLevelToSendApplicationData(); default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } private: quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; std::vector<CryptoHandshakeMessage> messages_; }; class QuicCryptoStreamTest : public QuicTest { public: QuicCryptoStreamTest() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT)), session_(connection_, false) { EXPECT_CALL(*static_cast<MockPacketWriter*>(connection_->writer()), WritePacket(_, _, _, _, _, _)) .WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0))); stream_ = new MockQuicCryptoStream(&session_); session_.SetCryptoStream(stream_); session_.Initialize(); message_.set_tag(kSHLO); message_.SetStringPiece(1, "abc"); message_.SetStringPiece(2, "def"); ConstructHandshakeMessage(); } QuicCryptoStreamTest(const QuicCryptoStreamTest&) = delete; QuicCryptoStreamTest& operator=(const QuicCryptoStreamTest&) = delete; void ConstructHandshakeMessage() { CryptoFramer framer; message_data_ = framer.ConstructHandshakeMessage(message_); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; MockQuicSpdySession session_; MockQuicCryptoStream* stream_; CryptoHandshakeMessage message_; std::unique_ptr<QuicData> message_data_; }; TEST_F(QuicCryptoStreamTest, NotInitiallyConected) { EXPECT_FALSE(stream_->encryption_established()); EXPECT_FALSE(stream_->one_rtt_keys_available()); } TEST_F(QuicCryptoStreamTest, ProcessRawData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, 0, message_data_->AsStringPiece())); } else { stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_INITIAL, 0, message_data_->AsStringPiece())); } ASSERT_EQ(1u, stream_->messages()->size()); const CryptoHandshakeMessage& message = (*stream_->messages())[0]; EXPECT_EQ(kSHLO, message.tag()); EXPECT_EQ(2u, message.tag_value_map().size()); EXPECT_EQ("abc", crypto_test_utils::GetValueForTag(message, 1)); EXPECT_EQ("def", crypto_test_utils::GetValueForTag(message, 2)); } TEST_F(QuicCryptoStreamTest, ProcessBadData) { std::string bad(message_data_->data(), message_data_->length()); const int kFirstTagIndex = sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t); EXPECT_EQ(1, bad[kFirstTagIndex]); bad[kFirstTagIndex] = 0x7F; EXPECT_CALL(*connection_, CloseConnection(QUIC_CRYPTO_TAGS_OUT_OF_ORDER, testing::_, testing::_)); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, 0, bad)); } else { stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, 0, bad)); } } TEST_F(QuicCryptoStreamTest, NoConnectionLevelFlowControl) { EXPECT_FALSE( QuicStreamPeer::StreamContributesToConnectionFlowControl(stream_)); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); stream_->OnStreamFrameLost(0, 1000, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(1200, 800, false); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1000, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1200, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasPendingRetransmission()); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoDataInCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); QuicCryptoFrame lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 0, 1000); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 1200, 150); stream_->OnCryptoFrameLost(&lost_frame); lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 150, 1200)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } TEST_F(QuicCryptoStreamTest, RetransmitEncryptionHandshakeLevelCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1000, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_HANDSHAKE, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_EQ(ENCRYPTION_HANDSHAKE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_HANDSHAKE, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicCryptoFrame lost_frame(ENCRYPTION_HANDSHAKE, 0, 200); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 200, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); stream_->OnStreamFrameLost(0, 1350, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(0, 1350, false); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(1350, 650, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1350); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, RetransmitStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicByteCount newly_acked_length = 0; stream_->OnStreamFrameAcked(2000, 500, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length); EXPECT_EQ(500u, newly_acked_length); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_.ConsumeData( QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1350, NO_FIN, HANDSHAKE_RETRANSMISSION, std::nullopt); })); EXPECT_FALSE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 200, 2500, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0); EXPECT_TRUE( stream_->RetransmitStreamData(0, 0, false, HANDSHAKE_RETRANSMISSION)); } TEST_F(QuicCryptoStreamTest, RetransmitStreamDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicCryptoFrame acked_frame(ENCRYPTION_ZERO_RTT, 650, 500); EXPECT_TRUE( stream_->OnCryptoFrameAcked(acked_frame, QuicTime::Delta::Zero())); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 150, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); QuicCryptoFrame frame_to_retransmit(ENCRYPTION_ZERO_RTT, 0, 150); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 200, 1150)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); frame_to_retransmit = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 1350); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); QuicCryptoFrame empty_frame(ENCRYPTION_FORWARD_SECURE, 0, 0); stream_->RetransmitData(&empty_frame, HANDSHAKE_RETRANSMISSION); } TEST_F(QuicCryptoStreamTest, HasUnackedCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(testing::Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } TEST_F(QuicCryptoStreamTest, HasUnackedCryptoDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } TEST_F(QuicCryptoStreamTest, CryptoMessageFramingOverhead) { for (const ParsedQuicVersion& version : AllSupportedVersionsWithQuicCrypto()) { SCOPED_TRACE(version); QuicByteCount expected_overhead = 52; if (version.HasLongHeaderLengths()) { expected_overhead += 3; } if (version.HasLengthPrefixedConnectionIds()) { expected_overhead += 1; } EXPECT_EQ(expected_overhead, QuicCryptoStream::CryptoMessageFramingOverhead( version.transport_version, TestConnectionId())); } } TEST_F(QuicCryptoStreamTest, WriteCryptoDataExceedsSendBufferLimit) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); int32_t buffer_limit = GetQuicFlag(quic_max_buffered_crypto_bytes); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); int32_t over_limit = buffer_limit + 1; EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, over_limit, 0)) .WillOnce(Return(over_limit)); std::string large_data(over_limit, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, large_data); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, buffer_limit, over_limit)) .WillOnce(Return(1)); std::string data(buffer_limit, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); std::string data2(1, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); if (GetQuicFlag(quic_bounded_crypto_send_buffer)) { EXPECT_CALL(*connection_, CloseConnection(QUIC_INTERNAL_ERROR, _, _)); EXPECT_QUIC_BUG( stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2), "Too much data for crypto send buffer with level: ENCRYPTION_INITIAL, " "current_buffer_size: 16384, data length: 1"); } } TEST_F(QuicCryptoStreamTest, WriteBufferedCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000)) .WillOnce(Return(350)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteBufferedCryptoFrames(); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 350, 1000)) .WillOnce(Return(350)); stream_->WriteBufferedCryptoFrames(); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); } TEST_F(QuicCryptoStreamTest, LimitBufferedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); std::string large_frame(2 * GetQuicFlag(quic_max_buffered_crypto_bytes), 'a'); QuicStreamOffset offset = 1; stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, offset, large_frame)); } TEST_F(QuicCryptoStreamTest, CloseConnectionWithZeroRttCryptoFrame) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, _, _)); test::QuicConnectionPeer::SetLastDecryptedLevel(connection_, ENCRYPTION_ZERO_RTT); QuicStreamOffset offset = 1; stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_ZERO_RTT, offset, "data")); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoFramesAndPartialWrite) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
244
cpp
google/quiche
quic_versions
quiche/quic/core/quic_versions.cc
quiche/quic/core/quic_versions_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_VERSIONS_H_ #define QUICHE_QUIC_CORE_QUIC_VERSIONS_H_ #include <cstdint> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { enum QuicTransportVersion { QUIC_VERSION_UNSUPPORTED = 0, QUIC_VERSION_46 = 46, QUIC_VERSION_IETF_DRAFT_29 = 73, QUIC_VERSION_IETF_RFC_V1 = 80, QUIC_VERSION_IETF_RFC_V2 = 82, QUIC_VERSION_RESERVED_FOR_NEGOTIATION = 999, }; QUICHE_EXPORT std::string QuicVersionToString( QuicTransportVersion transport_version); enum HandshakeProtocol { PROTOCOL_UNSUPPORTED, PROTOCOL_QUIC_CRYPTO, PROTOCOL_TLS1_3, }; QUICHE_EXPORT std::string HandshakeProtocolToString( HandshakeProtocol handshake_protocol); QUICHE_EXPORT constexpr bool QuicVersionUsesCryptoFrames( QuicTransportVersion transport_version) { return transport_version > QUIC_VERSION_46; } QUICHE_EXPORT constexpr bool ParsedQuicVersionIsValid( HandshakeProtocol handshake_protocol, QuicTransportVersion transport_version) { bool transport_version_is_valid = false; constexpr QuicTransportVersion valid_transport_versions[] = { QUIC_VERSION_IETF_RFC_V2, QUIC_VERSION_IETF_RFC_V1, QUIC_VERSION_IETF_DRAFT_29, QUIC_VERSION_46, QUIC_VERSION_RESERVED_FOR_NEGOTIATION, QUIC_VERSION_UNSUPPORTED, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(valid_transport_versions); ++i) { if (transport_version == valid_transport_versions[i]) { transport_version_is_valid = true; break; } } if (!transport_version_is_valid) { return false; } switch (handshake_protocol) { case PROTOCOL_UNSUPPORTED: return transport_version == QUIC_VERSION_UNSUPPORTED; case PROTOCOL_QUIC_CRYPTO: return transport_version != QUIC_VERSION_UNSUPPORTED && transport_version != QUIC_VERSION_RESERVED_FOR_NEGOTIATION && transport_version != QUIC_VERSION_IETF_DRAFT_29 && transport_version != QUIC_VERSION_IETF_RFC_V1 && transport_version != QUIC_VERSION_IETF_RFC_V2; case PROTOCOL_TLS1_3: return transport_version != QUIC_VERSION_UNSUPPORTED && QuicVersionUsesCryptoFrames(transport_version); } return false; } struct QUICHE_EXPORT ParsedQuicVersion { HandshakeProtocol handshake_protocol; QuicTransportVersion transport_version; constexpr ParsedQuicVersion(HandshakeProtocol handshake_protocol, QuicTransportVersion transport_version) : handshake_protocol(handshake_protocol), transport_version(transport_version) { QUICHE_DCHECK( ParsedQuicVersionIsValid(handshake_protocol, transport_version)) << QuicVersionToString(transport_version) << " " << HandshakeProtocolToString(handshake_protocol); } constexpr ParsedQuicVersion(const ParsedQuicVersion& other) : ParsedQuicVersion(other.handshake_protocol, other.transport_version) {} ParsedQuicVersion& operator=(const ParsedQuicVersion& other) { QUICHE_DCHECK(ParsedQuicVersionIsValid(other.handshake_protocol, other.transport_version)) << QuicVersionToString(other.transport_version) << " " << HandshakeProtocolToString(other.handshake_protocol); if (this != &other) { handshake_protocol = other.handshake_protocol; transport_version = other.transport_version; } return *this; } bool operator==(const ParsedQuicVersion& other) const { return handshake_protocol == other.handshake_protocol && transport_version == other.transport_version; } bool operator!=(const ParsedQuicVersion& other) const { return handshake_protocol != other.handshake_protocol || transport_version != other.transport_version; } static constexpr ParsedQuicVersion RFCv2() { return ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_RFC_V2); } static constexpr ParsedQuicVersion RFCv1() { return ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_RFC_V1); } static constexpr ParsedQuicVersion Draft29() { return ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_IETF_DRAFT_29); } static constexpr ParsedQuicVersion Q046() { return ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_46); } static constexpr ParsedQuicVersion Unsupported() { return ParsedQuicVersion(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED); } static constexpr ParsedQuicVersion ReservedForNegotiation() { return ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_RESERVED_FOR_NEGOTIATION); } bool IsKnown() const; bool KnowsWhichDecrypterToUse() const; bool UsesInitialObfuscators() const; bool AllowsLowFlowControlLimits() const; bool HasHeaderProtection() const; bool SupportsRetry() const; bool SendsVariableLengthPacketNumberInLongHeader() const; bool AllowsVariableLengthConnectionIds() const; bool SupportsClientConnectionIds() const; bool HasLengthPrefixedConnectionIds() const; bool SupportsAntiAmplificationLimit() const; bool CanSendCoalescedPackets() const; bool SupportsGoogleAltSvcFormat() const; bool UsesHttp3() const; bool HasLongHeaderLengths() const; bool UsesCryptoFrames() const; bool HasIetfQuicFrames() const; bool UsesLegacyTlsExtension() const; bool UsesTls() const; bool UsesQuicCrypto() const; bool UsesV2PacketTypes() const; bool AlpnDeferToRFCv1() const; }; QUICHE_EXPORT ParsedQuicVersion UnsupportedQuicVersion(); QUICHE_EXPORT ParsedQuicVersion QuicVersionReservedForNegotiation(); QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const ParsedQuicVersion& version); using ParsedQuicVersionVector = std::vector<ParsedQuicVersion>; QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const ParsedQuicVersionVector& versions); using QuicVersionLabel = uint32_t; using QuicVersionLabelVector = std::vector<QuicVersionLabel>; QUICHE_EXPORT QuicVersionLabel MakeVersionLabel(uint8_t a, uint8_t b, uint8_t c, uint8_t d); QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const QuicVersionLabelVector& version_labels); constexpr std::array<HandshakeProtocol, 2> SupportedHandshakeProtocols() { return {PROTOCOL_TLS1_3, PROTOCOL_QUIC_CRYPTO}; } constexpr std::array<ParsedQuicVersion, 4> SupportedVersions() { return { ParsedQuicVersion::RFCv2(), ParsedQuicVersion::RFCv1(), ParsedQuicVersion::Draft29(), ParsedQuicVersion::Q046(), }; } using QuicTransportVersionVector = std::vector<QuicTransportVersion>; QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const QuicTransportVersionVector& transport_versions); QUICHE_EXPORT ParsedQuicVersionVector AllSupportedVersions(); QUICHE_EXPORT ParsedQuicVersionVector CurrentSupportedVersions(); QUICHE_EXPORT ParsedQuicVersionVector ObsoleteSupportedVersions(); QUICHE_EXPORT bool IsObsoleteSupportedVersion(ParsedQuicVersion version); QUICHE_EXPORT ParsedQuicVersionVector CurrentSupportedVersionsForClients(); QUICHE_EXPORT ParsedQuicVersionVector FilterSupportedVersions(ParsedQuicVersionVector versions); QUICHE_EXPORT ParsedQuicVersionVector AllSupportedVersionsWithQuicCrypto(); QUICHE_EXPORT ParsedQuicVersionVector CurrentSupportedVersionsWithQuicCrypto(); QUICHE_EXPORT ParsedQuicVersionVector AllSupportedVersionsWithTls(); QUICHE_EXPORT ParsedQuicVersionVector CurrentSupportedVersionsWithTls(); QUICHE_EXPORT ParsedQuicVersionVector CurrentSupportedHttp3Versions(); QUICHE_EXPORT ParsedQuicVersionVector ParsedVersionOfIndex(const ParsedQuicVersionVector& versions, int index); QUICHE_EXPORT ParsedQuicVersion ParseQuicVersionLabel(QuicVersionLabel version_label); QUICHE_EXPORT ParsedQuicVersionVector ParseQuicVersionLabelVector(const QuicVersionLabelVector& version_labels); QUICHE_EXPORT ParsedQuicVersion ParseQuicVersionString(absl::string_view version_string); QUICHE_EXPORT ParsedQuicVersionVector ParseQuicVersionVectorString(absl::string_view versions_string); QUICHE_EXPORT QuicVersionLabel CreateQuicVersionLabel(ParsedQuicVersion parsed_version); QUICHE_EXPORT QuicVersionLabelVector CreateQuicVersionLabelVector(const ParsedQuicVersionVector& versions); QUICHE_EXPORT std::string QuicVersionLabelToString( QuicVersionLabel version_label); QUICHE_EXPORT ParsedQuicVersion ParseQuicVersionLabelString(absl::string_view version_label_string); QUICHE_EXPORT std::string QuicVersionLabelVectorToString( const QuicVersionLabelVector& version_labels, const std::string& separator, size_t skip_after_nth_version); QUICHE_EXPORT inline std::string QuicVersionLabelVectorToString( const QuicVersionLabelVector& version_labels) { return QuicVersionLabelVectorToString(version_labels, ",", std::numeric_limits<size_t>::max()); } QUICHE_EXPORT std::string ParsedQuicVersionToString(ParsedQuicVersion version); QUICHE_EXPORT QuicTransportVersionVector AllSupportedTransportVersions(); QUICHE_EXPORT std::string QuicTransportVersionVectorToString( const QuicTransportVersionVector& versions); QUICHE_EXPORT std::string ParsedQuicVersionVectorToString( const ParsedQuicVersionVector& versions); QUICHE_EXPORT std::string ParsedQuicVersionVectorToString( const ParsedQuicVersionVector& versions, const std::string& separator, size_t skip_after_nth_version); QUICHE_EXPORT inline std::string ParsedQuicVersionVectorToString( const ParsedQuicVersionVector& versions) { return ParsedQuicVersionVectorToString(versions, ",", std::numeric_limits<size_t>::max()); } QUICHE_EXPORT constexpr bool VersionUsesHttp3( QuicTransportVersion transport_version) { return transport_version >= QUIC_VERSION_IETF_DRAFT_29; } QUICHE_EXPORT constexpr bool QuicVersionHasLongHeaderLengths( QuicTransportVersion transport_version) { return transport_version > QUIC_VERSION_46; } QUICHE_EXPORT constexpr bool VersionHasIetfQuicFrames( QuicTransportVersion transport_version) { return VersionUsesHttp3(transport_version); } QUICHE_EXPORT bool VersionHasLengthPrefixedConnectionIds( QuicTransportVersion transport_version); QUICHE_EXPORT bool VersionSupportsGoogleAltSvcFormat( QuicTransportVersion transport_version); QUICHE_EXPORT bool VersionAllowsVariableLengthConnectionIds( QuicTransportVersion transport_version); QUICHE_EXPORT bool QuicVersionLabelUses4BitConnectionIdLength( QuicVersionLabel version_label); QUICHE_EXPORT std::string AlpnForVersion(ParsedQuicVersion parsed_version); QUICHE_EXPORT void QuicEnableVersion(const ParsedQuicVersion& version); QUICHE_EXPORT void QuicDisableVersion(const ParsedQuicVersion& version); QUICHE_EXPORT bool QuicVersionIsEnabled(const ParsedQuicVersion& version); } #endif #include "quiche/quic/core/quic_versions.h" #include <algorithm> #include <ostream> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { QuicVersionLabel CreateRandomVersionLabelForNegotiation() { QuicVersionLabel result; if (!GetQuicFlag(quic_disable_version_negotiation_grease_randomness)) { QuicRandom::GetInstance()->RandBytes(&result, sizeof(result)); } else { result = MakeVersionLabel(0xd1, 0x57, 0x38, 0x3f); } result &= 0xf0f0f0f0; result |= 0x0a0a0a0a; return result; } void SetVersionFlag(const ParsedQuicVersion& version, bool should_enable) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); const bool enable = should_enable; const bool disable = !should_enable; if (version == ParsedQuicVersion::RFCv2()) { SetQuicReloadableFlag(quic_enable_version_rfcv2, enable); } else if (version == ParsedQuicVersion::RFCv1()) { SetQuicReloadableFlag(quic_disable_version_rfcv1, disable); } else if (version == ParsedQuicVersion::Draft29()) { SetQuicReloadableFlag(quic_disable_version_draft_29, disable); } else if (version == ParsedQuicVersion::Q046()) { SetQuicReloadableFlag(quic_disable_version_q046, disable); } else { QUIC_BUG(quic_bug_10589_1) << "Cannot " << (enable ? "en" : "dis") << "able version " << version; } } } bool ParsedQuicVersion::IsKnown() const { QUICHE_DCHECK(ParsedQuicVersionIsValid(handshake_protocol, transport_version)) << QuicVersionToString(transport_version) << " " << HandshakeProtocolToString(handshake_protocol); return transport_version != QUIC_VERSION_UNSUPPORTED; } bool ParsedQuicVersion::KnowsWhichDecrypterToUse() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::UsesInitialObfuscators() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::AllowsLowFlowControlLimits() const { QUICHE_DCHECK(IsKnown()); return UsesHttp3(); } bool ParsedQuicVersion::HasHeaderProtection() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::SupportsRetry() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::SendsVariableLengthPacketNumberInLongHeader() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::AllowsVariableLengthConnectionIds() const { QUICHE_DCHECK(IsKnown()); return VersionAllowsVariableLengthConnectionIds(transport_version); } bool ParsedQuicVersion::SupportsClientConnectionIds() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::HasLengthPrefixedConnectionIds() const { QUICHE_DCHECK(IsKnown()); return VersionHasLengthPrefixedConnectionIds(transport_version); } bool ParsedQuicVersion::SupportsAntiAmplificationLimit() const { QUICHE_DCHECK(IsKnown()); return UsesHttp3(); } bool ParsedQuicVersion::CanSendCoalescedPackets() const { QUICHE_DCHECK(IsKnown()); return HasLongHeaderLengths() && UsesTls(); } bool ParsedQuicVersion::SupportsGoogleAltSvcFormat() const { QUICHE_DCHECK(IsKnown()); return VersionSupportsGoogleAltSvcFormat(transport_version); } bool ParsedQuicVersion::UsesHttp3() const { QUICHE_DCHECK(IsKnown()); return VersionUsesHttp3(transport_version); } bool ParsedQuicVersion::HasLongHeaderLengths() const { QUICHE_DCHECK(IsKnown()); return QuicVersionHasLongHeaderLengths(transport_version); } bool ParsedQuicVersion::UsesCryptoFrames() const { QUICHE_DCHECK(IsKnown()); return QuicVersionUsesCryptoFrames(transport_version); } bool ParsedQuicVersion::HasIetfQuicFrames() const { QUICHE_DCHECK(IsKnown()); return VersionHasIetfQuicFrames(transport_version); } bool ParsedQuicVersion::UsesLegacyTlsExtension() const { QUICHE_DCHECK(IsKnown()); return UsesTls() && transport_version <= QUIC_VERSION_IETF_DRAFT_29; } bool ParsedQuicVersion::UsesTls() const { QUICHE_DCHECK(IsKnown()); return handshake_protocol == PROTOCOL_TLS1_3; } bool ParsedQuicVersion::UsesQuicCrypto() const { QUICHE_DCHECK(IsKnown()); return handshake_protocol == PROTOCOL_QUIC_CRYPTO; } bool ParsedQuicVersion::UsesV2PacketTypes() const { QUICHE_DCHECK(IsKnown()); return transport_versi
#include "quiche/quic/core/quic_versions.h" #include <cstddef> #include <sstream> #include "absl/algorithm/container.h" #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; TEST(QuicVersionsTest, CreateQuicVersionLabelUnsupported) { EXPECT_QUIC_BUG( CreateQuicVersionLabel(UnsupportedQuicVersion()), "Unsupported version QUIC_VERSION_UNSUPPORTED PROTOCOL_UNSUPPORTED"); } TEST(QuicVersionsTest, KnownAndValid) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_TRUE(version.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(version.handshake_protocol, version.transport_version)); } ParsedQuicVersion unsupported = UnsupportedQuicVersion(); EXPECT_FALSE(unsupported.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(unsupported.handshake_protocol, unsupported.transport_version)); ParsedQuicVersion reserved = QuicVersionReservedForNegotiation(); EXPECT_TRUE(reserved.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(reserved.handshake_protocol, reserved.transport_version)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_TLS1_3, QUIC_VERSION_46)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_IETF_DRAFT_29)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, static_cast<QuicTransportVersion>(33))); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, static_cast<QuicTransportVersion>(99))); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_TLS1_3, static_cast<QuicTransportVersion>(99))); } TEST(QuicVersionsTest, Features) { ParsedQuicVersion parsed_version_q046 = ParsedQuicVersion::Q046(); ParsedQuicVersion parsed_version_draft_29 = ParsedQuicVersion::Draft29(); EXPECT_TRUE(parsed_version_q046.IsKnown()); EXPECT_FALSE(parsed_version_q046.KnowsWhichDecrypterToUse()); EXPECT_FALSE(parsed_version_q046.UsesInitialObfuscators()); EXPECT_FALSE(parsed_version_q046.AllowsLowFlowControlLimits()); EXPECT_FALSE(parsed_version_q046.HasHeaderProtection()); EXPECT_FALSE(parsed_version_q046.SupportsRetry()); EXPECT_FALSE( parsed_version_q046.SendsVariableLengthPacketNumberInLongHeader()); EXPECT_FALSE(parsed_version_q046.AllowsVariableLengthConnectionIds()); EXPECT_FALSE(parsed_version_q046.SupportsClientConnectionIds()); EXPECT_FALSE(parsed_version_q046.HasLengthPrefixedConnectionIds()); EXPECT_FALSE(parsed_version_q046.SupportsAntiAmplificationLimit()); EXPECT_FALSE(parsed_version_q046.CanSendCoalescedPackets()); EXPECT_TRUE(parsed_version_q046.SupportsGoogleAltSvcFormat()); EXPECT_FALSE(parsed_version_q046.UsesHttp3()); EXPECT_FALSE(parsed_version_q046.HasLongHeaderLengths()); EXPECT_FALSE(parsed_version_q046.UsesCryptoFrames()); EXPECT_FALSE(parsed_version_q046.HasIetfQuicFrames()); EXPECT_FALSE(parsed_version_q046.UsesTls()); EXPECT_TRUE(parsed_version_q046.UsesQuicCrypto()); EXPECT_TRUE(parsed_version_draft_29.IsKnown()); EXPECT_TRUE(parsed_version_draft_29.KnowsWhichDecrypterToUse()); EXPECT_TRUE(parsed_version_draft_29.UsesInitialObfuscators()); EXPECT_TRUE(parsed_version_draft_29.AllowsLowFlowControlLimits()); EXPECT_TRUE(parsed_version_draft_29.HasHeaderProtection()); EXPECT_TRUE(parsed_version_draft_29.SupportsRetry()); EXPECT_TRUE( parsed_version_draft_29.SendsVariableLengthPacketNumberInLongHeader()); EXPECT_TRUE(parsed_version_draft_29.AllowsVariableLengthConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.SupportsClientConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.HasLengthPrefixedConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.SupportsAntiAmplificationLimit()); EXPECT_TRUE(parsed_version_draft_29.CanSendCoalescedPackets()); EXPECT_FALSE(parsed_version_draft_29.SupportsGoogleAltSvcFormat()); EXPECT_TRUE(parsed_version_draft_29.UsesHttp3()); EXPECT_TRUE(parsed_version_draft_29.HasLongHeaderLengths()); EXPECT_TRUE(parsed_version_draft_29.UsesCryptoFrames()); EXPECT_TRUE(parsed_version_draft_29.HasIetfQuicFrames()); EXPECT_TRUE(parsed_version_draft_29.UsesTls()); EXPECT_FALSE(parsed_version_draft_29.UsesQuicCrypto()); } TEST(QuicVersionsTest, ParseQuicVersionLabel) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionLabel(MakeVersionLabel('Q', '0', '4', '6'))); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionLabel(MakeVersionLabel(0xff, 0x00, 0x00, 0x1d))); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionLabel(MakeVersionLabel(0x00, 0x00, 0x00, 0x01))); EXPECT_EQ(ParsedQuicVersion::RFCv2(), ParseQuicVersionLabel(MakeVersionLabel(0x6b, 0x33, 0x43, 0xcf))); EXPECT_EQ((ParsedQuicVersionVector{ParsedQuicVersion::RFCv2(), ParsedQuicVersion::RFCv1(), ParsedQuicVersion::Draft29()}), ParseQuicVersionLabelVector(QuicVersionLabelVector{ MakeVersionLabel(0x6b, 0x33, 0x43, 0xcf), MakeVersionLabel(0x00, 0x00, 0x00, 0x01), MakeVersionLabel(0xaa, 0xaa, 0xaa, 0xaa), MakeVersionLabel(0xff, 0x00, 0x00, 0x1d)})); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionLabel(CreateQuicVersionLabel(version))); } } TEST(QuicVersionsTest, ParseQuicVersionString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("QUIC_VERSION_46")); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("46")); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("Q046")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("Q 46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("Q046 ")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("99")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("70")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("ff00001d")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("draft29")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("h3-29")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionString("00000001")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionString("h3")); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionString(ParsedQuicVersionToString(version))); EXPECT_EQ(version, ParseQuicVersionString(QuicVersionLabelToString( CreateQuicVersionLabel(version)))); if (!version.AlpnDeferToRFCv1()) { EXPECT_EQ(version, ParseQuicVersionString(AlpnForVersion(version))); } } } TEST(QuicVersionsTest, ParseQuicVersionVectorString) { ParsedQuicVersion version_q046 = ParsedQuicVersion::Q046(); ParsedQuicVersion version_draft_29 = ParsedQuicVersion::Draft29(); EXPECT_THAT(ParseQuicVersionVectorString(""), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,h3-Q046,h3-29"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29, h3-Q046"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46,h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29, QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46,h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString( "QUIC_VERSION_46, h3-Q046, QUIC_VERSION_46, h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, h3-29, h3-Q046"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("99"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("70"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("h3-01"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("h3-01,h3-29"), ElementsAre(version_draft_29)); } TEST(QuicVersionsTest, CreateQuicVersionLabel) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(0x51303436u, CreateQuicVersionLabel(ParsedQuicVersion::Q046())); EXPECT_EQ(0xff00001du, CreateQuicVersionLabel(ParsedQuicVersion::Draft29())); EXPECT_EQ(0x00000001u, CreateQuicVersionLabel(ParsedQuicVersion::RFCv1())); EXPECT_EQ(0x6b3343cfu, CreateQuicVersionLabel(ParsedQuicVersion::RFCv2())); EXPECT_EQ( 0xda5a3a3au & 0x0f0f0f0f, CreateQuicVersionLabel(ParsedQuicVersion::ReservedForNegotiation()) & 0x0f0f0f0f); SetQuicFlag(quic_disable_version_negotiation_grease_randomness, true); EXPECT_EQ(0xda5a3a3au, CreateQuicVersionLabel( ParsedQuicVersion::ReservedForNegotiation())); } TEST(QuicVersionsTest, QuicVersionLabelToString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ("Q046", QuicVersionLabelToString( CreateQuicVersionLabel(ParsedQuicVersion::Q046()))); EXPECT_EQ("ff00001d", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::Draft29()))); EXPECT_EQ("00000001", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::RFCv1()))); EXPECT_EQ("6b3343cf", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::RFCv2()))); QuicVersionLabelVector version_labels = { MakeVersionLabel('Q', '0', '3', '5'), MakeVersionLabel('T', '0', '3', '8'), MakeVersionLabel(0xff, 0, 0, 7), }; EXPECT_EQ("Q035", QuicVersionLabelToString(version_labels[0])); EXPECT_EQ("T038", QuicVersionLabelToString(version_labels[1])); EXPECT_EQ("ff000007", QuicVersionLabelToString(version_labels[2])); EXPECT_EQ("Q035,T038,ff000007", QuicVersionLabelVectorToString(version_labels)); EXPECT_EQ("Q035:T038:ff000007", QuicVersionLabelVectorToString(version_labels, ":", 2)); EXPECT_EQ("Q035|T038|...", QuicVersionLabelVectorToString(version_labels, "|", 1)); std::ostringstream os; os << version_labels; EXPECT_EQ("Q035,T038,ff000007", os.str()); } TEST(QuicVersionsTest, ParseQuicVersionLabelString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionLabelString("Q046")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionLabelString("ff00001d")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionLabelString("00000001")); EXPECT_EQ(ParsedQuicVersion::RFCv2(), ParseQuicVersionLabelString("6b3343cf")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("1")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("QUIC_VERSION_46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("h3")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("h3-29")); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionLabelString(QuicVersionLabelToString( CreateQuicVersionLabel(version)))); } } TEST(QuicVersionsTest, QuicVersionToString) { EXPECT_EQ("QUIC_VERSION_UNSUPPORTED", QuicVersionToString(QUIC_VERSION_UNSUPPORTED)); QuicTransportVersion single_version[] = {QUIC_VERSION_46}; QuicTransportVersionVector versions_vector; for (size_t i = 0; i < ABSL_ARRAYSIZE(single_version); ++i) { versions_vector.push_back(single_version[i]); } EXPECT_EQ("QUIC_VERSION_46", QuicTransportVersionVectorToString(versions_vector)); QuicTransportVersion multiple_versions[] = {QUIC_VERSION_UNSUPPORTED, QUIC_VERSION_46}; versions_vector.clear(); for (size_t i = 0; i < ABSL_ARRAYSIZE(multiple_versions); ++i) { versions_vector.push_back(multiple_versions[i]); } EXPECT_EQ("QUIC_VERSION_UNSUPPORTED,QUIC_VERSION_46", QuicTransportVersionVectorToString(versions_vector)); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE("QUIC_VERSION_UNSUPPORTED", QuicVersionToString(version.transport_version)); } std::ostringstream os; os << versions_vector; EXPECT_EQ("QUIC_VERSION_UNSUPPORTED,QUIC_VERSION_46", os.str()); } TEST(QuicVersionsTest, ParsedQuicVersionToString) { EXPECT_EQ("0", ParsedQuicVersionToString(ParsedQuicVersion::Unsupported())); EXPECT_EQ("Q046", ParsedQuicVersionToString(ParsedQuicVersion::Q046())); EXPECT_EQ("draft29", ParsedQuicVersionToString(ParsedQuicVersion::Draft29())); EXPECT_EQ("RFCv1", ParsedQuicVersionToString(ParsedQuicVersion::RFCv1())); EXPECT_EQ("RFCv2", ParsedQuicVersionToString(ParsedQuicVersion::RFCv2())); ParsedQuicVersionVector versions_vector = {ParsedQuicVersion::Q046()}; EXPECT_EQ("Q046", ParsedQuicVersionVectorToString(versions_vector)); versions_vector = {ParsedQuicVersion::Unsupported(), ParsedQuicVersion::Q046()}; EXPECT_EQ("0,Q046", ParsedQuicVersionVectorToString(versions_vector)); EXPECT_EQ("0:Q046", ParsedQuicVersionVectorToString(versions_vector, ":", versions_vector.size())); EXPECT_EQ("0|...", ParsedQuicVersionVectorToString(versions_vector, "|", 0)); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE("0", ParsedQuicVersionToString(version)); } std::ostringstream os; os << versions_vector; EXPECT_EQ("0,Q046", os.str()); } TEST(QuicVersionsTest, FilterSupportedVersionsAllVersions) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } ParsedQuicVersionVector expected_parsed_versions; for (const ParsedQuicVersion& version : SupportedVersions()) { expected_parsed_versions.push_back(version); } EXPECT_EQ(expected_parsed_versions, FilterSupportedVersions(AllSupportedVersions())); EXPECT_EQ(expected_parsed_versions, AllSupportedVersions()); } TEST(QuicVersionsTest, FilterSupportedVersionsWithoutFirstVersion) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } QuicDisableVersion(AllSupportedVersions().front()); ParsedQuicVersionVector expected_parsed_versions; for (const ParsedQuicVersion& version : SupportedVersions()) { expected_parsed_versions.push_back(version); } expected_parsed_versions.erase(expected_parsed_versions.begin()); EXPECT_EQ(expected_parsed_versions, FilterSupportedVersions(AllSupportedVersions())); } TEST(QuicVersionsTest, LookUpParsedVersionByIndex) { ParsedQuicVersionVector all_versions = AllSupportedVersions(); int version_count = all_versions.size(); for (int i = -5; i <= version_count + 1; ++i) { ParsedQuicVersionVector index = ParsedVersionOfIndex(all_versions, i); if (i >= 0 && i < version_count) { EXPECT_EQ(all_versions[i], index[0]); } else { EXPECT_EQ(UnsupportedQuicVersion(), index[0]); } } } TEST(QuicVersionsTest, CheckTransportVersionNumbersForTypos) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(QUIC_VERSION_46, 46); EXPECT_EQ(QUIC_VERSION_IETF_DRAFT_29, 73); EXPECT_EQ(QUIC_VERSION_IETF_RFC_V1, 80); EXPECT_EQ(QUIC_VERSION_IETF_RFC_V2, 82); } TEST(QuicVersionsTest, AlpnForVersion) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ("h3-Q046", AlpnForVersion(ParsedQuicVersion::Q046())); EXPECT_EQ("h3-29", AlpnForVersion(ParsedQuicVersion::Draft29())); EXPECT_EQ("h3", AlpnForVersion(ParsedQuicVersion::RFCv1())); EXPECT_EQ("h3", AlpnForVersion(ParsedQuicVersion::RFCv2())); } TEST(QuicVersionsTest, QuicVersionEnabling) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicFlagSaver flag_saver; QuicDisableVersion(version); EXPECT_FALSE(QuicVersionIsEnabled(version)); QuicEnableVersion(version); EXPECT_TRUE(QuicVersionIsEnabled(version)); } } TEST(QuicVersionsTest, ReservedForNegotiation) { EXPECT_EQ(QUIC_VERSION_RESERVED_FOR_NEGOTIATION, QuicVersionReservedForNegotiation().transport_version); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE(QUIC_VERSION_RESERVED_FOR_NEGOTIATION, version.transport_version); } } TEST(QuicVersionsTest, SupportedVersionsHasCorrectList) { size_t index = 0; for (HandshakeProtocol handshake_protocol : SupportedHandshakeProtocols()) { for (int trans_vers = 255; trans_vers > 0; trans_vers--) { QuicTransportVersion transport_version = static_cast<QuicTransportVersion>(trans_vers); SCOPED_TRACE(index); if (ParsedQuicVersionIsValid(handshake_protocol, transport_version)) { ParsedQuicVersion version = SupportedVersions()[index]; EXPECT_EQ(version, ParsedQuicVersion(handshake_protocol, transport_version)); index++; } } } EXPECT_EQ(SupportedVersions().size(), index); } TEST(QuicVersionsTest, SupportedVersionsAllDistinct) { for (size_t index1 = 0; index1 < SupportedVersions().size(); ++index1) { ParsedQuicVersion version1 = SupportedVersions()[index1]; for (size_t index2 = index1 + 1; index2 < SupportedVersions().size(); ++index2) { ParsedQuicVersion version2 = SupportedVersions()[index2]; EXPECT_NE(version1, version2) << version1 << " " << version2; EXPECT_NE(CreateQuicVersionLabel(version1), CreateQuicVersionLabel(version2)) << version1 << " " << version2; if ((version1 != ParsedQuicVersion::RFCv2()) && (version2 != ParsedQuicVersion::RFCv1())) { EXPECT_NE(AlpnForVersion(version1), AlpnForVersion(version2)) << version1 << " " << version2; } } } } TEST(QuicVersionsTest, CurrentSupportedHttp3Versions) { ParsedQuicVersionVector h3_versions = CurrentSupportedHttp3Versions(); ParsedQuicVersionVector all_current_supported_versions = CurrentSupportedVersions(); for (auto& version : all_current_supported_versions) { bool version_is_h3 = false; for (auto& h3_version : h3_versions) { if (version == h3_version) { EXPECT_TRUE(version.UsesHttp3()); version_is_h3 = true; break; } } if (!version_is_h3) { EXPECT_FALSE(version.UsesHttp3()); } } } TEST(QuicVersionsTest, ObsoleteSupportedVersions) { ParsedQuicVersionVector obsolete_versions = ObsoleteSupportedVersions(); EXPECT_EQ(quic::ParsedQuicVersion::Q046(), obsolete_versions[0]); EXPECT_EQ(quic::ParsedQuicVersion::Draft29(), obsolete_versions[1]); } TEST(QuicVersionsTest, IsObsoleteSupportedVersion) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { bool is_obsolete = version.handshake_protocol != PROTOCOL_TLS1_3 || version.transport_version < QUIC_VERSION_IETF_RFC_V1; EXPECT_EQ(is_obsolete, IsObsoleteSupportedVersion(version)); } } TEST(QuicVersionsTest, CurrentSupportedVersionsForClients) { ParsedQuicVersionVector supported_versions = CurrentSupportedVersions(); ParsedQuicVersionVector client_versions = CurrentSupportedVersionsForClients(); for (auto& version : supported_versions) { const bool is_obsolete = IsObsoleteSupportedVersion(version); const bool is_supported = absl::c_find(client_versions, version) != client_versions.end(); EXPECT_EQ(!is_obsolete, is_supported); } for (auto& version : client_versions) { EXPECT_TRUE(absl::c_find(supported_versions, version) != supported_versions.end()); } } } } }
245
cpp
google/quiche
quic_network_blackhole_detector
quiche/quic/core/quic_network_blackhole_detector.cc
quiche/quic/core/quic_network_blackhole_detector_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_NETWORK_BLACKHOLE_DETECTOR_H_ #define QUICHE_QUIC_CORE_QUIC_NETWORK_BLACKHOLE_DETECTOR_H_ #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace test { class QuicConnectionPeer; class QuicNetworkBlackholeDetectorPeer; } class QUICHE_EXPORT QuicNetworkBlackholeDetector { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() {} virtual void OnPathDegradingDetected() = 0; virtual void OnBlackholeDetected() = 0; virtual void OnPathMtuReductionDetected() = 0; }; QuicNetworkBlackholeDetector(Delegate* delegate, QuicAlarm* alarm); void StopDetection(bool permanent); void RestartDetection(QuicTime path_degrading_deadline, QuicTime blackhole_deadline, QuicTime path_mtu_reduction_deadline); void OnAlarm(); bool IsDetectionInProgress() const; private: friend class test::QuicConnectionPeer; friend class test::QuicNetworkBlackholeDetectorPeer; QuicTime GetEarliestDeadline() const; QuicTime GetLastDeadline() const; void UpdateAlarm() const; Delegate* delegate_; QuicTime path_degrading_deadline_ = QuicTime::Zero(); QuicTime blackhole_deadline_ = QuicTime::Zero(); QuicTime path_mtu_reduction_deadline_ = QuicTime::Zero(); QuicAlarm& alarm_; }; } #endif #include "quiche/quic/core/quic_network_blackhole_detector.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" namespace quic { QuicNetworkBlackholeDetector::QuicNetworkBlackholeDetector(Delegate* delegate, QuicAlarm* alarm) : delegate_(delegate), alarm_(*alarm) {} void QuicNetworkBlackholeDetector::OnAlarm() { QuicTime next_deadline = GetEarliestDeadline(); if (!next_deadline.IsInitialized()) { QUIC_BUG(quic_bug_10328_1) << "BlackholeDetector alarm fired unexpectedly"; return; } QUIC_DVLOG(1) << "BlackholeDetector alarm firing. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; if (path_degrading_deadline_ == next_deadline) { path_degrading_deadline_ = QuicTime::Zero(); delegate_->OnPathDegradingDetected(); } if (path_mtu_reduction_deadline_ == next_deadline) { path_mtu_reduction_deadline_ = QuicTime::Zero(); delegate_->OnPathMtuReductionDetected(); } if (blackhole_deadline_ == next_deadline) { blackhole_deadline_ = QuicTime::Zero(); delegate_->OnBlackholeDetected(); } UpdateAlarm(); } void QuicNetworkBlackholeDetector::StopDetection(bool permanent) { if (permanent) { alarm_.PermanentCancel(); } else { alarm_.Cancel(); } path_degrading_deadline_ = QuicTime::Zero(); blackhole_deadline_ = QuicTime::Zero(); path_mtu_reduction_deadline_ = QuicTime::Zero(); } void QuicNetworkBlackholeDetector::RestartDetection( QuicTime path_degrading_deadline, QuicTime blackhole_deadline, QuicTime path_mtu_reduction_deadline) { path_degrading_deadline_ = path_degrading_deadline; blackhole_deadline_ = blackhole_deadline; path_mtu_reduction_deadline_ = path_mtu_reduction_deadline; QUIC_BUG_IF(quic_bug_12708_1, blackhole_deadline_.IsInitialized() && blackhole_deadline_ != GetLastDeadline()) << "Blackhole detection deadline should be the last deadline."; UpdateAlarm(); } QuicTime QuicNetworkBlackholeDetector::GetEarliestDeadline() const { QuicTime result = QuicTime::Zero(); for (QuicTime t : {path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}) { if (!t.IsInitialized()) { continue; } if (!result.IsInitialized() || t < result) { result = t; } } return result; } QuicTime QuicNetworkBlackholeDetector::GetLastDeadline() const { return std::max({path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}); } void QuicNetworkBlackholeDetector::UpdateAlarm() const { if (alarm_.IsPermanentlyCancelled()) { return; } QuicTime next_deadline = GetEarliestDeadline(); QUIC_DVLOG(1) << "Updating alarm. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; alarm_.Update(next_deadline, kAlarmGranularity); } bool QuicNetworkBlackholeDetector::IsDetectionInProgress() const { return alarm_.IsSet(); } }
#include "quiche/quic/core/quic_network_blackhole_detector.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicNetworkBlackholeDetectorPeer { public: static QuicAlarm* GetAlarm(QuicNetworkBlackholeDetector* detector) { return &detector->alarm_; } }; namespace { class MockDelegate : public QuicNetworkBlackholeDetector::Delegate { public: MOCK_METHOD(void, OnPathDegradingDetected, (), (override)); MOCK_METHOD(void, OnBlackholeDetected, (), (override)); MOCK_METHOD(void, OnPathMtuReductionDetected, (), (override)); }; const size_t kPathDegradingDelayInSeconds = 5; const size_t kPathMtuReductionDelayInSeconds = 7; const size_t kBlackholeDelayInSeconds = 10; class QuicNetworkBlackholeDetectorTest : public QuicTest { public: QuicNetworkBlackholeDetectorTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), detector_(&delegate_, &alarms_.network_blackhole_detector_alarm()), alarm_(static_cast<MockAlarmFactory::TestAlarm*>( QuicNetworkBlackholeDetectorPeer::GetAlarm(&detector_))), path_degrading_delay_( QuicTime::Delta::FromSeconds(kPathDegradingDelayInSeconds)), path_mtu_reduction_delay_( QuicTime::Delta::FromSeconds(kPathMtuReductionDelayInSeconds)), blackhole_delay_( QuicTime::Delta::FromSeconds(kBlackholeDelayInSeconds)) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); ON_CALL(connection_alarms_delegate_, OnNetworkBlackholeDetectorAlarm()) .WillByDefault([&] { detector_.OnAlarm(); }); } protected: void RestartDetection() { detector_.RestartDetection(clock_.Now() + path_degrading_delay_, clock_.Now() + blackhole_delay_, clock_.Now() + path_mtu_reduction_delay_); } testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; QuicNetworkBlackholeDetector detector_; MockAlarmFactory::TestAlarm* alarm_; MockClock clock_; const QuicTime::Delta path_degrading_delay_; const QuicTime::Delta path_mtu_reduction_delay_; const QuicTime::Delta blackhole_delay_; }; TEST_F(QuicNetworkBlackholeDetectorTest, StartAndFire) { EXPECT_FALSE(detector_.IsDetectionInProgress()); RestartDetection(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_degrading_delay_); EXPECT_CALL(delegate_, OnPathDegradingDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_mtu_reduction_delay_ - path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_mtu_reduction_delay_ - path_degrading_delay_); EXPECT_CALL(delegate_, OnPathMtuReductionDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + blackhole_delay_ - path_mtu_reduction_delay_, alarm_->deadline()); clock_.AdvanceTime(blackhole_delay_ - path_mtu_reduction_delay_); EXPECT_CALL(delegate_, OnBlackholeDetected()); alarm_->Fire(); EXPECT_FALSE(detector_.IsDetectionInProgress()); } TEST_F(QuicNetworkBlackholeDetectorTest, RestartAndStop) { RestartDetection(); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); RestartDetection(); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); detector_.StopDetection(false); EXPECT_FALSE(detector_.IsDetectionInProgress()); } TEST_F(QuicNetworkBlackholeDetectorTest, PathDegradingFiresAndRestart) { EXPECT_FALSE(detector_.IsDetectionInProgress()); RestartDetection(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_degrading_delay_); EXPECT_CALL(delegate_, OnPathDegradingDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_mtu_reduction_delay_ - path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); RestartDetection(); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); } } } }
246
cpp
google/quiche
quic_session
quiche/quic/core/quic_session.cc
quiche/quic/core/quic_session_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_SESSION_H_ #define QUICHE_QUIC_CORE_QUIC_SESSION_H_ #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/tls_connection.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_stop_sending_frame.h" #include "quiche/quic/core/frames/quic_window_update_frame.h" #include "quiche/quic/core/handshaker_delegate_interface.h" #include "quiche/quic/core/legacy_quic_stream_id_manager.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_control_frame_manager.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_datagram_queue.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_write_blocked_list.h" #include "quiche/quic/core/session_notifier_interface.h" #include "quiche/quic/core/stream_delegate_interface.h" #include "quiche/quic/core/uber_quic_stream_id_manager.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { class QuicCryptoStream; class QuicFlowController; class QuicStream; class QuicStreamIdManager; namespace test { class QuicSessionPeer; } class QUICHE_EXPORT QuicSession : public QuicConnectionVisitorInterface, public SessionNotifierInterface, public QuicStreamFrameDataProducer, public QuicStreamIdManager::DelegateInterface, public HandshakerDelegateInterface, public StreamDelegateInterface, public QuicControlFrameManager::DelegateInterface { public: class QUICHE_EXPORT Visitor { public: virtual ~Visitor() {} virtual void OnConnectionClosed(QuicConnectionId server_connection_id, QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) = 0; virtual void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) = 0; virtual void OnRstStreamReceived(const QuicRstStreamFrame& frame) = 0; virtual void OnStopSendingReceived(const QuicStopSendingFrame& frame) = 0; virtual bool TryAddNewConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& new_connection_id) = 0; virtual void OnConnectionIdRetired( const QuicConnectionId& server_connection_id) = 0; virtual void OnServerPreferredAddressAvailable( const QuicSocketAddress& ) = 0; virtual void OnPathDegrading() = 0; }; QuicSession(QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicStreamCount num_expected_unidirectional_static_streams); QuicSession(QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicStreamCount num_expected_unidirectional_static_streams, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicPriorityType priority_type = QuicPriorityType::kHttp); QuicSession(const QuicSession&) = delete; QuicSession& operator=(const QuicSession&) = delete; ~QuicSession() override; virtual void Initialize(); virtual const QuicCryptoStream* GetCryptoStream() const = 0; void OnStreamFrame(const QuicStreamFrame& frame) override; void OnCryptoFrame(const QuicCryptoFrame& frame) override; void OnRstStream(const QuicRstStreamFrame& frame) override; void OnGoAway(const QuicGoAwayFrame& frame) override; void OnMessageReceived(absl::string_view message) override; void OnHandshakeDoneReceived() override; void OnNewTokenReceived(absl::string_view token) override; void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; void OnBlockedFrame(const QuicBlockedFrame& frame) override; void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) override; void OnWriteBlocked() override; void OnSuccessfulVersionNegotiation( const ParsedQuicVersion& version) override; void OnPacketReceived(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, bool is_connectivity_probe) override; void OnCanWrite() override; void OnCongestionWindowChange(QuicTime ) override {} void OnConnectionMigration(AddressChangeType ) override {} void OnAckNeedsRetransmittableFrame() override; void SendAckFrequency(const QuicAckFrequencyFrame& frame) override; void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) override; void SendRetireConnectionId(uint64_t sequence_number) override; bool MaybeReserveConnectionId( const QuicConnectionId& server_connection_id) override; void OnServerConnectionIdRetired( const QuicConnectionId& server_connection_id) override; bool WillingAndAbleToWrite() const override; std::string GetStreamsInfoForLogging() const override; void OnPathDegrading() override; void OnForwardProgressMadeAfterPathDegrading() override; bool AllowSelfAddressChange() const override; HandshakeState GetHandshakeState() const override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; void OnStopSendingFrame(const QuicStopSendingFrame& frame) override; void OnPacketDecrypted(EncryptionLevel level) override; void OnOneRttPacketAcknowledged() override; void OnHandshakePacketSent() override; void OnKeyUpdate(KeyUpdateReason ) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void BeforeConnectionCloseSent() override {} bool ValidateToken(absl::string_view token) override; bool MaybeSendAddressToken() override; void CreateContextForMultiPortPath( std::unique_ptr<MultiPortPathContextObserver> ) override {} void MigrateToMultiPortPath( std::unique_ptr<QuicPathValidationContext> ) override {} void OnServerPreferredAddressAvailable( const QuicSocketAddress& ) override; void MaybeBundleOpportunistically() override {} QuicByteCount GetFlowControlSendWindowSize(QuicStreamId id) override; WriteStreamDataResult WriteStreamData(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override; bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override; bool OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) override; void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override; void OnFrameLost(const QuicFrame& frame) override; bool RetransmitFrames(const QuicFrames& frames, TransmissionType type) override; bool IsFrameOutstanding(const QuicFrame& frame) const override; bool HasUnackedCryptoData() const override; bool HasUnackedStreamData() const override; bool CanSendMaxStreams() override; void SendMaxStreams(QuicStreamCount stream_count, bool unidirectional) override; virtual void OnCanCreateNewOutgoingStream(bool ) {} virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet); MessageResult SendMessage(absl::Span<quiche::QuicheMemSlice> message); MessageResult SendMessage(absl::Span<quiche::QuicheMemSlice> message, bool flush); MessageResult SendMessage(quiche::QuicheMemSlice message); virtual void OnMessageAcked(QuicMessageId message_id, QuicTime receive_timestamp); virtual void OnMessageLost(QuicMessageId message_id); void OnControlFrameManagerError(QuicErrorCode error_code, std::string error_details) override; bool WriteControlFrame(const QuicFrame& frame, TransmissionType type) override; virtual void ResetStream(QuicStreamId id, QuicRstStreamErrorCode error); virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason); virtual void SendBlocked(QuicStreamId id, QuicStreamOffset byte_offset); virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset); virtual void OnStreamClosed(QuicStreamId stream_id); virtual bool IsEncryptionEstablished() const; bool OneRttKeysAvailable() const; virtual void OnConfigNegotiated(); virtual std::optional<std::string> OnAlpsData(const uint8_t* alps_data, size_t alps_length); bool OnNewDecryptionKeyAvailable(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool set_alternative_decrypter, bool latch_once_used) override; void OnNewEncryptionKeyAvailable( EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) override; void SetDefaultEncryptionLevel(EncryptionLevel level) override; void OnTlsHandshakeComplete() override; void OnTlsHandshakeConfirmed() override {} void DiscardOldDecryptionKey(EncryptionLevel level) override; void DiscardOldEncryptionKey(EncryptionLevel level) override; void NeuterUnencryptedData() override; void NeuterHandshakeData() override; void OnZeroRttRejected(int reason) override; bool FillTransportParameters(TransportParameters* params) override; QuicErrorCode ProcessTransportParameters(const TransportParameters& params, bool is_resumption, std::string* error_details) override; void OnHandshakeCallbackDone() override; bool PacketFlusherAttached() const override; ParsedQuicVersion parsed_version() const override { return version(); } void OnEncryptedClientHelloSent( absl::string_view client_hello) const override; void OnEncryptedClientHelloReceived( absl::string_view client_hello) const override; void OnStreamError(QuicErrorCode error_code, std::string error_details) override; void OnStreamError(QuicErrorCode error_code, QuicIetfTransportErrorCodes ietf_error, std::string error_details) override; void RegisterStreamPriority(QuicStreamId id, bool is_static, const QuicStreamPriority& priority) override; void UnregisterStreamPriority(QuicStreamId id) override; void UpdateStreamPriority(QuicStreamId id, const QuicStreamPriority& new_priority) override; QuicConsumedData WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) override; size_t SendCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset, TransmissionType type) override; virtual void OnCryptoHandshakeMessageSent( const CryptoHandshakeMessage& message); virtual void OnCryptoHandshakeMessageReceived( const CryptoHandshakeMessage& message); QuicConfig* config() { return &config_; } const QuicConfig* config() const { return &config_; } bool IsClosedStream(QuicStreamId id); QuicConnection* connection() { return connection_; } const QuicConnection* connection() const { return connection_; } const QuicSocketAddress& peer_address() const { return connection_->peer_address(); } const QuicSocketAddress& self_address() const { return connection_->self_address(); } QuicConnectionId connection_id() const { return connection_->connection_id(); } size_t GetNumActiveStreams() const; virtual void MarkConnectionLevelWriteBlocked(QuicStreamId id); void MaybeCloseZombieStream(QuicStreamId id); bool HasPendingHandshake() const; bool HasDataToWrite() const; void ValidatePath( std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate, PathValidationReason reason); bool HasPendingPathValidation() const; bool MigratePath(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicPacketWriter* writer, bool owns_writer); QuicPacketLength GetCurrentLargestMessagePayload() const; QuicPacketLength GetGuaranteedLargestMessagePayload() const; bool transport_goaway_sent() const { return transport_goaway_sent_; } bool transport_goaway_received() const { return transport_goaway_received_; } QuicErrorCode error() const { return on_closed_frame_.quic_error_code; } uint64_t wire_error() const { return on_closed_frame_.wire_error_code; } const std::string& error_details() const { return on_closed_frame_.error_details; } uint64_t transport_close_frame_type() const { return on_closed_frame_.transport_close_frame_type; } QuicConnectionCloseType close_type() const { return on_closed_frame_.close_type; } Perspective perspective() const { return perspective_; } QuicFlowController* flow_controller() { return &flow_controller_; } bool IsConnectionFlowControlBlocked() const; bool IsStreamFlowControlBlocked(); size_t max_open_incoming_bidirectional_streams() const; size_t max_open_incoming_unidirectional_streams() const; size_t MaxAvailableBidirectionalStreams() const; size_t MaxAvailableUnidirectionalStreams() const; QuicStream* GetOrCreateStream(const QuicStreamId stream_id); void StreamDraining(QuicStreamId id, bool unidirectional); virtual bool ShouldYield(QuicStreamId stream_id); void CleanUpClosedStreams(); const ParsedQuicVersionVector& supported_versions() const { return supported_versions_; } QuicStreamId next_outgoing_bidirectional_stream_id() const; QuicStreamId next_outgoing_unidirectional_stream_id() const; bool IsIncomingStream(QuicStreamId id) const; static void RecordConnectionCloseAtServer(QuicErrorCode error, ConnectionCloseSource source); QuicTransportVersion transport_version() const { return connection_->transport_version(); } ParsedQuicVersion version() const { return connection_->version(); } bool is_configured() const { return is_configured_; } void NeuterCryptoDataOfEncryptionLevel(EncryptionLevel level); virtual std::vector<std::string> GetAlpnsToOffer() const { return std::vector<std::string>({AlpnForVersion(connection()->version())}); } virtual std::vector<absl::string_view>::const_iterator SelectAlpn( const std::vector<absl::string_view>& alpns) const; virtual void OnAlpnSelected(absl::string_view alpn); virtual bool ResumeApplicationState(ApplicationState* ) { return true; } virtual void MaybeSendRstStreamFrame(QuicStreamId id, QuicResetStreamError error, QuicStreamOffset bytes_written); virtual void MaybeSendStopSendingFrame(QuicStreamId id, QuicResetStreamError error); EncryptionLevel GetEncryptionLevelToSendApplicationData() const; const std::optional<std::string> user_agent_id() const { return user_agent_id_; } void SetUserAgentId(std::string user_agent_id) { user_agent_id_ = std::move(user_agent_id); connection()->OnUserAgentIdKnown(*user_agent_id_); } void SetSourceAddressTokenToSend(absl::string_view token) { connection()->SetSourceAddressTokenToSend(token); } const QuicClock* GetClock() const { return connection()->helper()->GetClock(); } bool liveness_testing_in_progress() const { return liveness_testing_in_progress_; } virtual QuicSSLConfig GetSSLConfig() const { return QuicSSLConfig(); } void ProcessAllPendingStreams(); const ParsedQuicVersionVector& client_original_supported_versions() const { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); return client_original_supported_versions_; } void set_client_original_supported_versions( const ParsedQuicVersionVector& client_original_supported_versions) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); client_original_supported_versions_ = client_original_supported_versions; } void SetForceFlushForDefaultQueue(bool force_flush) { datagram_queue_.SetForceFlush(force_flush); } uint64_t expired_datagrams_in_default_queue() const { return datagram_queue_.expired_datagram_count(); } uint64_t total_datagrams_lost() const { return total_datagrams_lost_; } QuicStream* GetActiveStream(QuicStreamId id) const; void OnStreamCountReset(); QuicPriorityType priority_type() const { return priority_type_; } protected: using StreamMap = absl::flat_hash_map<QuicStreamId, std::unique_ptr<QuicStream>>; using PendingStreamMap = quiche::QuicheLinkedHashMap<QuicStreamId, std::unique_ptr<PendingStream>>; using ClosedStreams = std::vector<std::unique_ptr<QuicStream>>; using ZombieStreamMap = absl::flat_hash_map<QuicStreamId, std::unique_ptr<QuicStream>>; std::string on_closed_frame_string() const; virtual QuicStream* CreateIncomingStream(QuicStreamId id) = 0; virtual QuicStream* CreateIncomingStream(PendingStream* pending) = 0; virtual QuicCryptoStream* GetMutableCryptoStream() = 0; virtual void ActivateStream(std::unique_ptr<QuicStream> stream); void SetTransmissionType(TransmissionType type); QuicStreamId GetNextOutgoingBidirectionalStreamId(); QuicStreamId GetNextOutgoingUnidirectionalStreamId(); bool CanO
#include "quiche/quic/core/quic_session.h" #include <cstdint> #include <memory> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_max_streams_frame.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_send_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_mem_slice_storage.h" using spdy::kV3HighestPriority; using spdy::SpdyPriority; using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::InSequence; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::Return; using ::testing::StrictMock; using ::testing::WithArg; namespace quic { namespace test { namespace { class TestCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit TestCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), encryption_established_(false), one_rtt_keys_available_(false), params_(new QuicCryptoNegotiatedParameters) { params_->cipher_suite = 1; } void EstablishZeroRttEncryption() { encryption_established_ = true; session()->connection()->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(session()->perspective())); } void OnHandshakeMessage(const CryptoHandshakeMessage& ) override { encryption_established_ = true; one_rtt_keys_available_ = true; QuicErrorCode error; std::string error_details; session()->config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session()->config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (session()->version().UsesTls()) { if (session()->perspective() == Perspective::IS_CLIENT) { session()->config()->SetOriginalConnectionIdToSend( session()->connection()->connection_id()); session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->connection_id()); } else { session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->client_connection_id()); } TransportParameters transport_parameters; EXPECT_TRUE( session()->config()->FillTransportParameters(&transport_parameters)); error = session()->config()->ProcessTransportParameters( transport_parameters, false, &error_details); } else { CryptoHandshakeMessage msg; session()->config()->ToHandshakeMessage(&msg, transport_version()); error = session()->config()->ProcessPeerHello(msg, CLIENT, &error_details); } EXPECT_THAT(error, IsQuicNoError()); session()->OnNewEncryptionKeyAvailable( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(session()->perspective())); session()->OnConfigNegotiated(); if (session()->connection()->version().handshake_protocol == PROTOCOL_TLS1_3) { session()->OnTlsHandshakeComplete(); } else { session()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } session()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return encryption_established_; } bool one_rtt_keys_available() const override { return one_rtt_keys_available_; } const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override { return *params_; } CryptoMessageParser* crypto_message_parser() override { return QuicCryptoHandshaker::crypto_message_parser(); } void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view ) override {} std::string GetAddressToken( const CachedNetworkParameters* ) const override { return ""; } bool ValidateAddressToken(absl::string_view ) const override { return true; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters ) override {} HandshakeState GetHandshakeState() const override { return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override {} MOCK_METHOD(std::unique_ptr<QuicDecrypter>, AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override)); MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (), (override)); MOCK_METHOD(void, OnCanWrite, (), (override)); bool HasPendingCryptoRetransmission() const override { return false; } MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) override {} bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { return false; } SSL* GetSsl() const override { return nullptr; } bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return ENCRYPTION_FORWARD_SECURE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } private: using QuicCryptoStream::session; bool encryption_established_; bool one_rtt_keys_available_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; }; class TestStream : public QuicStream { public: TestStream(QuicStreamId id, QuicSession* session, StreamType type) : TestStream(id, session, false, type) {} TestStream(QuicStreamId id, QuicSession* session, bool is_static, StreamType type) : QuicStream(id, session, is_static, type) {} TestStream(PendingStream* pending, QuicSession* session) : QuicStream(pending, session, false) {} using QuicStream::CloseWriteSide; using QuicStream::WriteMemSlices; void OnDataAvailable() override {} MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, RetransmitStreamData, (QuicStreamOffset, QuicByteCount, bool, TransmissionType), (override)); MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); }; class TestSession : public QuicSession { public: explicit TestSession(QuicConnection* connection, MockQuicSessionVisitor* session_visitor) : QuicSession(connection, session_visitor, DefaultQuicConfig(), CurrentSupportedVersions(), 0), crypto_stream_(this), writev_consumes_all_data_(false), uses_pending_streams_(false), num_incoming_streams_created_(0) { set_max_streams_accepted_per_loop(5); Initialize(); this->connection()->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection->perspective())); if (this->connection()->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(this->connection()); } } ~TestSession() override { DeleteConnection(); } TestCryptoStream* GetMutableCryptoStream() override { return &crypto_stream_; } const TestCryptoStream* GetCryptoStream() const override { return &crypto_stream_; } TestStream* CreateOutgoingBidirectionalStream() { QuicStreamId id = GetNextOutgoingBidirectionalStreamId(); if (id == QuicUtils::GetInvalidStreamId(connection()->transport_version())) { return nullptr; } TestStream* stream = new TestStream(id, this, BIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } TestStream* CreateOutgoingUnidirectionalStream() { TestStream* stream = new TestStream(GetNextOutgoingUnidirectionalStreamId(), this, WRITE_UNIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } TestStream* CreateIncomingStream(QuicStreamId id) override { if (!VersionHasIetfQuicFrames(connection()->transport_version()) && stream_id_manager().num_open_incoming_streams() + 1 > max_open_incoming_bidirectional_streams()) { connection()->CloseConnection( QUIC_TOO_MANY_OPEN_STREAMS, "Too many streams!", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return nullptr; } TestStream* stream = new TestStream( id, this, DetermineStreamType(id, connection()->version(), perspective(), true, BIDIRECTIONAL)); ActivateStream(absl::WrapUnique(stream)); ++num_incoming_streams_created_; return stream; } TestStream* CreateIncomingStream(PendingStream* pending) override { TestStream* stream = new TestStream(pending, this); ActivateStream(absl::WrapUnique(stream)); ++num_incoming_streams_created_; return stream; } QuicStream* ProcessBidirectionalPendingStream( PendingStream* pending) override { return CreateIncomingStream(pending); } QuicStream* ProcessReadUnidirectionalPendingStream( PendingStream* pending) override { struct iovec iov; if (pending->sequencer()->GetReadableRegion(&iov)) { return CreateIncomingStream(pending); } return nullptr; } bool IsClosedStream(QuicStreamId id) { return QuicSession::IsClosedStream(id); } QuicStream* GetOrCreateStream(QuicStreamId stream_id) { return QuicSession::GetOrCreateStream(stream_id); } bool ShouldKeepConnectionAlive() const override { return GetNumActiveStreams() > 0; } QuicConsumedData WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) override { bool fin = state != NO_FIN; QuicConsumedData consumed(write_length, fin); if (!writev_consumes_all_data_) { consumed = QuicSession::WritevData(id, write_length, offset, state, type, level); } QuicSessionPeer::GetWriteBlockedStreams(this)->UpdateBytesForStream( id, consumed.bytes_consumed); return consumed; } MOCK_METHOD(void, OnCanCreateNewOutgoingStream, (bool unidirectional), (override)); void set_writev_consumes_all_data(bool val) { writev_consumes_all_data_ = val; } QuicConsumedData SendStreamData(QuicStream* stream) { if (!QuicUtils::IsCryptoStreamId(connection()->transport_version(), stream->id()) && this->connection()->encryption_level() != ENCRYPTION_FORWARD_SECURE) { this->connection()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } QuicStreamPeer::SendBuffer(stream).SaveStreamData("not empty"); QuicConsumedData consumed = WritevData(stream->id(), 9, 0, FIN, NOT_RETRANSMISSION, GetEncryptionLevelToSendApplicationData()); QuicStreamPeer::SendBuffer(stream).OnStreamDataConsumed( consumed.bytes_consumed); return consumed; } const QuicFrame& save_frame() { return save_frame_; } bool SaveFrame(const QuicFrame& frame) { save_frame_ = frame; DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } QuicConsumedData SendLargeFakeData(QuicStream* stream, int bytes) { QUICHE_DCHECK(writev_consumes_all_data_); return WritevData(stream->id(), bytes, 0, FIN, NOT_RETRANSMISSION, GetEncryptionLevelToSendApplicationData()); } bool UsesPendingStreamForFrame(QuicFrameType type, QuicStreamId stream_id) const override { if (!uses_pending_streams_) { return false; } bool is_incoming_stream = IsIncomingStream(stream_id); StreamType stream_type = QuicUtils::GetStreamType( stream_id, perspective(), is_incoming_stream, version()); switch (type) { case STREAM_FRAME: ABSL_FALLTHROUGH_INTENDED; case RST_STREAM_FRAME: return is_incoming_stream; case STOP_SENDING_FRAME: ABSL_FALLTHROUGH_INTENDED; case WINDOW_UPDATE_FRAME: return stream_type == BIDIRECTIONAL; default: return false; } } void set_uses_pending_streams(bool uses_pending_streams) { uses_pending_streams_ = uses_pending_streams; } int num_incoming_streams_created() const { return num_incoming_streams_created_; } using QuicSession::ActivateStream; using QuicSession::CanOpenNextOutgoingBidirectionalStream; using QuicSession::CanOpenNextOutgoingUnidirectionalStream; using QuicSession::closed_streams; using QuicSession::GetNextOutgoingBidirectionalStreamId; using QuicSession::GetNextOutgoingUnidirectionalStreamId; private: StrictMock<TestCryptoStream> crypto_stream_; bool writev_consumes_all_data_; bool uses_pending_streams_; QuicFrame save_frame_; int num_incoming_streams_created_; }; MATCHER_P(IsFrame, type, "") { return arg.type == type; } class QuicSessionTestBase : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicSessionTestBase(Perspective perspective, bool configure_session) : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, SupportedVersions(GetParam()))), session_(connection_, &session_visitor_), configure_session_(configure_session) { session_.config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session_.config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (configure_session) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1); EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(true)).Times(1); } QuicConfigPeer::SetReceivedMaxBidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_.OnConfigNegotiated(); } TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_CALL(*crypto_stream, HasPendingRetransmission()) .Times(testing::AnyNumber()); testing::Mock::VerifyAndClearExpectations(&session_); } ~QuicSessionTestBase() { if (configure_session_) { EXPECT_TRUE(session_.is_configured()); } } void CheckClosedStreams() { QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(connection_->transport_version()); } for (QuicStreamId i = first_stream_id; i < 100; i++) { if (closed_streams_.find(i) == closed_streams_.end()) { EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i; } else { EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i; } } } void CloseStream(QuicStreamId id) { if (VersionHasIetfQuicFrames(transport_version())) { if (QuicUtils::GetStreamType( id, session_.perspective(), session_.IsIncomingStream(id), connection_->version()) == READ_UNIDIRECTIONAL) { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME))) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)).Times(1); } else if (QuicUtils::GetStreamType( id, session_.perspective(), session_.IsIncomingStream(id), connection_->version()) == WRITE_UNIDIRECTIONAL) { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME))) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } else { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME))) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME))) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } } else { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } session_.ResetStream(id, QUIC_STREAM_CANCELLED); closed_streams_.insert(id); } void CompleteHandshake() { CryptoHandshakeMessage msg; if (connection_->version().UsesTls() && connection_->perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); } session_.GetMutableCryptoStream()->OnHandshakeMessage(msg); } QuicTransportVersion transport_version() const { return connection_->transport_version(); } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthServerInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId( connection_->transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId StreamCountToId(QuicStreamCount stream_count, Perspective perspective, bool bidirectional) { QuicStreamId id = ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version())); if (!bidirectional) { id |= 0x2; } if (perspective == Perspective::IS_SERVER) { id |= 0x1; } return id; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; NiceMock<MockQuicSessionVisitor> session_visitor_; StrictMock<MockQuicConnection>* connection_; TestSession session_; std::set<QuicStreamId> closed_streams_; bool configure_session_; }; class QuicSessionTestServer : public QuicSessionTestBase { public: WriteResult CheckMultiPathResponse(const char* buffer, size_t buf_len, const QuicIpAddress& , const QuicSocketAddress& , PerPacketOptions* ) { QuicEncryptedPacket packet(buffer, buf_len); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)) .WillOnce( WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) { EXPECT_EQ(path_frame_buffer1_, frame.data_buffer); return true; }))); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)) .WillOnce( WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) { EXPECT_EQ(path_frame_buffer2_, frame.data_buffer); return true; }))); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } client_framer_.ProcessPacket(packet); return WriteResult(WRITE_STATUS_OK, 0); } protected: QuicSessionTestServer() : QuicSessionTestBase(Perspective::IS_SERVER, true), path_frame_buffer1_({0, 1, 2, 3, 4, 5, 6, 7}), path_frame_buffer2_({8, 9, 10, 11, 12, 13, 14, 15}), client_framer_(SupportedVersions(GetParam()), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength) { client_framer_.set_visitor(&framer_visitor_); client_framer_.SetInitialObfuscators(TestConnectionId()); if (client_framer_.version().KnowsWhichDecrypterToUse()) { client_framer_.InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullDecrypter>(Perspective::IS_CLIENT)); } } QuicPathFrameBuffer path_frame_buffer1_; QuicPathFrameBuffer path_frame_buffer2_; StrictMock<MockFramerVisitor> framer_visitor_; QuicFramer client_framer_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestServer, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSessionTestServer, PeerAddress) { EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort), session_.peer_address()); } TEST_P(QuicSessionTestServer, SelfAddress) { EXPECT_TRUE(session_.self_address().IsInitialized()); } TEST_P(QuicSessionTestServer, DontCallOnWriteBlockedForDisconnectedConnection) { EXPECT_CALL(*connection_, CloseConnection(_, _, _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); connection_->CloseConnection(QUIC_NO_ERROR, "Everything is fine.", ConnectionCloseBehavior::SILENT_CLOSE); ASSERT_FALSE(connection_->connected()); EXPECT_CALL(session_visitor_, OnWriteBlocked(_)).Times(0); session_.OnWriteBlocked(); } TEST_P(QuicSessionTestServer, OneRttKeysAvailable) { EXPECT_FALSE(session_.OneRttKeysAvailable()); CompleteHandshake(); EXPECT_TRUE(session_.OneRttKeysAvailable()); } TEST_P(QuicSessionTestServer, IsClosedStreamDefault) { QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(connection_->transport_version()); } for (QuicStreamId i = first_stream_id; i < 100; i++) { EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i; } } TEST_P(QuicSessionTestServer, AvailableBidirectionalStreams) { ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(3)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedBidirectionalId(1))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedBidirectionalId(2))); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(2)) != nullptr); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(1)) != nullptr); } TEST_P(QuicSessionTestServer, AvailableUnidirectionalStreams) { ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(3)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedUnidirectionalId(1))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedUnidirectionalId(2))); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(2)) != nullptr); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(1)) != nullptr); } TEST_P(QuicSessionTestServer, MaxAvailableBidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_EQ(session_.max_open_incoming_bidirectional_streams(), session_.MaxAvailableBidirectionalStreams()); } else { EXPECT_EQ(session_.max_open_incoming_bidirectional_streams() * kMaxAvailableStreamsMultiplier, session_.MaxAvailableBidirectionalStreams()); } } TEST_P(QuicSessionTestServer, MaxAvailableUnidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_EQ(session_.max_open_incoming_unidirectional_streams(), session_.MaxAvailableUnidirectionalStreams()); } else { EXPECT_EQ(session_.max_open_incoming_unidirectional_streams() * kMaxAvailableStreamsMultiplier, session_.MaxAvailableUnidirectionalStreams()); } } TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamLocallyCreated) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(0), stream2->id()); TestStream* stream4 = session_.CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(1), stream4->id()); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(0)); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(1)); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamLocallyCreated) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingUnidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(0), stream2->id()); TestStream* stream4 = session_.CreateOutgoingUnidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(1), stream4->id()); CheckClosedStreams(); CloseStream(GetNthServerInitiatedUnidirectionalId(0)); CheckClosedStreams(); CloseStream(GetNthServerInitiatedUnidirectionalId(1)); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamPeerCreated) { CompleteHandshake(); QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0); QuicStreamId stream_id2 = GetNthClientInitiatedBidirectionalId(1); session_.GetOrCreateStream(stream_id1); session_.GetOrCreateStream(stream_id2); CheckClosedStreams(); CloseStream(stream_id1); CheckClosedStreams(); CloseStream(stream_id2); QuicStream* stream3 = session_.GetOrCreateStream( stream_id2 + 2 * QuicUtils::StreamIdDelta(connection_->transport_version())); CheckClosedStreams(); CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamPeerCreated) { CompleteHandshake(); QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0); QuicStreamId stream_id2 = GetNthClientInitiatedUnidirectionalId(1); session_.GetOrCreateStream(stream_id1); session_.GetOrCreateStream(stream_id2); CheckClosedStreams(); CloseStream(stream_id1); CheckClosedStreams(); CloseStream(stream_id2); QuicStream* stream3 = session_.GetOrCreateStream( stream_id2 + 2 * QuicUtils::StreamIdDelta(connection_->transport_version())); CheckClosedStreams(); CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, MaximumAvailableOpenedBidirectionalStreams) { QuicStreamId stream_id = GetNthClientInitiatedBidir
247
cpp
google/quiche
quic_chaos_protector
quiche/quic/core/quic_chaos_protector.cc
quiche/quic/core/quic_chaos_protector_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CHAOS_PROTECTOR_H_ #define QUICHE_QUIC_CORE_QUIC_CHAOS_PROTECTOR_H_ #include <cstddef> #include <memory> #include <optional> #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_types.h" namespace quic { namespace test { class QuicChaosProtectorTest; } class QUICHE_EXPORT QuicChaosProtector : public QuicStreamFrameDataProducer { public: explicit QuicChaosProtector(const QuicCryptoFrame& crypto_frame, int num_padding_bytes, size_t packet_size, QuicFramer* framer, QuicRandom* random); ~QuicChaosProtector() override; QuicChaosProtector(const QuicChaosProtector&) = delete; QuicChaosProtector(QuicChaosProtector&&) = delete; QuicChaosProtector& operator=(const QuicChaosProtector&) = delete; QuicChaosProtector& operator=(QuicChaosProtector&&) = delete; std::optional<size_t> BuildDataPacket(const QuicPacketHeader& header, char* buffer); WriteStreamDataResult WriteStreamData(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* ) override; bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override; private: friend class test::QuicChaosProtectorTest; bool CopyCryptoDataToLocalBuffer(); void SplitCryptoFrame(); void AddPingFrames(); void ReorderFrames(); void SpreadPadding(); std::optional<size_t> BuildPacket(const QuicPacketHeader& header, char* buffer); size_t packet_size_; std::unique_ptr<char[]> crypto_frame_buffer_; const char* crypto_data_buffer_ = nullptr; QuicByteCount crypto_data_length_; QuicStreamOffset crypto_buffer_offset_; EncryptionLevel level_; int remaining_padding_bytes_; QuicFrames frames_; QuicFramer* framer_; QuicRandom* random_; }; } #endif #include "quiche/quic/core/quic_chaos_protector.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_padding_frame.h" #include "quiche/quic/core/frames/quic_ping_frame.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QuicChaosProtector::QuicChaosProtector(const QuicCryptoFrame& crypto_frame, int num_padding_bytes, size_t packet_size, QuicFramer* framer, QuicRandom* random) : packet_size_(packet_size), crypto_data_length_(crypto_frame.data_length), crypto_buffer_offset_(crypto_frame.offset), level_(crypto_frame.level), remaining_padding_bytes_(num_padding_bytes), framer_(framer), random_(random) { QUICHE_DCHECK_NE(framer_, nullptr); QUICHE_DCHECK_NE(framer_->data_producer(), nullptr); QUICHE_DCHECK_NE(random_, nullptr); } QuicChaosProtector::~QuicChaosProtector() { DeleteFrames(&frames_); } std::optional<size_t> QuicChaosProtector::BuildDataPacket( const QuicPacketHeader& header, char* buffer) { if (!CopyCryptoDataToLocalBuffer()) { return std::nullopt; } SplitCryptoFrame(); AddPingFrames(); SpreadPadding(); ReorderFrames(); return BuildPacket(header, buffer); } WriteStreamDataResult QuicChaosProtector::WriteStreamData( QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* ) { QUIC_BUG(chaos stream) << "This should never be called; id " << id << " offset " << offset << " data_length " << data_length; return STREAM_MISSING; } bool QuicChaosProtector::WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { if (level != level_) { QUIC_BUG(chaos bad level) << "Unexpected " << level << " != " << level_; return false; } if (offset < crypto_buffer_offset_ || data_length > crypto_data_length_ || offset - crypto_buffer_offset_ > crypto_data_length_ - data_length) { QUIC_BUG(chaos bad lengths) << "Unexpected buffer_offset_ " << crypto_buffer_offset_ << " offset " << offset << " buffer_length_ " << crypto_data_length_ << " data_length " << data_length; return false; } writer->WriteBytes(&crypto_data_buffer_[offset - crypto_buffer_offset_], data_length); return true; } bool QuicChaosProtector::CopyCryptoDataToLocalBuffer() { crypto_frame_buffer_ = std::make_unique<char[]>(packet_size_); frames_.push_back(QuicFrame( new QuicCryptoFrame(level_, crypto_buffer_offset_, crypto_data_length_))); QuicDataWriter writer(packet_size_, crypto_frame_buffer_.get()); if (!framer_->AppendCryptoFrame(*frames_.front().crypto_frame, &writer)) { QUIC_BUG(chaos write crypto data); return false; } QuicDataReader reader(crypto_frame_buffer_.get(), writer.length()); uint64_t parsed_offset, parsed_length; if (!reader.ReadVarInt62(&parsed_offset) || !reader.ReadVarInt62(&parsed_length)) { QUIC_BUG(chaos parse crypto frame); return false; } absl::string_view crypto_data = reader.ReadRemainingPayload(); crypto_data_buffer_ = crypto_data.data(); QUICHE_DCHECK_EQ(parsed_offset, crypto_buffer_offset_); QUICHE_DCHECK_EQ(parsed_length, crypto_data_length_); QUICHE_DCHECK_EQ(parsed_length, crypto_data.length()); return true; } void QuicChaosProtector::SplitCryptoFrame() { const int max_overhead_of_adding_a_crypto_frame = static_cast<int>(QuicFramer::GetMinCryptoFrameSize( crypto_buffer_offset_ + crypto_data_length_, crypto_data_length_)); constexpr uint64_t kMaxAddedCryptoFrames = 10; const uint64_t num_added_crypto_frames = random_->InsecureRandUint64() % (kMaxAddedCryptoFrames + 1); for (uint64_t i = 0; i < num_added_crypto_frames; i++) { if (remaining_padding_bytes_ < max_overhead_of_adding_a_crypto_frame) { break; } size_t frame_to_split_index = random_->InsecureRandUint64() % frames_.size(); QuicCryptoFrame* frame_to_split = frames_[frame_to_split_index].crypto_frame; if (frame_to_split->data_length <= 1) { continue; } const int frame_to_split_old_overhead = static_cast<int>(QuicFramer::GetMinCryptoFrameSize( frame_to_split->offset, frame_to_split->data_length)); const QuicPacketLength frame_to_split_new_data_length = 1 + (random_->InsecureRandUint64() % (frame_to_split->data_length - 1)); const QuicPacketLength new_frame_data_length = frame_to_split->data_length - frame_to_split_new_data_length; const QuicStreamOffset new_frame_offset = frame_to_split->offset + frame_to_split_new_data_length; frame_to_split->data_length -= new_frame_data_length; frames_.push_back(QuicFrame( new QuicCryptoFrame(level_, new_frame_offset, new_frame_data_length))); const int frame_to_split_new_overhead = static_cast<int>(QuicFramer::GetMinCryptoFrameSize( frame_to_split->offset, frame_to_split->data_length)); const int new_frame_overhead = static_cast<int>(QuicFramer::GetMinCryptoFrameSize( new_frame_offset, new_frame_data_length)); QUICHE_DCHECK_LE(frame_to_split_new_overhead, frame_to_split_old_overhead); remaining_padding_bytes_ -= new_frame_overhead; remaining_padding_bytes_ -= frame_to_split_new_overhead; remaining_padding_bytes_ += frame_to_split_old_overhead; } } void QuicChaosProtector::AddPingFrames() { if (remaining_padding_bytes_ == 0) { return; } constexpr uint64_t kMaxAddedPingFrames = 10; const uint64_t num_ping_frames = random_->InsecureRandUint64() % std::min<uint64_t>(kMaxAddedPingFrames, remaining_padding_bytes_); for (uint64_t i = 0; i < num_ping_frames; i++) { frames_.push_back(QuicFrame(QuicPingFrame())); } remaining_padding_bytes_ -= static_cast<int>(num_ping_frames); } void QuicChaosProtector::ReorderFrames() { for (size_t i = frames_.size() - 1; i > 0; i--) { std::swap(frames_[i], frames_[random_->InsecureRandUint64() % (i + 1)]); } } void QuicChaosProtector::SpreadPadding() { for (auto it = frames_.begin(); it != frames_.end(); ++it) { const int padding_bytes_in_this_frame = random_->InsecureRandUint64() % (remaining_padding_bytes_ + 1); if (padding_bytes_in_this_frame <= 0) { continue; } it = frames_.insert( it, QuicFrame(QuicPaddingFrame(padding_bytes_in_this_frame))); ++it; remaining_padding_bytes_ -= padding_bytes_in_this_frame; } if (remaining_padding_bytes_ > 0) { frames_.push_back(QuicFrame(QuicPaddingFrame(remaining_padding_bytes_))); } } std::optional<size_t> QuicChaosProtector::BuildPacket( const QuicPacketHeader& header, char* buffer) { QuicStreamFrameDataProducer* original_data_producer = framer_->data_producer(); framer_->set_data_producer(this); size_t length = framer_->BuildDataPacket(header, frames_, buffer, packet_size_, level_); framer_->set_data_producer(original_data_producer); if (length == 0) { return std::nullopt; } return length; } }
#include "quiche/quic/core/quic_chaos_protector.h" #include <cstddef> #include <memory> #include <optional> #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_quic_framer.h" namespace quic { namespace test { class QuicChaosProtectorTest : public QuicTestWithParam<ParsedQuicVersion>, public QuicStreamFrameDataProducer { public: QuicChaosProtectorTest() : version_(GetParam()), framer_({version_}, QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength), validation_framer_({version_}), random_(3), level_(ENCRYPTION_INITIAL), crypto_offset_(0), crypto_data_length_(100), crypto_frame_(level_, crypto_offset_, crypto_data_length_), num_padding_bytes_(50), packet_size_(1000), packet_buffer_(std::make_unique<char[]>(packet_size_)) { ReCreateChaosProtector(); } void ReCreateChaosProtector() { chaos_protector_ = std::make_unique<QuicChaosProtector>( crypto_frame_, num_padding_bytes_, packet_size_, SetupHeaderAndFramers(), &random_); } WriteStreamDataResult WriteStreamData(QuicStreamId , QuicStreamOffset , QuicByteCount , QuicDataWriter* ) override { ADD_FAILURE() << "This should never be called"; return STREAM_MISSING; } bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override { EXPECT_EQ(level, level); EXPECT_EQ(offset, crypto_offset_); EXPECT_EQ(data_length, crypto_data_length_); for (QuicByteCount i = 0; i < data_length; i++) { EXPECT_TRUE(writer->WriteUInt8(static_cast<uint8_t>(i & 0xFF))); } return true; } protected: QuicFramer* SetupHeaderAndFramers() { header_.destination_connection_id = TestConnectionId(); header_.destination_connection_id_included = CONNECTION_ID_PRESENT; header_.source_connection_id = EmptyQuicConnectionId(); header_.source_connection_id_included = CONNECTION_ID_PRESENT; header_.reset_flag = false; header_.version_flag = true; header_.has_possible_stateless_reset_token = false; header_.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header_.version = version_; header_.packet_number = QuicPacketNumber(1); header_.form = IETF_QUIC_LONG_HEADER_PACKET; header_.long_packet_type = INITIAL; header_.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header_.length_length = quiche::kQuicheDefaultLongHeaderLengthLength; validation_framer_.framer()->SetInitialObfuscators( header_.destination_connection_id); framer_.SetInitialObfuscators(header_.destination_connection_id); framer_.set_data_producer(this); return &framer_; } void BuildEncryptAndParse() { std::optional<size_t> length = chaos_protector_->BuildDataPacket(header_, packet_buffer_.get()); ASSERT_TRUE(length.has_value()); ASSERT_GT(length.value(), 0u); size_t encrypted_length = framer_.EncryptInPlace( level_, header_.packet_number, GetStartOfEncryptedData(framer_.transport_version(), header_), length.value(), packet_size_, packet_buffer_.get()); ASSERT_GT(encrypted_length, 0u); ASSERT_TRUE(validation_framer_.ProcessPacket(QuicEncryptedPacket( absl::string_view(packet_buffer_.get(), encrypted_length)))); } void ResetOffset(QuicStreamOffset offset) { crypto_offset_ = offset; crypto_frame_.offset = offset; ReCreateChaosProtector(); } void ResetLength(QuicByteCount length) { crypto_data_length_ = length; crypto_frame_.data_length = length; ReCreateChaosProtector(); } ParsedQuicVersion version_; QuicPacketHeader header_; QuicFramer framer_; SimpleQuicFramer validation_framer_; MockRandom random_; EncryptionLevel level_; QuicStreamOffset crypto_offset_; QuicByteCount crypto_data_length_; QuicCryptoFrame crypto_frame_; int num_padding_bytes_; size_t packet_size_; std::unique_ptr<char[]> packet_buffer_; std::unique_ptr<QuicChaosProtector> chaos_protector_; }; namespace { ParsedQuicVersionVector TestVersions() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.UsesCryptoFrames()) { versions.push_back(version); } } return versions; } INSTANTIATE_TEST_SUITE_P(QuicChaosProtectorTests, QuicChaosProtectorTest, ::testing::ValuesIn(TestVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicChaosProtectorTest, Main) { BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, 0u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 1u); ASSERT_EQ(validation_framer_.ping_frames().size(), 3u); ASSERT_EQ(validation_framer_.padding_frames().size(), 7u); EXPECT_EQ(validation_framer_.padding_frames()[0].num_padding_bytes, 3); } TEST_P(QuicChaosProtectorTest, DifferentRandom) { random_.ResetBase(4); BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u); ASSERT_EQ(validation_framer_.ping_frames().size(), 4u); ASSERT_EQ(validation_framer_.padding_frames().size(), 8u); } TEST_P(QuicChaosProtectorTest, RandomnessZero) { random_.ResetBase(0); BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 1u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_); EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, crypto_data_length_); ASSERT_EQ(validation_framer_.ping_frames().size(), 0u); ASSERT_EQ(validation_framer_.padding_frames().size(), 1u); } TEST_P(QuicChaosProtectorTest, Offset) { ResetOffset(123); BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_); EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 1u); ASSERT_EQ(validation_framer_.ping_frames().size(), 3u); ASSERT_EQ(validation_framer_.padding_frames().size(), 7u); EXPECT_EQ(validation_framer_.padding_frames()[0].num_padding_bytes, 3); } TEST_P(QuicChaosProtectorTest, OffsetAndRandomnessZero) { ResetOffset(123); random_.ResetBase(0); BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 1u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_); EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, crypto_data_length_); ASSERT_EQ(validation_framer_.ping_frames().size(), 0u); ASSERT_EQ(validation_framer_.padding_frames().size(), 1u); } TEST_P(QuicChaosProtectorTest, ZeroRemainingBytesAfterSplit) { QuicPacketLength new_length = 63; num_padding_bytes_ = QuicFramer::GetMinCryptoFrameSize( crypto_frame_.offset + new_length, new_length); ResetLength(new_length); BuildEncryptAndParse(); ASSERT_EQ(validation_framer_.crypto_frames().size(), 2u); EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_); EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 4); EXPECT_EQ(validation_framer_.crypto_frames()[1]->offset, crypto_offset_ + 4); EXPECT_EQ(validation_framer_.crypto_frames()[1]->data_length, crypto_data_length_ - 4); ASSERT_EQ(validation_framer_.ping_frames().size(), 0u); } } } }
248
cpp
google/quiche
quic_dispatcher
quiche/quic/core/quic_dispatcher.cc
quiche/quic/core/quic_dispatcher_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_DISPATCHER_H_ #define QUICHE_QUIC_CORE_QUIC_DISPATCHER_H_ #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/frames/quic_stop_sending_frame.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/core/quic_blocked_writer_list.h" #include "quiche/quic/core/quic_buffered_packet_store.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_process_packet_interface.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_time_wait_list_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_version_manager.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { namespace test { class QuicDispatcherPeer; } class QuicConfig; class QuicCryptoServerConfig; class QUICHE_EXPORT QuicDispatcher : public QuicTimeWaitListManager::Visitor, public ProcessPacketInterface, public QuicBufferedPacketStore::VisitorInterface { public: QuicDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, uint8_t expected_server_connection_id_length, ConnectionIdGeneratorInterface& connection_id_generator); QuicDispatcher(const QuicDispatcher&) = delete; QuicDispatcher& operator=(const QuicDispatcher&) = delete; ~QuicDispatcher() override; void InitializeWithWriter(QuicPacketWriter* writer); void ProcessPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) override; virtual void OnCanWrite(); virtual bool HasPendingWrites() const; void Shutdown(); void OnConnectionClosed(QuicConnectionId server_connection_id, QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) override; void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) override; void OnRstStreamReceived(const QuicRstStreamFrame& frame) override; void OnStopSendingReceived(const QuicStopSendingFrame& frame) override; bool TryAddNewConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& new_connection_id) override; void OnConnectionIdRetired( const QuicConnectionId& server_connection_id) override; void OnServerPreferredAddressAvailable( const QuicSocketAddress& ) override { QUICHE_DCHECK(false); } void OnConnectionAddedToTimeWaitList( QuicConnectionId server_connection_id) override; using ReferenceCountedSessionMap = absl::flat_hash_map<QuicConnectionId, std::shared_ptr<QuicSession>, QuicConnectionIdHash>; size_t NumSessions() const; virtual void DeleteSessions(); void ClearStatelessResetAddresses(); using ConnectionIdMap = absl::flat_hash_map<QuicConnectionId, QuicConnectionId, QuicConnectionIdHash>; void OnExpiredPackets(QuicConnectionId server_connection_id, QuicBufferedPacketStore::BufferedPacketList early_arrived_packets) override; void OnPathDegrading() override {} virtual void ProcessBufferedChlos(size_t max_connections_to_create); virtual bool HasChlosBuffered() const; void StartAcceptingNewConnections(); void StopAcceptingNewConnections(); void PerformActionOnActiveSessions( quiche::UnretainedCallback<void(QuicSession*)> operation) const; std::vector<std::shared_ptr<QuicSession>> GetSessionsSnapshot() const; bool accept_new_connections() const { return accept_new_connections_; } uint64_t num_packets_received() const { return num_packets_received_; } protected: virtual std::unique_ptr<QuicSession> CreateQuicSession( QuicConnectionId server_connection_id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, absl::string_view alpn, const ParsedQuicVersion& version, const ParsedClientHello& parsed_chlo, ConnectionIdGeneratorInterface& connection_id_generator) = 0; virtual bool MaybeDispatchPacket(const ReceivedPacketInfo& packet_info); enum QuicPacketFate { kFateProcess, kFateTimeWait, kFateDrop, }; virtual QuicPacketFate ValidityChecks(const ReceivedPacketInfo& packet_info); virtual QuicPacketFate ValidityChecksOnFullChlo( const ReceivedPacketInfo& , const ParsedClientHello& ) const { return kFateProcess; } virtual QuicTimeWaitListManager* CreateQuicTimeWaitListManager(); void BufferEarlyPacket(const ReceivedPacketInfo& packet_info); void ProcessChlo(ParsedClientHello parsed_chlo, ReceivedPacketInfo* packet_info); QuicTimeWaitListManager* time_wait_list_manager() { return time_wait_list_manager_.get(); } const ParsedQuicVersionVector& GetSupportedVersions(); const QuicConfig& config() const { return *config_; } const QuicCryptoServerConfig* crypto_config() const { return crypto_config_; } QuicCompressedCertsCache* compressed_certs_cache() { return &compressed_certs_cache_; } QuicConnectionHelperInterface* helper() { return helper_.get(); } QuicCryptoServerStreamBase::Helper* session_helper() { return session_helper_.get(); } const QuicCryptoServerStreamBase::Helper* session_helper() const { return session_helper_.get(); } QuicAlarmFactory* alarm_factory() { return alarm_factory_.get(); } QuicPacketWriter* writer() { return writer_.get(); } virtual bool ShouldCreateSessionForUnknownVersion( const ReceivedPacketInfo& packet_info); void SetLastError(QuicErrorCode error); virtual bool OnFailedToDispatchPacket(const ReceivedPacketInfo& packet_info); bool HasBufferedPackets(QuicConnectionId server_connection_id); virtual void OnBufferPacketFailure( QuicBufferedPacketStore::EnqueuePacketResult result, QuicConnectionId server_connection_id); void CleanUpSession(QuicConnectionId server_connection_id, QuicConnection* connection, QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source); void StatelesslyTerminateConnection( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId server_connection_id, PacketHeaderFormat format, bool version_flag, bool use_length_prefix, ParsedQuicVersion version, QuicErrorCode error_code, const std::string& error_details, QuicTimeWaitListManager::TimeWaitAction action); virtual std::unique_ptr<QuicPerPacketContext> GetPerPacketContext() const; virtual void RestorePerPacketContext( std::unique_ptr<QuicPerPacketContext> ) {} void SetShouldUpdateExpectedServerConnectionIdLength( bool should_update_expected_server_connection_id_length) { should_update_expected_server_connection_id_length_ = should_update_expected_server_connection_id_length; } void SetAllowShortInitialServerConnectionIds( bool allow_short_initial_server_connection_ids) { allow_short_initial_server_connection_ids_ = allow_short_initial_server_connection_ids; } virtual void OnNewConnectionRejected() {} virtual void OnStatelessConnectionCloseGenerated( const QuicSocketAddress& , const QuicSocketAddress& , QuicConnectionId , ParsedQuicVersion , QuicErrorCode , const std::string& ) {} std::string SelectAlpn(const std::vector<std::string>& alpns); virtual void MaybeResetPacketsWithNoVersion( const quic::ReceivedPacketInfo& packet_info); virtual void MaybeSendVersionNegotiationPacket( const ReceivedPacketInfo& packet_info); virtual ConnectionIdGeneratorInterface& ConnectionIdGenerator() { return connection_id_generator_; } private: friend class test::QuicDispatcherPeer; void ProcessHeader(ReceivedPacketInfo* packet_info); struct ExtractChloResult { std::optional<ParsedClientHello> parsed_chlo; std::optional<uint8_t> tls_alert; }; ExtractChloResult TryExtractChloOrBufferEarlyPacket( const ReceivedPacketInfo& packet_info); void DeliverPacketsToSession( const std::list<QuicBufferedPacketStore::BufferedPacket>& packets, QuicSession* session); bool IsSupportedVersion(const ParsedQuicVersion version); bool IsServerConnectionIdTooShort(QuicConnectionId connection_id) const; std::shared_ptr<QuicSession> CreateSessionFromChlo( QuicConnectionId original_connection_id, const ParsedClientHello& parsed_chlo, ParsedQuicVersion version, QuicSocketAddress self_address, QuicSocketAddress peer_address, ConnectionIdGeneratorInterface* connection_id_generator); const QuicConfig* config_; const QuicCryptoServerConfig* crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicBlockedWriterList write_blocked_list_; ReferenceCountedSessionMap reference_counted_session_map_; std::unique_ptr<QuicTimeWaitListManager> time_wait_list_manager_; std::vector<std::shared_ptr<QuicSession>> closed_session_list_; std::unique_ptr<QuicConnectionHelperInterface> helper_; std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper_; std::unique_ptr<QuicAlarmFactory> alarm_factory_; std::unique_ptr<QuicAlarm> delete_sessions_alarm_; std::unique_ptr<QuicPacketWriter> writer_; QuicBufferedPacketStore buffered_packets_; QuicVersionManager* version_manager_; QuicErrorCode last_error_; size_t num_sessions_in_session_map_ = 0; uint64_t num_packets_received_ = 0; int16_t new_sessions_allowed_per_event_loop_; bool accept_new_connections_; bool allow_short_initial_server_connection_ids_; uint8_t expected_server_connection_id_length_; absl::flat_hash_set<QuicSocketAddress, QuicSocketAddressHash> recent_stateless_reset_addresses_; std::unique_ptr<QuicAlarm> clear_stateless_reset_addresses_alarm_; bool should_update_expected_server_connection_id_length_; ConnectionIdGeneratorInterface& connection_id_generator_; }; } #endif #include "quiche/quic/core/quic_dispatcher.h" #include <openssl/ssl.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <list> #include <memory> #include <optional> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/chlo_extractor.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/frames/quic_stop_sending_frame.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/core/quic_buffered_packet_store.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_stream_send_buffer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_wait_list_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_version_manager.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_chlo_extractor.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_stack_trace.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/print_elements.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_text_utils.h" namespace quic { using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; namespace { const QuicPacketLength kMinClientInitialPacketLength = 1200; class DeleteSessionsAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit DeleteSessionsAlarm(QuicDispatcher* dispatcher) : dispatcher_(dispatcher) {} DeleteSessionsAlarm(const DeleteSessionsAlarm&) = delete; DeleteSessionsAlarm& operator=(const DeleteSessionsAlarm&) = delete; void OnAlarm() override { dispatcher_->DeleteSessions(); } private: QuicDispatcher* dispatcher_; }; class ClearStatelessResetAddressesAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ClearStatelessResetAddressesAlarm(QuicDispatcher* dispatcher) : dispatcher_(dispatcher) {} ClearStatelessResetAddressesAlarm(const DeleteSessionsAlarm&) = delete; ClearStatelessResetAddressesAlarm& operator=(const DeleteSessionsAlarm&) = delete; void OnAlarm() override { dispatcher_->ClearStatelessResetAddresses(); } private: QuicDispatcher* dispatcher_; }; class StatelessConnectionTerminator { public: StatelessConnectionTerminator(QuicConnectionId server_connection_id, QuicConnectionId original_server_connection_id, const ParsedQuicVersion version, QuicConnectionHelperInterface* helper, QuicTimeWaitListManager* time_wait_list_manager) : server_connection_id_(server_connection_id), framer_(ParsedQuicVersionVector{version}, QuicTime::Zero(), Perspective::IS_SERVER, kQuicDefaultConnectionIdLength), collector_(helper->GetStreamSendBufferAllocator()), creator_(server_connection_id, &framer_, &collector_), time_wait_list_manager_(time_wait_list_manager) { framer_.set_data_producer(&collector_); framer_.SetInitialObfuscators(original_server_connection_id); } ~StatelessConnectionTerminator() { framer_.set_data_producer(nullptr); } void CloseConnection(QuicErrorCode error_code, const std::string& error_details, bool ietf_quic, std::vector<QuicConnectionId> active_connection_ids) { SerializeConnectionClosePacket(error_code, error_details); time_wait_list_manager_->AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(ietf_quic, collector_.packets(), std::move(active_connection_ids), QuicTime::Delta::Zero())); } private: void SerializeConnectionClosePacket(QuicErrorCode error_code, const std::string& error_details) { QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame(framer_.transport_version(), error_code, NO_IETF_QUIC_ERROR, error_details, 0); if (!creator_.AddFrame(QuicFrame(frame), NOT_RETRANSMISSION)) { QUIC_BUG(quic_bug_10287_1) << "Unable to add frame to an empty packet"; delete frame; return; } creator_.FlushCurrentPacket(); QUICHE_DCHECK_EQ(1u, collector_.packets()->size()); } QuicConnectionId server_connection_id_; QuicFramer framer_; PacketCollector collector_; QuicPacketCreator creator_; QuicTimeWaitListManager* time_wait_list_manager_; }; class ChloAlpnSniExtractor : public ChloExtractor::Delegate { public: void OnChlo(QuicTransportVersion , QuicConnectionId , const CryptoHandshakeMessage& chlo) override { absl::string_view alpn_value; if (chlo.GetStringPiece(kALPN, &alpn_value)) { alpn_ = std::string(alpn_value); } absl::string_view sni; if (chlo.GetStringPiece(quic::kSNI, &sni)) { sni_ = std::string(sni); } absl::string_view uaid_value; if (chlo.GetStringPiece(quic::kUAID, &uaid_value)) { uaid_ = std::string(uaid_value); } } std::string&& ConsumeAlpn() { return std::move(alpn_); } std::string&& ConsumeSni() { return std::move(sni_); } std::string&& ConsumeUaid() { return std::move(uaid_); } private: std::string alpn_; std::string sni_; std::string uaid_; }; } QuicDispatcher::QuicDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, uint8_t expected_server_connection_id_length, ConnectionIdGeneratorInterface& connection_id_generator) : config_(config), crypto_config_(crypto_config), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), helper_(std::move(helper)), session_helper_(std::move(session_helper)), alarm_factory_(std::move(alarm_factory)), delete_sessions_alarm_( alarm_factory_->CreateAlarm(new DeleteSessionsAlarm(this))), buffered_packets_(this, helper_->GetClock(), alarm_factory_.get()), version_manager_(version_manager), last_error_(QUIC_NO_ERROR), new_sessions_allowed_per_event_loop_(0u), accept_new_connections_(true), allow_short_initial_server_connection_ids_(false), expected_server_connection_id_length_( expected_server_connection_id_length), clear_stateless_reset_addresses_alarm_(alarm_factory_->CreateAlarm( new ClearStatelessResetAddressesAlarm(this))), should_update_expected_server_connection_id_length_(false), connection_id_generator_(connection_id_generator) { QUIC_BUG_IF(quic_bug_12724_1, GetSupportedVersions().empty()) << "Trying to create dispatcher without any supported versions"; QUIC_DLOG(INFO) << "Created QuicDispatcher with versions: " << ParsedQuicVersionVectorToString(GetSupportedVersions()); } QuicDispatcher::~QuicDispatcher() { if (delete_sessions_alarm_ != nullptr) { delete_sessions_alarm_->PermanentCancel(); } if (clear_stateless_reset_addresses_alarm_ != nullptr) { clear_stateless_reset_addresses_alarm_->PermanentCancel(); } reference_counted_session_map_.clear(); closed_session_list_.clear(); num_sessions_in_session_map_ = 0; } void QuicDispatcher::InitializeWithWriter(QuicPacketWriter* writer) { QUICHE_DCHECK(writer_ == nullptr); writer_.reset(writer); time_wait_list_manager_.reset(CreateQuicTimeWaitListManager()); } void QuicDispatcher::ProcessPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { QUIC_DVLOG(2) << "Dispatcher received encrypted " << packet.length() << " bytes:" << std::endl << quiche::QuicheTextUtils::HexDump( absl::string_view(packet.data(), packet.length())); ++num_packets_received_; ReceivedPacketInfo packet_info(self_address, peer_address, packet); std::string detailed_error; QuicErrorCode error; error = QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( packet, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &packet_info.retry_token, &detailed_error, connection_id_generator_); if (error != QUIC_NO_ERROR) { SetLastError(error); QUIC_DLOG(ERROR) << detailed_error; return; } if (packet_info.destination_connection_id.length() != expected_server_connection_id_length_ && !should_update_expected_server_connection_id_length_ && packet_info.version.IsKnown() && !packet_info.version.AllowsVariableLengthConnectionIds()) { SetLastError(QUIC_INVALID_PACKET_HEADER); QUIC_DLOG(ERROR) << "Invalid Connection Id Length"; return; } if (packet_info.version_flag && IsSupportedVersion(packet_info.version)) { if (!QuicUtils::IsConnectionIdValidForVersion( packet_info.destination_connection_id,
#include "quiche/quic/core/quic_dispatcher.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/chlo_extractor.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/http/quic_server_session_base.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packet_writer_wrapper.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_wait_list_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_version_manager.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/first_flight.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/mock_quic_time_wait_list_manager.h" #include "quiche/quic/test_tools/quic_buffered_packet_store_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_dispatcher_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; using testing::AllOf; using testing::ByMove; using testing::ElementsAreArray; using testing::Eq; using testing::Field; using testing::InSequence; using testing::Invoke; using testing::IsEmpty; using testing::NiceMock; using testing::Not; using testing::Ref; using testing::Return; using testing::ReturnRef; using testing::WithArg; using testing::WithoutArgs; static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; static const int16_t kMaxNumSessionsToCreate = 16; namespace quic { namespace test { namespace { const QuicConnectionId kReturnConnectionId{ {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}}; class TestQuicSpdyServerSession : public QuicServerSessionBase { public: TestQuicSpdyServerSession(const QuicConfig& config, QuicConnection* connection, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicServerSessionBase(config, CurrentSupportedVersions(), connection, nullptr, nullptr, crypto_config, compressed_certs_cache) { Initialize(); } TestQuicSpdyServerSession(const TestQuicSpdyServerSession&) = delete; TestQuicSpdyServerSession& operator=(const TestQuicSpdyServerSession&) = delete; ~TestQuicSpdyServerSession() override { DeleteConnection(); } MOCK_METHOD(void, OnConnectionClosed, (const QuicConnectionCloseFrame& frame, ConnectionCloseSource source), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*), (override)); MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (), (override)); MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (), (override)); std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) override { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, stream_helper()); } QuicCryptoServerStreamBase::Helper* stream_helper() { return QuicServerSessionBase::stream_helper(); } }; class TestDispatcher : public QuicDispatcher { public: TestDispatcher(const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, QuicRandom* random, ConnectionIdGeneratorInterface& generator) : QuicDispatcher(config, crypto_config, version_manager, std::make_unique<MockQuicConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), std::make_unique<TestAlarmFactory>(), kQuicDefaultConnectionIdLength, generator), random_(random) { EXPECT_CALL(*this, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(generator)); } MOCK_METHOD(std::unique_ptr<QuicSession>, CreateQuicSession, (QuicConnectionId connection_id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, absl::string_view alpn, const ParsedQuicVersion& version, const ParsedClientHello& parsed_chlo, ConnectionIdGeneratorInterface& connection_id_generator), (override)); MOCK_METHOD(ConnectionIdGeneratorInterface&, ConnectionIdGenerator, (), (override)); struct TestQuicPerPacketContext : public QuicPerPacketContext { std::string custom_packet_context; }; std::unique_ptr<QuicPerPacketContext> GetPerPacketContext() const override { auto test_context = std::make_unique<TestQuicPerPacketContext>(); test_context->custom_packet_context = custom_packet_context_; return std::move(test_context); } void RestorePerPacketContext( std::unique_ptr<QuicPerPacketContext> context) override { TestQuicPerPacketContext* test_context = static_cast<TestQuicPerPacketContext*>(context.get()); custom_packet_context_ = test_context->custom_packet_context; } std::string custom_packet_context_; using QuicDispatcher::ConnectionIdGenerator; using QuicDispatcher::MaybeDispatchPacket; using QuicDispatcher::SetAllowShortInitialServerConnectionIds; using QuicDispatcher::writer; QuicRandom* random_; }; class MockServerConnection : public MockQuicConnection { public: MockServerConnection(QuicConnectionId connection_id, MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, QuicDispatcher* dispatcher) : MockQuicConnection(connection_id, helper, alarm_factory, Perspective::IS_SERVER), dispatcher_(dispatcher), active_connection_ids_({connection_id}) {} void AddNewConnectionId(QuicConnectionId id) { if (!dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(), id)) { return; } QuicConnectionPeer::SetServerConnectionId(this, id); active_connection_ids_.push_back(id); } void UnconditionallyAddNewConnectionIdForTest(QuicConnectionId id) { dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(), id); active_connection_ids_.push_back(id); } void RetireConnectionId(QuicConnectionId id) { auto it = std::find(active_connection_ids_.begin(), active_connection_ids_.end(), id); QUICHE_DCHECK(it != active_connection_ids_.end()); dispatcher_->OnConnectionIdRetired(id); active_connection_ids_.erase(it); } std::vector<QuicConnectionId> GetActiveServerConnectionIds() const override { std::vector<QuicConnectionId> result; for (const auto& cid : active_connection_ids_) { result.push_back(cid); } auto original_connection_id = GetOriginalDestinationConnectionId(); if (std::find(result.begin(), result.end(), original_connection_id) == result.end()) { result.push_back(original_connection_id); } return result; } void UnregisterOnConnectionClosed() { QUIC_LOG(ERROR) << "Unregistering " << connection_id(); dispatcher_->OnConnectionClosed(connection_id(), QUIC_NO_ERROR, "Unregistering.", ConnectionCloseSource::FROM_SELF); } private: QuicDispatcher* dispatcher_; std::vector<QuicConnectionId> active_connection_ids_; }; class QuicDispatcherTestBase : public QuicTestWithParam<ParsedQuicVersion> { public: QuicDispatcherTestBase() : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting()) {} explicit QuicDispatcherTestBase(std::unique_ptr<ProofSource> proof_source) : version_(GetParam()), version_manager_(AllSupportedVersions()), crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), server_address_(QuicIpAddress::Any4(), 5), dispatcher_(new NiceMock<TestDispatcher>( &config_, &crypto_config_, &version_manager_, mock_helper_.GetRandomGenerator(), connection_id_generator_)), time_wait_list_manager_(nullptr), session1_(nullptr), session2_(nullptr), store_(nullptr), connection_id_(1) {} void SetUp() override { dispatcher_->InitializeWithWriter(new NiceMock<MockPacketWriter>()); QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop( dispatcher_.get(), kMaxNumSessionsToCreate); } MockQuicConnection* connection1() { if (session1_ == nullptr) { return nullptr; } return reinterpret_cast<MockQuicConnection*>(session1_->connection()); } MockQuicConnection* connection2() { if (session2_ == nullptr) { return nullptr; } return reinterpret_cast<MockQuicConnection*>(session2_->connection()); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data) { ProcessPacket(peer_address, server_connection_id, has_version_flag, data, CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length) { ProcessPacket(peer_address, server_connection_id, has_version_flag, data, server_connection_id_included, packet_number_length, 1); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ProcessPacket(peer_address, server_connection_id, has_version_flag, version_, data, true, server_connection_id_included, packet_number_length, packet_number); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, ParsedQuicVersion version, const std::string& data, bool full_padding, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ProcessPacket(peer_address, server_connection_id, EmptyQuicConnectionId(), has_version_flag, version, data, full_padding, server_connection_id_included, CONNECTION_ID_ABSENT, packet_number_length, packet_number); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool has_version_flag, ParsedQuicVersion version, const std::string& data, bool full_padding, QuicConnectionIdIncluded server_connection_id_included, QuicConnectionIdIncluded client_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ParsedQuicVersionVector versions(SupportedVersions(version)); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( server_connection_id, client_connection_id, has_version_flag, false, packet_number, data, full_padding, server_connection_id_included, client_connection_id_included, packet_number_length, &versions)); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(*packet, mock_helper_.GetClock()->Now())); if (!has_version_flag || !version.AllowsVariableLengthConnectionIds() || server_connection_id.length() == 0 || server_connection_id_included == CONNECTION_ID_ABSENT) { EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)) .WillRepeatedly(Return(generated_connection_id_.has_value() ? generated_connection_id_->length() : kQuicDefaultConnectionIdLength)); } ProcessReceivedPacket(std::move(received_packet), peer_address, version, server_connection_id); } void ProcessReceivedPacket( std::unique_ptr<QuicReceivedPacket> received_packet, const QuicSocketAddress& peer_address, const ParsedQuicVersion& version, const QuicConnectionId& server_connection_id) { if (version.UsesQuicCrypto() && ChloExtractor::Extract(*received_packet, version, {}, nullptr, server_connection_id.length())) { data_connection_map_[server_connection_id].push_front( std::string(received_packet->data(), received_packet->length())); } else { data_connection_map_[server_connection_id].push_back( std::string(received_packet->data(), received_packet->length())); } dispatcher_->ProcessPacket(server_address_, peer_address, *received_packet); } void ValidatePacket(QuicConnectionId conn_id, const QuicEncryptedPacket& packet) { EXPECT_EQ(data_connection_map_[conn_id].front().length(), packet.AsStringPiece().length()); EXPECT_EQ(data_connection_map_[conn_id].front(), packet.AsStringPiece()); data_connection_map_[conn_id].pop_front(); } std::unique_ptr<QuicSession> CreateSession( TestDispatcher* dispatcher, const QuicConfig& config, QuicConnectionId connection_id, const QuicSocketAddress& , MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, TestQuicSpdyServerSession** session_ptr) { MockServerConnection* connection = new MockServerConnection( connection_id, helper, alarm_factory, dispatcher); connection->SetQuicPacketWriter(dispatcher->writer(), false); auto session = std::make_unique<TestQuicSpdyServerSession>( config, connection, crypto_config, compressed_certs_cache); *session_ptr = session.get(); connection->set_visitor(session.get()); ON_CALL(*connection, CloseConnection(_, _, _)) .WillByDefault(WithoutArgs(Invoke( connection, &MockServerConnection::UnregisterOnConnectionClosed))); return session; } void CreateTimeWaitListManager() { time_wait_list_manager_ = new MockTimeWaitListManager( QuicDispatcherPeer::GetWriter(dispatcher_.get()), dispatcher_.get(), mock_helper_.GetClock(), &mock_alarm_factory_); QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(), time_wait_list_manager_); } std::string SerializeCHLO() { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); client_hello.SetStringPiece(kALPN, ExpectedAlpn()); return std::string(client_hello.GetSerialized().AsStringPiece()); } void ProcessUndecryptableEarlyPacket( const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessUndecryptableEarlyPacket(version_, peer_address, server_connection_id); } void ProcessUndecryptableEarlyPacket( const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { std::unique_ptr<QuicEncryptedPacket> encrypted_packet = GetUndecryptableEarlyPacket(version, server_connection_id); std::unique_ptr<QuicReceivedPacket> received_packet(ConstructReceivedPacket( *encrypted_packet, mock_helper_.GetClock()->Now())); ProcessReceivedPacket(std::move(received_packet), peer_address, version, server_connection_id); } void ProcessFirstFlight(const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version_, peer_address, server_connection_id); } void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version, peer_address, server_connection_id, EmptyQuicConnectionId()); } void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id) { ProcessFirstFlight(version, peer_address, server_connection_id, client_connection_id, TestClientCryptoConfig()); } void ProcessFirstFlight( const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id, std::unique_ptr<QuicCryptoClientConfig> client_crypto_config) { if (expect_generator_is_called_) { if (version.AllowsVariableLengthConnectionIds()) { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(server_connection_id, version)) .WillOnce(Return(generated_connection_id_)); } else { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(server_connection_id, version)) .WillOnce(Return(std::nullopt)); } } std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version, DefaultQuicConfig(), server_connection_id, client_connection_id, std::move(client_crypto_config)); for (auto&& packet : packets) { ProcessReceivedPacket(std::move(packet), peer_address, version, server_connection_id); } } std::unique_ptr<QuicCryptoClientConfig> TestClientCryptoConfig() { auto client_crypto_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting()); if (address_token_.has_value()) { client_crypto_config->LookupOrCreate(TestServerId()) ->set_source_address_token(*address_token_); } return client_crypto_config; } void SetAddressToken(std::string address_token) { address_token_ = std::move(address_token); } std::string ExpectedAlpnForVersion(ParsedQuicVersion version) { return AlpnForVersion(version); } std::string ExpectedAlpn() { return ExpectedAlpnForVersion(version_); } auto MatchParsedClientHello() { if (version_.UsesQuicCrypto()) { return AllOf( Field(&ParsedClientHello::alpns, ElementsAreArray({ExpectedAlpn()})), Field(&ParsedClientHello::sni, Eq(TestHostname())), Field(&ParsedClientHello::supported_groups, IsEmpty())); } return AllOf( Field(&ParsedClientHello::alpns, ElementsAreArray({ExpectedAlpn()})), Field(&ParsedClientHello::sni, Eq(TestHostname())), Field(&ParsedClientHello::supported_groups, Not(IsEmpty()))); } void MarkSession1Deleted() { session1_ = nullptr; } void VerifyVersionSupported(ParsedQuicVersion version) { expect_generator_is_called_ = true; QuicConnectionId connection_id = TestConnectionId(++connection_id_); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address, Eq(ExpectedAlpnForVersion(version)), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, connection_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, connection_id](const QuicEncryptedPacket& packet) { ValidatePacket(connection_id, packet); }))); ProcessFirstFlight(version, client_address, connection_id); } void VerifyVersionNotSupported(ParsedQuicVersion version) { QuicConnectionId connection_id = TestConnectionId(++connection_id_); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address, _, _, _, _)) .Times(0); expect_generator_is_called_ = false; ProcessFirstFlight(version, client_address, connection_id); } void TestTlsMultiPacketClientHello(bool add_reordering, bool long_connection_id); void TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id); TestAlarmFactory::TestAlarm* GetClearResetAddressesAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicDispatcherPeer::GetClearResetAddressesAlarm(dispatcher_.get())); } ParsedQuicVersion version_; MockQuicConnectionHelper mock_helper_; MockAlarmFactory mock_alarm_factory_; QuicConfig config_; QuicVersionManager version_manager_; QuicCryptoServerConfig crypto_config_; QuicSocketAddress server_address_; bool expect_generator_is_called_ = true; std::optional<QuicConnectionId> generated_connection_id_; MockConnectionIdGenerator connection_id_generator_; std::unique_ptr<NiceMock<TestDispatcher>> dispatcher_; MockTimeWaitListManager* time_wait_list_manager_; TestQuicSpdyServerSession* session1_; TestQuicSpdyServerSession* session2_; std::map<QuicConnectionId, std::list<std::string>> data_connection_map_; QuicBufferedPacketStore* store_; uint64_t connection_id_; std::optional<std::string> address_token_; }; class QuicDispatcherTestAllVersions : public QuicDispatcherTestBase {}; class QuicDispatcherTestOneVersion : public QuicDispatcherTestBase {}; INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsAllVersions, QuicDispatcherTestAllVersions, ::testing::ValuesIn(CurrentSupportedVersions()), ::testing::PrintToStringParamName()); INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsOneVersion, QuicDispatcherTestOneVersion, ::testing::Values(CurrentSupportedVersions().front()), ::testing::PrintToStringParamName()); TEST_P(QuicDispatcherTestAllVersions, TlsClientHelloCreatesSession) { if (version_.UsesQuicCrypto()) { return; } SetAddressToken("hsdifghdsaifnasdpfjdsk"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestAllVersions, TlsClientHelloCreatesSessionWithCorrectConnectionIdGenerator) { if (version_.UsesQuicCrypto()) { return; } SetAddressToken("hsdifghdsaifnasdpfjdsk"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); MockConnectionIdGenerator mock_connection_id_generator; EXPECT_CALL(*dispatcher_, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(mock_connection_id_generator)); ConnectionIdGeneratorInterface& expected_generator = mock_connection_id_generator; EXPECT_CALL(mock_connection_id_generator, MaybeReplaceConnectionId(TestConnectionId(1), version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), Ref(expected_generator))) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); expect_generator_is_called_ = false; ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestAllVersions, VariableServerConnectionIdLength) { QuicConnectionId old_id = TestConnectionId(1); if (version_.HasIetfQuicFrames()) { generated_connection_id_ = QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}); } QuicConnectionId new_id = generated_connection_id_.has_value() ? *generated_connection_id_ : old_id; QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(new_id, _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, new_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, old_id); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1); ProcessPacket(client_address, new_id, false, "foo"); } void QuicDispatcherTestBase::TestTlsMultiPacketClientHello( bool add_reordering, bool long_connection_id) { if (!version_.UsesTls()) { return; } SetAddressToken("857293462398"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId original_connection_id, new_connection_id; if (long_connection_id) { original_connection_id = TestConnectionIdNineBytesLong(1); new_connection_id = kReturnConnectionId; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(original_connection_id, version_)) .WillOnce(Return(new_connection_id)); } else { original_connection_id = TestConnectionId(); new_connection_id = original_connection_id; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(original_connection_id, version_)) .WillOnce(Return(std::nullopt)); } QuicConfig client_config = DefaultQuicConfig(); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); client_config.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_, client_config, original_connection_id, EmptyQuicConnectionId(), TestClientCryptoConfig()); ASSERT_EQ(packets.size(), 2u); if (add_reordering) { std::swap(packets[0], packets[1]); } ProcessReceivedPacket(std::move(packets[0]), client_address, version_, original_connection_id); EXPECT_EQ(dispatcher_->NumSessions(), 0u) << "No session should be created before the rest of the CHLO arrives."; EXPECT_CALL( *disp
249
cpp
google/quiche
deterministic_connection_id_generator
quiche/quic/core/deterministic_connection_id_generator.cc
quiche/quic/core/deterministic_connection_id_generator_test.cc
#ifndef QUICHE_QUIC_CORE_CONNECTION_ID_GENERATOR_DETERMINISTIC_H_ #define QUICHE_QUIC_CORE_CONNECTION_ID_GENERATOR_DETERMINISTIC_H_ #include "quiche/quic/core/connection_id_generator.h" namespace quic { class QUICHE_EXPORT DeterministicConnectionIdGenerator : public ConnectionIdGeneratorInterface { public: DeterministicConnectionIdGenerator(uint8_t expected_connection_id_length); std::optional<QuicConnectionId> GenerateNextConnectionId( const QuicConnectionId& original) override; std::optional<QuicConnectionId> MaybeReplaceConnectionId( const QuicConnectionId& original, const ParsedQuicVersion& version) override; uint8_t ConnectionIdLength(uint8_t ) const override { return expected_connection_id_length_; } private: const uint8_t expected_connection_id_length_; }; } #endif #include "quiche/quic/core/deterministic_connection_id_generator.h" #include <optional> #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { DeterministicConnectionIdGenerator::DeterministicConnectionIdGenerator( uint8_t expected_connection_id_length) : expected_connection_id_length_(expected_connection_id_length) { if (expected_connection_id_length_ > kQuicMaxConnectionIdWithLengthPrefixLength) { QUIC_BUG(quic_bug_465151159_01) << "Issuing connection IDs longer than allowed in RFC9000"; } } std::optional<QuicConnectionId> DeterministicConnectionIdGenerator::GenerateNextConnectionId( const QuicConnectionId& original) { if (expected_connection_id_length_ == 0) { return EmptyQuicConnectionId(); } const uint64_t connection_id_hash64 = QuicUtils::FNV1a_64_Hash( absl::string_view(original.data(), original.length())); if (expected_connection_id_length_ <= sizeof(uint64_t)) { return QuicConnectionId( reinterpret_cast<const char*>(&connection_id_hash64), expected_connection_id_length_); } char new_connection_id_data[255] = {}; const absl::uint128 connection_id_hash128 = QuicUtils::FNV1a_128_Hash( absl::string_view(original.data(), original.length())); static_assert(sizeof(connection_id_hash64) + sizeof(connection_id_hash128) <= sizeof(new_connection_id_data), "bad size"); memcpy(new_connection_id_data, &connection_id_hash64, sizeof(connection_id_hash64)); memcpy(new_connection_id_data + sizeof(connection_id_hash64), &connection_id_hash128, sizeof(connection_id_hash128)); return QuicConnectionId(new_connection_id_data, expected_connection_id_length_); } std::optional<QuicConnectionId> DeterministicConnectionIdGenerator::MaybeReplaceConnectionId( const QuicConnectionId& original, const ParsedQuicVersion& version) { if (original.length() == expected_connection_id_length_) { return std::optional<QuicConnectionId>(); } QUICHE_DCHECK(version.AllowsVariableLengthConnectionIds()); std::optional<QuicConnectionId> new_connection_id = GenerateNextConnectionId(original); if (!new_connection_id.has_value()) { QUIC_BUG(unset_next_connection_id); return std::nullopt; } QUICHE_DCHECK_EQ( *new_connection_id, static_cast<QuicConnectionId>(*GenerateNextConnectionId(original))); QUICHE_DCHECK_EQ(expected_connection_id_length_, new_connection_id->length()); QUIC_DLOG(INFO) << "Replacing incoming connection ID " << original << " with " << *new_connection_id; return new_connection_id; } }
#include "quiche/quic/core/deterministic_connection_id_generator.h" #include <optional> #include <ostream> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { struct TestParams { TestParams(int connection_id_length) : connection_id_length_(connection_id_length) {} TestParams() : TestParams(kQuicDefaultConnectionIdLength) {} friend std::ostream& operator<<(std::ostream& os, const TestParams& p) { os << "{ connection ID length: " << p.connection_id_length_ << " }"; return os; } int connection_id_length_; }; std::vector<struct TestParams> GetTestParams() { std::vector<struct TestParams> params; std::vector<int> connection_id_lengths{7, 8, 9, 16, 20}; for (int connection_id_length : connection_id_lengths) { params.push_back(TestParams(connection_id_length)); } return params; } class DeterministicConnectionIdGeneratorTest : public QuicTestWithParam<TestParams> { public: DeterministicConnectionIdGeneratorTest() : connection_id_length_(GetParam().connection_id_length_), generator_(DeterministicConnectionIdGenerator(connection_id_length_)), version_(ParsedQuicVersion::RFCv1()) {} protected: int connection_id_length_; DeterministicConnectionIdGenerator generator_; ParsedQuicVersion version_; }; INSTANTIATE_TEST_SUITE_P(DeterministicConnectionIdGeneratorTests, DeterministicConnectionIdGeneratorTest, ::testing::ValuesIn(GetTestParams())); TEST_P(DeterministicConnectionIdGeneratorTest, NextConnectionIdIsDeterministic) { QuicConnectionId connection_id64a = TestConnectionId(33); QuicConnectionId connection_id64b = TestConnectionId(33); EXPECT_EQ(connection_id64a, connection_id64b); EXPECT_EQ(*generator_.GenerateNextConnectionId(connection_id64a), *generator_.GenerateNextConnectionId(connection_id64b)); QuicConnectionId connection_id72a = TestConnectionIdNineBytesLong(42); QuicConnectionId connection_id72b = TestConnectionIdNineBytesLong(42); EXPECT_EQ(connection_id72a, connection_id72b); EXPECT_EQ(*generator_.GenerateNextConnectionId(connection_id72a), *generator_.GenerateNextConnectionId(connection_id72b)); } TEST_P(DeterministicConnectionIdGeneratorTest, NextConnectionIdLengthIsCorrect) { const char connection_id_bytes[255] = {}; for (uint8_t i = 0; i < sizeof(connection_id_bytes) - 1; ++i) { QuicConnectionId connection_id(connection_id_bytes, i); std::optional<QuicConnectionId> replacement_connection_id = generator_.GenerateNextConnectionId(connection_id); ASSERT_TRUE(replacement_connection_id.has_value()); EXPECT_EQ(connection_id_length_, replacement_connection_id->length()); } } TEST_P(DeterministicConnectionIdGeneratorTest, NextConnectionIdHasEntropy) { for (uint64_t i = 0; i < 256; ++i) { QuicConnectionId connection_id_i = TestConnectionId(i); std::optional<QuicConnectionId> new_i = generator_.GenerateNextConnectionId(connection_id_i); ASSERT_TRUE(new_i.has_value()); EXPECT_NE(connection_id_i, *new_i); for (uint64_t j = i + 1; j <= 256; ++j) { QuicConnectionId connection_id_j = TestConnectionId(j); EXPECT_NE(connection_id_i, connection_id_j); std::optional<QuicConnectionId> new_j = generator_.GenerateNextConnectionId(connection_id_j); ASSERT_TRUE(new_j.has_value()); EXPECT_NE(*new_i, *new_j); } } } TEST_P(DeterministicConnectionIdGeneratorTest, OnlyReplaceConnectionIdWithWrongLength) { const char connection_id_input[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14}; for (int i = 0; i < kQuicMaxConnectionIdWithLengthPrefixLength; i++) { QuicConnectionId input = QuicConnectionId(connection_id_input, i); std::optional<QuicConnectionId> output = generator_.MaybeReplaceConnectionId(input, version_); if (i == connection_id_length_) { EXPECT_FALSE(output.has_value()); } else { ASSERT_TRUE(output.has_value()); EXPECT_EQ(*output, generator_.GenerateNextConnectionId(input)); } } } TEST_P(DeterministicConnectionIdGeneratorTest, ReturnLength) { EXPECT_EQ(generator_.ConnectionIdLength(0x01), connection_id_length_); } } } }
250
cpp
google/quiche
quic_time_wait_list_manager
quiche/quic/core/quic_time_wait_list_manager.cc
quiche/quic/core/quic_time_wait_list_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_TIME_WAIT_LIST_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_TIME_WAIT_LIST_MANAGER_H_ #include <cstddef> #include <memory> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { namespace test { class QuicDispatcherPeer; class QuicTimeWaitListManagerPeer; } struct QUICHE_EXPORT TimeWaitConnectionInfo { TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids); TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids, QuicTime::Delta srtt); TimeWaitConnectionInfo(const TimeWaitConnectionInfo& other) = delete; TimeWaitConnectionInfo(TimeWaitConnectionInfo&& other) = default; ~TimeWaitConnectionInfo() = default; bool ietf_quic; std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; std::vector<QuicConnectionId> active_connection_ids; QuicTime::Delta srtt; }; class QUICHE_EXPORT QuicTimeWaitListManager : public QuicBlockedWriterInterface { public: enum TimeWaitAction : uint8_t { SEND_TERMINATION_PACKETS, SEND_CONNECTION_CLOSE_PACKETS, SEND_STATELESS_RESET, DO_NOTHING, }; class QUICHE_EXPORT Visitor : public QuicSession::Visitor { public: virtual void OnConnectionAddedToTimeWaitList( QuicConnectionId connection_id) = 0; void OnPathDegrading() override {} }; QuicTimeWaitListManager(QuicPacketWriter* writer, Visitor* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory); QuicTimeWaitListManager(const QuicTimeWaitListManager&) = delete; QuicTimeWaitListManager& operator=(const QuicTimeWaitListManager&) = delete; ~QuicTimeWaitListManager() override; virtual void AddConnectionIdToTimeWait(TimeWaitAction action, TimeWaitConnectionInfo info); bool IsConnectionIdInTimeWait(QuicConnectionId connection_id) const; virtual void ProcessPacket( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, PacketHeaderFormat header_format, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context); void OnBlockedWriterCanWrite() override; bool IsWriterBlocked() const override { return writer_ != nullptr && writer_->IsWriteBlocked(); } void CleanUpOldConnectionIds(); void TrimTimeWaitListIfNeeded(); size_t num_connections() const { return connection_id_map_.size(); } virtual void SendVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& supported_versions, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, std::unique_ptr<QuicPerPacketContext> packet_context); virtual void SendPublicReset( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, bool ietf_quic, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context); virtual void SendPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicEncryptedPacket& packet); QuicPacketWriter* writer() { return writer_; } protected: virtual std::unique_ptr<QuicEncryptedPacket> BuildPublicReset( const QuicPublicResetPacket& packet); virtual void GetEndpointId(std::string* ) {} virtual StatelessResetToken GetStatelessResetToken( QuicConnectionId connection_id) const; class QUICHE_EXPORT QueuedPacket { public: QueuedPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, std::unique_ptr<QuicEncryptedPacket> packet) : self_address_(self_address), peer_address_(peer_address), packet_(std::move(packet)) {} QueuedPacket(const QueuedPacket&) = delete; QueuedPacket& operator=(const QueuedPacket&) = delete; const QuicSocketAddress& self_address() const { return self_address_; } const QuicSocketAddress& peer_address() const { return peer_address_; } QuicEncryptedPacket* packet() { return packet_.get(); } private: const QuicSocketAddress self_address_; const QuicSocketAddress peer_address_; std::unique_ptr<QuicEncryptedPacket> packet_; }; virtual bool SendOrQueuePacket(std::unique_ptr<QueuedPacket> packet, const QuicPerPacketContext* packet_context); const quiche::QuicheCircularDeque<std::unique_ptr<QueuedPacket>>& pending_packets_queue() const { return pending_packets_queue_; } private: friend class test::QuicDispatcherPeer; friend class test::QuicTimeWaitListManagerPeer; bool ShouldSendResponse(int received_packet_count); bool WriteToWire(QueuedPacket* packet); void SetConnectionIdCleanUpAlarm(); bool MaybeExpireOldestConnection(QuicTime expiration_time); virtual void OnPacketReceivedForKnownConnection( int , QuicTime::Delta , QuicTime::Delta ) const {} std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length); struct QUICHE_EXPORT ConnectionIdData { ConnectionIdData(int num_packets, QuicTime time_added, TimeWaitAction action, TimeWaitConnectionInfo info); ConnectionIdData(const ConnectionIdData& other) = delete; ConnectionIdData(ConnectionIdData&& other); ~ConnectionIdData(); int num_packets; QuicTime time_added; TimeWaitAction action; TimeWaitConnectionInfo info; }; using ConnectionIdMap = quiche::QuicheLinkedHashMap<QuicConnectionId, ConnectionIdData, QuicConnectionIdHash>; ConnectionIdMap connection_id_map_; absl::flat_hash_map<QuicConnectionId, QuicConnectionId, QuicConnectionIdHash> indirect_connection_id_map_; ConnectionIdMap::iterator FindConnectionIdDataInMap( const QuicConnectionId& connection_id); void AddConnectionIdDataToMap(const QuicConnectionId& canonical_connection_id, int num_packets, TimeWaitAction action, TimeWaitConnectionInfo info); void RemoveConnectionDataFromMap(ConnectionIdMap::iterator it); quiche::QuicheCircularDeque<std::unique_ptr<QueuedPacket>> pending_packets_queue_; const QuicTime::Delta time_wait_period_; std::unique_ptr<QuicAlarm> connection_id_clean_up_alarm_; const QuicClock* clock_; QuicPacketWriter* writer_; Visitor* visitor_; }; } #endif #include "quiche/quic/core/quic_time_wait_list_manager.h" #include <errno.h> #include <memory> #include <ostream> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/quiche_text_utils.h" namespace quic { class ConnectionIdCleanUpAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ConnectionIdCleanUpAlarm( QuicTimeWaitListManager* time_wait_list_manager) : time_wait_list_manager_(time_wait_list_manager) {} ConnectionIdCleanUpAlarm(const ConnectionIdCleanUpAlarm&) = delete; ConnectionIdCleanUpAlarm& operator=(const ConnectionIdCleanUpAlarm&) = delete; void OnAlarm() override { time_wait_list_manager_->CleanUpOldConnectionIds(); } private: QuicTimeWaitListManager* time_wait_list_manager_; }; TimeWaitConnectionInfo::TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids) : TimeWaitConnectionInfo(ietf_quic, termination_packets, std::move(active_connection_ids), QuicTime::Delta::Zero()) {} TimeWaitConnectionInfo::TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids, QuicTime::Delta srtt) : ietf_quic(ietf_quic), active_connection_ids(std::move(active_connection_ids)), srtt(srtt) { if (termination_packets != nullptr) { this->termination_packets.swap(*termination_packets); } } QuicTimeWaitListManager::QuicTimeWaitListManager( QuicPacketWriter* writer, Visitor* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory) : time_wait_period_(QuicTime::Delta::FromSeconds( GetQuicFlag(quic_time_wait_list_seconds))), connection_id_clean_up_alarm_( alarm_factory->CreateAlarm(new ConnectionIdCleanUpAlarm(this))), clock_(clock), writer_(writer), visitor_(visitor) { SetConnectionIdCleanUpAlarm(); } QuicTimeWaitListManager::~QuicTimeWaitListManager() { connection_id_clean_up_alarm_->Cancel(); } QuicTimeWaitListManager::ConnectionIdMap::iterator QuicTimeWaitListManager::FindConnectionIdDataInMap( const QuicConnectionId& connection_id) { auto it = indirect_connection_id_map_.find(connection_id); if (it == indirect_connection_id_map_.end()) { return connection_id_map_.end(); } return connection_id_map_.find(it->second); } void QuicTimeWaitListManager::AddConnectionIdDataToMap( const QuicConnectionId& canonical_connection_id, int num_packets, TimeWaitAction action, TimeWaitConnectionInfo info) { for (const auto& cid : info.active_connection_ids) { indirect_connection_id_map_[cid] = canonical_connection_id; } ConnectionIdData data(num_packets, clock_->ApproximateNow(), action, std::move(info)); connection_id_map_.emplace( std::make_pair(canonical_connection_id, std::move(data))); } void QuicTimeWaitListManager::RemoveConnectionDataFromMap( ConnectionIdMap::iterator it) { for (const auto& cid : it->second.info.active_connection_ids) { indirect_connection_id_map_.erase(cid); } connection_id_map_.erase(it); } void QuicTimeWaitListManager::AddConnectionIdToTimeWait( TimeWaitAction action, TimeWaitConnectionInfo info) { QUICHE_DCHECK(!info.active_connection_ids.empty()); const QuicConnectionId& canonical_connection_id = info.active_connection_ids.front(); QUICHE_DCHECK(action != SEND_TERMINATION_PACKETS || !info.termination_packets.empty()); QUICHE_DCHECK(action != DO_NOTHING || info.ietf_quic); int num_packets = 0; auto it = FindConnectionIdDataInMap(canonical_connection_id); const bool new_connection_id = it == connection_id_map_.end(); if (!new_connection_id) { num_packets = it->second.num_packets; RemoveConnectionDataFromMap(it); } TrimTimeWaitListIfNeeded(); int64_t max_connections = GetQuicFlag(quic_time_wait_list_max_connections); QUICHE_DCHECK(connection_id_map_.empty() || num_connections() < static_cast<size_t>(max_connections)); if (new_connection_id) { for (const auto& cid : info.active_connection_ids) { visitor_->OnConnectionAddedToTimeWaitList(cid); } } AddConnectionIdDataToMap(canonical_connection_id, num_packets, action, std::move(info)); } bool QuicTimeWaitListManager::IsConnectionIdInTimeWait( QuicConnectionId connection_id) const { return indirect_connection_id_map_.contains(connection_id); } void QuicTimeWaitListManager::OnBlockedWriterCanWrite() { writer_->SetWritable(); while (!pending_packets_queue_.empty()) { QueuedPacket* queued_packet = pending_packets_queue_.front().get(); if (!WriteToWire(queued_packet)) { return; } pending_packets_queue_.pop_front(); } } void QuicTimeWaitListManager::ProcessPacket( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, PacketHeaderFormat header_format, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context) { QUICHE_DCHECK(IsConnectionIdInTimeWait(connection_id)); auto it = FindConnectionIdDataInMap(connection_id); QUICHE_DCHECK(it != connection_id_map_.end()); ConnectionIdData* connection_data = &it->second; ++(connection_data->num_packets); const QuicTime now = clock_->ApproximateNow(); QuicTime::Delta delta = QuicTime::Delta::Zero(); if (now > connection_data->time_added) { delta = now - connection_data->time_added; } OnPacketReceivedForKnownConnection(connection_data->num_packets, delta, connection_data->info.srtt); if (!ShouldSendResponse(connection_data->num_packets)) { QUIC_DLOG(INFO) << "Processing " << connection_id << " in time wait state: " << "throttled"; return; } QUIC_DLOG(INFO) << "Processing " << connection_id << " in time wait state: " << "header format=" << header_format << " ietf=" << connection_data->info.ietf_quic << ", action=" << connection_data->action << ", number termination packets=" << connection_data->info.termination_packets.size(); switch (connection_data->action) { case SEND_TERMINATION_PACKETS: if (connection_data->info.termination_packets.empty()) { QUIC_BUG(quic_bug_10608_1) << "There are no termination packets."; return; } switch (header_format) { case IETF_QUIC_LONG_HEADER_PACKET: if (!connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_long_header_packet_for_gquic); } break; case IETF_QUIC_SHORT_HEADER_PACKET: if (!connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_short_header_packet_for_gquic); } SendPublicReset(self_address, peer_address, connection_id, connection_data->info.ietf_quic, received_packet_length, std::move(packet_context)); return; case GOOGLE_QUIC_PACKET: if (connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_gquic_packet_for_ietf_quic); } break; } for (const auto& packet : connection_data->info.termination_packets) { SendOrQueuePacket(std::make_unique<QueuedPacket>( self_address, peer_address, packet->Clone()), packet_context.get()); } return; case SEND_CONNECTION_CLOSE_PACKETS: if (connection_data->info.termination_packets.empty()) { QUIC_BUG(quic_bug_10608_2) << "There are no termination packets."; return; } for (const auto& packet : connection_data->info.termination_packets) { SendOrQueuePacket(std::make_unique<QueuedPacket>( self_address, peer_address, packet->Clone()), packet_context.get()); } return; case SEND_STATELESS_RESET: if (header_format == IETF_QUIC_LONG_HEADER_PACKET) { QUIC_CODE_COUNT(quic_stateless_reset_long_header_packet); } SendPublicReset(self_address, peer_address, connection_id, connection_data->info.ietf_quic, received_packet_length, std::move(packet_context)); return; case DO_NOTHING: QUIC_CODE_COUNT(quic_time_wait_list_do_nothing); QUICHE_DCHECK(connection_data->info.ietf_quic); } } void QuicTimeWaitListManager::SendVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& supported_versions, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, std::unique_ptr<QuicPerPacketContext> packet_context) { std::unique_ptr<QuicEncryptedPacket> version_packet = QuicFramer::BuildVersionNegotiationPacket( server_connection_id, client_connection_id, ietf_quic, use_length_prefix, supported_versions); QUIC_DVLOG(2) << "Dispatcher sending version negotiation packet {" << ParsedQuicVersionVectorToString(supported_versions) << "}, " << (ietf_quic ? "" : "!") << "ietf_quic, " << (use_length_prefix ? "" : "!") << "use_length_prefix:" << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( version_packet->data(), version_packet->length())); SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, std::move(version_packet)), packet_context.get()); } bool QuicTimeWaitListManager::ShouldSendResponse(int received_packet_count) { return (received_packet_count & (received_packet_count - 1)) == 0; } void QuicTimeWaitListManager::SendPublicReset( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, bool ietf_quic, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context) { if (ietf_quic) { std::unique_ptr<QuicEncryptedPacket> ietf_reset_packet = BuildIetfStatelessResetPacket(connection_id, received_packet_length); if (ietf_reset_packet == nullptr) { return; } QUIC_DVLOG(2) << "Dispatcher sending IETF reset packet for " << connection_id << std::endl << quiche::QuicheTextUtils::HexDump( absl::string_view(ietf_reset_packet->data(), ietf_reset_packet->length())); SendOrQueuePacket( std::make_unique<QueuedPacket>(self_address, peer_address, std::move(ietf_reset_packet)), packet_context.get()); return; } QuicPublicResetPacket packet; packet.connection_id = connection_id; packet.nonce_proof = 1010101; packet.client_address = peer_address; GetEndpointId(&packet.endpoint_id); std::unique_ptr<QuicEncryptedPacket> reset_packet = BuildPublicReset(packet); QUIC_DVLOG(2) << "Dispatcher sending reset packet for " << connection_id << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( reset_packet->data(), reset_packet->length())); SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, std::move(reset_packet)), packet_context.get()); } void QuicTimeWaitListManager::SendPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicEncryptedPacket& packet) { SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, packet.Clone()), nullptr); } std::unique_ptr<QuicEncryptedPacket> QuicTimeWaitListManager::BuildPublicReset( const QuicPublicResetPacket& packet) { return QuicFramer::BuildPublicResetPacket(packet); } std::unique_ptr<QuicEncryptedPacket> QuicTimeWaitListManager::BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length) { return QuicFramer::BuildIetfStatelessResetPacket( connection_id, received_packet_length, GetStatelessResetToken(connection_id)); } bool QuicTimeWaitListManager::SendOrQueuePacket( std::unique_ptr<QueuedPacket> packet, const QuicPerPacketContext* ) { if (packet == nullptr) { QUIC_LOG(ERROR) << "Tried to send or queue a null packet"; return true; } if (pending_packets_queue_.size() >= GetQuicFlag(quic_time_wait_list_max_pending_packets)) { QUIC_CODE_COUNT(quic_too_many_pending_packets_in_time_wait); return true; } if (WriteToWire(packet.get())) { return true; } pending_packets_queue_.push_back(std::move(packet)); return false; } bool QuicTimeWaitListManager::WriteToWire(QueuedPacket* queued_packet) { if (writer_->IsWriteBlocked()) { visitor_->OnWriteBlocked(this); return false; } WriteResult result = writer_->WritePacket( queued_packet->packet()->data(), queued_packet->packet()->length(), queued_packet->self_address().host(), queued_packet->peer_address(), nullptr, QuicPacketWriterParams()); if (writer_->IsBatchMode() && result.status == WRITE_STATUS_OK && result.bytes_written == 0) { result = writer_->Flush(); } if (IsWriteBlockedStatus(result.status)) { QUICHE_DCHECK(writer_->IsWriteBlocked()); visitor_->OnWriteBlocked(this); return result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED; } else if (IsWriteError(result.status)) { QUIC_LOG_FIRST_N(WARNING, 1) << "Received unknown error while sending termination packet to " << queued_packet->peer_address().ToString() << ": " << strerror(result.error_code); } return true; } void QuicTimeWaitListManager::SetConnectionIdCleanUpAlarm() { QuicTime::Delta next_alarm_interval = QuicTime::Delta::Zero(); if (!connection_id_map_.empty()) { QuicTime oldest_connection_id = connection_id_map_.begin()->second.time_added; QuicTime now = clock_->ApproximateNow(); if (now - oldest_connection_id < time_wait_period_) { next_alarm_interval = oldest_connection_id + time_wait_period_ - now; } else { QUIC_LOG(ERROR) << "ConnectionId lingered for longer than time_wait_period_"; } } else { next_alarm_interval = time_wait_period_; } connection_id_clean_up_alarm_->Update( clock_->ApproximateNow() + next_alarm_interval, QuicTime::Delta::Zero()); } bool QuicTimeWaitListManager::MaybeExpireOldestConnection( QuicTime expiration_time) { if (connection_id_map_.empty()) { return false; } auto it = connection_id_map_.begin(); QuicTime oldest_connection_id_time = it->second.time_added; if (oldest_connection_id_time > expiration_time) { return false; } QUIC_DLOG(INFO) << "Connection " << it->first << " expired from time wait list"; RemoveConnectionDataFromMap(it); if (expiration_time == QuicTime::Infinite()) { QUIC_CODE_COUNT(quic_time_wait_list_trim_full); } else { QUIC_CODE_COUNT(quic_time_wait_list_expire_connections); } return true; } void QuicTimeWaitListManager::CleanUpOldConnectionIds() { QuicTime now = clock_->ApproximateNow(); QuicTime expiration = now - time_wait_period_; while (MaybeExpireOldestConnection(expiration)) {
#include "quiche/quic/core/quic_time_wait_list_manager.h" #include <cerrno> #include <memory> #include <ostream> #include <tuple> #include <utility> #include <vector> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/quic_time_wait_list_manager_peer.h" using testing::_; using testing::Args; using testing::Assign; using testing::DoAll; using testing::Matcher; using testing::NiceMock; using testing::Return; using testing::ReturnPointee; using testing::StrictMock; using testing::Truly; namespace quic { namespace test { namespace { const size_t kTestPacketSize = 100; class FramerVisitorCapturingPublicReset : public NoOpFramerVisitor { public: FramerVisitorCapturingPublicReset(QuicConnectionId connection_id) : connection_id_(connection_id) {} ~FramerVisitorCapturingPublicReset() override = default; bool IsValidStatelessResetToken( const StatelessResetToken& token) const override { return token == QuicUtils::GenerateStatelessResetToken(connection_id_); } void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) override { stateless_reset_packet_ = packet; } const QuicIetfStatelessResetPacket stateless_reset_packet() { return stateless_reset_packet_; } private: QuicIetfStatelessResetPacket stateless_reset_packet_; QuicConnectionId connection_id_; }; class MockAlarmFactory; class MockAlarm : public QuicAlarm { public: explicit MockAlarm(QuicArenaScopedPtr<Delegate> delegate, int alarm_index, MockAlarmFactory* factory) : QuicAlarm(std::move(delegate)), alarm_index_(alarm_index), factory_(factory) {} virtual ~MockAlarm() {} void SetImpl() override; void CancelImpl() override; private: int alarm_index_; MockAlarmFactory* factory_; }; class MockAlarmFactory : public QuicAlarmFactory { public: ~MockAlarmFactory() override {} QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override { return new MockAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate), alarm_index_++, this); } QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override { if (arena != nullptr) { return arena->New<MockAlarm>(std::move(delegate), alarm_index_++, this); } return QuicArenaScopedPtr<MockAlarm>( new MockAlarm(std::move(delegate), alarm_index_++, this)); } MOCK_METHOD(void, OnAlarmSet, (int, QuicTime), ()); MOCK_METHOD(void, OnAlarmCancelled, (int), ()); private: int alarm_index_ = 0; }; void MockAlarm::SetImpl() { factory_->OnAlarmSet(alarm_index_, deadline()); } void MockAlarm::CancelImpl() { factory_->OnAlarmCancelled(alarm_index_); } class QuicTimeWaitListManagerTest : public QuicTest { protected: QuicTimeWaitListManagerTest() : time_wait_list_manager_(&writer_, &visitor_, &clock_, &alarm_factory_), connection_id_(TestConnectionId(45)), peer_address_(TestPeerIPAddress(), kTestPort), writer_is_blocked_(false) {} ~QuicTimeWaitListManagerTest() override = default; void SetUp() override { EXPECT_CALL(writer_, IsWriteBlocked()) .WillRepeatedly(ReturnPointee(&writer_is_blocked_)); } void AddConnectionId(QuicConnectionId connection_id, QuicTimeWaitListManager::TimeWaitAction action) { AddConnectionId(connection_id, action, nullptr); } void AddStatelessConnectionId(QuicConnectionId connection_id) { std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back(std::unique_ptr<QuicEncryptedPacket>( new QuicEncryptedPacket(nullptr, 0, false))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(false, &termination_packets, {connection_id})); } void AddConnectionId( QuicConnectionId connection_id, QuicTimeWaitListManager::TimeWaitAction action, std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets) { time_wait_list_manager_.AddConnectionIdToTimeWait( action, TimeWaitConnectionInfo(true, packets, {connection_id})); } bool IsConnectionIdInTimeWait(QuicConnectionId connection_id) { return time_wait_list_manager_.IsConnectionIdInTimeWait(connection_id); } void ProcessPacket(QuicConnectionId connection_id) { time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id, GOOGLE_QUIC_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, uint64_t packet_number) { return quic::test::ConstructEncryptedPacket(destination_connection_id, source_connection_id, false, false, packet_number, "data"); } MockClock clock_; MockAlarmFactory alarm_factory_; NiceMock<MockPacketWriter> writer_; StrictMock<MockQuicSessionVisitor> visitor_; QuicTimeWaitListManager time_wait_list_manager_; QuicConnectionId connection_id_; QuicSocketAddress self_address_; QuicSocketAddress peer_address_; bool writer_is_blocked_; }; bool ValidPublicResetPacketPredicate( QuicConnectionId expected_connection_id, const std::tuple<const char*, int>& packet_buffer) { FramerVisitorCapturingPublicReset visitor(expected_connection_id); QuicFramer framer(AllSupportedVersions(), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength); framer.set_visitor(&visitor); QuicEncryptedPacket encrypted(std::get<0>(packet_buffer), std::get<1>(packet_buffer)); framer.ProcessPacket(encrypted); QuicIetfStatelessResetPacket stateless_reset = visitor.stateless_reset_packet(); StatelessResetToken expected_stateless_reset_token = QuicUtils::GenerateStatelessResetToken(expected_connection_id); return stateless_reset.stateless_reset_token == expected_stateless_reset_token; } Matcher<const std::tuple<const char*, int>> PublicResetPacketEq( QuicConnectionId connection_id) { return Truly( [connection_id](const std::tuple<const char*, int> packet_buffer) { return ValidPublicResetPacketPredicate(connection_id, packet_buffer); }); } TEST_F(QuicTimeWaitListManagerTest, CheckConnectionIdInTimeWait) { EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); } TEST_F(QuicTimeWaitListManagerTest, CheckStatelessConnectionIdInTimeWait) { EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddStatelessConnectionId(connection_id_); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); } TEST_F(QuicTimeWaitListManagerTest, SendVersionNegotiationPacket) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), false, false, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), false, false, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacketWithoutLengthPrefix) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, false, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, false, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacket) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, true, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, true, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacketWithClientConnectionId) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, TestConnectionId(0x33), true, true, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, TestConnectionId(0x33), true, true, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClose) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, &termination_packets); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendTwoConnectionCloses) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, &termination_packets); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .Times(2) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendPublicReset) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_STATELESS_RESET); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id_))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendPublicResetWithExponentialBackOff) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_STATELESS_RESET); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); for (int packet_number = 1; packet_number < 101; ++packet_number) { if ((packet_number & (packet_number - 1)) == 0) { EXPECT_CALL(writer_, WritePacket(_, _, _, _, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); } ProcessPacket(connection_id_); if ((packet_number & (packet_number - 1)) == 0) { EXPECT_TRUE(QuicTimeWaitListManagerPeer::ShouldSendResponse( &time_wait_list_manager_, packet_number)); } else { EXPECT_FALSE(QuicTimeWaitListManagerPeer::ShouldSendResponse( &time_wait_list_manager_, packet_number)); } } } TEST_F(QuicTimeWaitListManagerTest, NoPublicResetForStatelessConnections) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddStatelessConnectionId(connection_id_); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, CleanUpOldConnectionIds) { const size_t kConnectionIdCount = 100; const size_t kOldConnectionIdCount = 31; for (uint64_t conn_id = 1; conn_id <= kOldConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } EXPECT_EQ(kOldConnectionIdCount, time_wait_list_manager_.num_connections()); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period); for (uint64_t conn_id = kOldConnectionIdCount + 1; conn_id <= kConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } EXPECT_EQ(kConnectionIdCount, time_wait_list_manager_.num_connections()); QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39); clock_.AdvanceTime(offset); QuicTime next_alarm_time = clock_.Now() + time_wait_period - offset; EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time)); time_wait_list_manager_.CleanUpOldConnectionIds(); for (uint64_t conn_id = 1; conn_id <= kConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ(conn_id > kOldConnectionIdCount, IsConnectionIdInTimeWait(connection_id)) << "kOldConnectionIdCount: " << kOldConnectionIdCount << " connection_id: " << connection_id; } EXPECT_EQ(kConnectionIdCount - kOldConnectionIdCount, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, CleanUpOldConnectionIdsForMultipleConnectionIdsPerConnection) { connection_id_ = TestConnectionId(7); const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(TestConnectionId(8))); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); std::vector<QuicConnectionId> active_connection_ids{connection_id_, TestConnectionId(8)}; time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, active_connection_ids, QuicTime::Delta::Zero())); EXPECT_TRUE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(7))); EXPECT_TRUE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(8))); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(7))); EXPECT_FALSE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(8))); } TEST_F(QuicTimeWaitListManagerTest, SendQueuedPackets) { QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( connection_id, EmptyQuicConnectionId(), 234)); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); ProcessPacket(connection_id); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(DoAll(Assign(&writer_is_blocked_, true), Return(WriteResult(WRITE_STATUS_BLOCKED, EAGAIN)))); EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_)); ProcessPacket(connection_id); ProcessPacket(connection_id); QuicConnectionId other_connection_id = TestConnectionId(2); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(other_connection_id)); AddConnectionId(other_connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); std::unique_ptr<QuicEncryptedPacket> other_packet(ConstructEncryptedPacket( other_connection_id, EmptyQuicConnectionId(), 23423)); EXPECT_CALL(writer_, WritePacket(_, _, _, _, _, _)).Times(0); EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_)); ProcessPacket(other_connection_id); EXPECT_EQ(2u, time_wait_list_manager_.num_connections()); writer_is_blocked_ = false; EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(other_connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); time_wait_list_manager_.OnBlockedWriterCanWrite(); } TEST_F(QuicTimeWaitListManagerTest, AddConnectionIdTwice) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); const size_t kConnectionCloseLength = 100; std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, &termination_packets); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39); clock_.AdvanceTime(offset + time_wait_period); QuicTime next_alarm_time = clock_.Now() + time_wait_period; EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time)); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, ConnectionIdsOrderedByTime) { const uint64_t conn_id1 = QuicRandom::GetInstance()->RandUint64() % 2; const QuicConnectionId connection_id1 = TestConnectionId(conn_id1); const QuicConnectionId connection_id2 = TestConnectionId(1 - conn_id1); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id1)); AddConnectionId(connection_id1, QuicTimeWaitListManager::DO_NOTHING); clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(10)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id2)); AddConnectionId(connection_id2, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(2u, time_wait_list_manager_.num_connections()); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period - QuicTime::Delta::FromMicroseconds(9)); EXPECT_CALL(alarm_factory_, OnAlarmSet(_, _)); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id1)); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id2)); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, MaxConnectionsTest) { SetQuicFlag(quic_time_wait_list_seconds, 10000000000); SetQuicFlag(quic_time_wait_list_max_connections, 5); uint64_t current_conn_id = 0; const int64_t kMaxConnections = GetQuicFlag(quic_time_wait_list_max_connections); for (int64_t i = 0; i < kMaxConnections; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(current_conn_id, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } for (int64_t i = 0; i < kMaxConnections; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); const QuicConnectionId id_to_evict = TestConnectionId(current_conn_id - kMaxConnections); EXPECT_TRUE(IsConnectionIdInTimeWait(id_to_evict)); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(static_cast<size_t>(kMaxConnections), time_wait_list_manager_.num_connections()); EXPECT_FALSE(IsConnectionIdInTimeWait(id_to_evict)); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } } TEST_F(QuicTimeWaitListManagerTest, ZeroMaxConnections) { SetQuicFlag(quic_time_wait_list_seconds, 10000000000); SetQuicFlag(quic_time_wait_list_max_connections, 0); uint64_t current_conn_id = 0; for (int64_t i = 0; i < 10; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } } TEST_F(QuicTimeWaitListManagerTest, SendStatelessResetInResponseToShortHeaders) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, {connection_id_})); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id_))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id_, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClosePacketsInResponseToShortHeaders) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, {connection_id_})); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id_, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClosePacketsForMultipleConnectionIds) { connection_id_ = TestConnectionId(7); const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(TestConnectionId(8))); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); std::vector<QuicConnectionId> active_connection_ids{connection_id_, TestConnectionId(8)}; time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, active_connection_ids, QuicTime::Delta::Zero())); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .Times(2) .WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 1))); for (auto const& cid : active_connection_ids) { time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, cid, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } } TEST_F(QuicTimeWaitListManagerTest, DonotCrashOnNullStatelessReset) { time_wait_list_manager_.SendPublicReset( self_address_, peer_address_, TestConnectionId(1), true, QuicFramer::GetMinStatelessResetPacketLength() - 1, nullptr); } TEST_F(QuicTimeWaitListManagerTest, SendOrQueueNullPacket) { QuicTimeWaitListManagerPeer::SendOrQueuePacket(&time_wait_list_manager_, nullptr, nullptr); } TEST_F(QuicTimeWaitListManagerTest, TooManyPendingPackets) { SetQuicFlag(quic_time_wait_list_max_pending_packets, 5);
251
cpp
google/quiche
quic_path_validator
quiche/quic/core/quic_path_validator.cc
quiche/quic/core/quic_path_validator_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_PATH_VALIDATOR_H_ #define QUICHE_QUIC_CORE_QUIC_PATH_VALIDATOR_H_ #include <memory> #include <ostream> #include "absl/container/inlined_vector.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_arena_scoped_ptr.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { namespace test { class QuicPathValidatorPeer; } class QuicConnection; enum class PathValidationReason { kReasonUnknown, kMultiPort, kReversePathValidation, kServerPreferredAddressMigration, kPortMigration, kConnectionMigration, kMaxValue, }; class QUICHE_EXPORT QuicPathValidationContext { public: QuicPathValidationContext(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) : self_address_(self_address), peer_address_(peer_address), effective_peer_address_(peer_address) {} QuicPathValidationContext(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicSocketAddress& effective_peer_address) : self_address_(self_address), peer_address_(peer_address), effective_peer_address_(effective_peer_address) {} virtual ~QuicPathValidationContext() = default; virtual QuicPacketWriter* WriterToUse() = 0; const QuicSocketAddress& self_address() const { return self_address_; } const QuicSocketAddress& peer_address() const { return peer_address_; } const QuicSocketAddress& effective_peer_address() const { return effective_peer_address_; } private: QUICHE_EXPORT friend std::ostream& operator<<( std::ostream& os, const QuicPathValidationContext& context); QuicSocketAddress self_address_; QuicSocketAddress peer_address_; QuicSocketAddress effective_peer_address_; }; class QUICHE_EXPORT QuicPathValidator { public: static const uint16_t kMaxRetryTimes = 2; class QUICHE_EXPORT SendDelegate { public: virtual ~SendDelegate() = default; virtual bool SendPathChallenge( const QuicPathFrameBuffer& data_buffer, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicSocketAddress& effective_peer_address, QuicPacketWriter* writer) = 0; virtual QuicTime GetRetryTimeout(const QuicSocketAddress& peer_address, QuicPacketWriter* writer) const = 0; }; class QUICHE_EXPORT ResultDelegate { public: virtual ~ResultDelegate() = default; virtual void OnPathValidationSuccess( std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) = 0; virtual void OnPathValidationFailure( std::unique_ptr<QuicPathValidationContext> context) = 0; }; QuicPathValidator(QuicAlarmFactory* alarm_factory, QuicConnectionArena* arena, SendDelegate* delegate, QuicRandom* random, const QuicClock* clock, QuicConnectionContext* context); void StartPathValidation(std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<ResultDelegate> result_delegate, PathValidationReason reason); void OnPathResponse(const QuicPathFrameBuffer& probing_data, QuicSocketAddress self_address); void CancelPathValidation(); bool HasPendingPathValidation() const; QuicPathValidationContext* GetContext() const; std::unique_ptr<QuicPathValidationContext> ReleaseContext(); PathValidationReason GetPathValidationReason() const { return reason_; } void OnRetryTimeout(); bool IsValidatingPeerAddress(const QuicSocketAddress& effective_peer_address); void MaybeWritePacketToAddress(const char* buffer, size_t buf_len, const QuicSocketAddress& peer_address); private: friend class test::QuicPathValidatorPeer; const QuicPathFrameBuffer& GeneratePathChallengePayload(); void SendPathChallengeAndSetAlarm(); void ResetPathValidation(); struct QUICHE_EXPORT ProbingData { explicit ProbingData(QuicTime send_time) : send_time(send_time) {} QuicPathFrameBuffer frame_buffer; QuicTime send_time; }; absl::InlinedVector<ProbingData, 3> probing_data_; SendDelegate* send_delegate_; QuicRandom* random_; const QuicClock* clock_; std::unique_ptr<QuicPathValidationContext> path_context_; std::unique_ptr<ResultDelegate> result_delegate_; QuicArenaScopedPtr<QuicAlarm> retry_timer_; size_t retry_count_; PathValidationReason reason_ = PathValidationReason::kReasonUnknown; }; } #endif #include "quiche/quic/core/quic_path_validator.h" #include <memory> #include <ostream> #include <utility> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { class RetryAlarmDelegate : public QuicAlarm::DelegateWithContext { public: explicit RetryAlarmDelegate(QuicPathValidator* path_validator, QuicConnectionContext* context) : QuicAlarm::DelegateWithContext(context), path_validator_(path_validator) {} RetryAlarmDelegate(const RetryAlarmDelegate&) = delete; RetryAlarmDelegate& operator=(const RetryAlarmDelegate&) = delete; void OnAlarm() override { path_validator_->OnRetryTimeout(); } private: QuicPathValidator* path_validator_; }; std::ostream& operator<<(std::ostream& os, const QuicPathValidationContext& context) { return os << " from " << context.self_address_ << " to " << context.peer_address_; } QuicPathValidator::QuicPathValidator(QuicAlarmFactory* alarm_factory, QuicConnectionArena* arena, SendDelegate* send_delegate, QuicRandom* random, const QuicClock* clock, QuicConnectionContext* context) : send_delegate_(send_delegate), random_(random), clock_(clock), retry_timer_(alarm_factory->CreateAlarm( arena->New<RetryAlarmDelegate>(this, context), arena)), retry_count_(0u) {} void QuicPathValidator::OnPathResponse(const QuicPathFrameBuffer& probing_data, QuicSocketAddress self_address) { if (!HasPendingPathValidation()) { return; } QUIC_DVLOG(1) << "Match PATH_RESPONSE received on " << self_address; QUIC_BUG_IF(quic_bug_12402_1, !path_context_->self_address().IsInitialized()) << "Self address should have been known by now"; if (self_address != path_context_->self_address()) { QUIC_DVLOG(1) << "Expect the response to be received on " << path_context_->self_address(); return; } for (auto it = probing_data_.begin(); it != probing_data_.end(); ++it) { if (it->frame_buffer == probing_data) { result_delegate_->OnPathValidationSuccess(std::move(path_context_), it->send_time); ResetPathValidation(); return; } } QUIC_DVLOG(1) << "PATH_RESPONSE with payload " << probing_data.data() << " doesn't match the probing data."; } void QuicPathValidator::StartPathValidation( std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<ResultDelegate> result_delegate, PathValidationReason reason) { QUICHE_DCHECK(context); QUIC_DLOG(INFO) << "Start validating path " << *context << " via writer: " << context->WriterToUse(); if (path_context_ != nullptr) { QUIC_BUG(quic_bug_10876_1) << "There is an on-going validation on path " << *path_context_; ResetPathValidation(); } reason_ = reason; path_context_ = std::move(context); result_delegate_ = std::move(result_delegate); SendPathChallengeAndSetAlarm(); } void QuicPathValidator::ResetPathValidation() { path_context_ = nullptr; result_delegate_ = nullptr; retry_timer_->Cancel(); retry_count_ = 0; reason_ = PathValidationReason::kReasonUnknown; } void QuicPathValidator::CancelPathValidation() { if (path_context_ == nullptr) { return; } QUIC_DVLOG(1) << "Cancel validation on path" << *path_context_; result_delegate_->OnPathValidationFailure(std::move(path_context_)); ResetPathValidation(); } bool QuicPathValidator::HasPendingPathValidation() const { return path_context_ != nullptr; } QuicPathValidationContext* QuicPathValidator::GetContext() const { return path_context_.get(); } std::unique_ptr<QuicPathValidationContext> QuicPathValidator::ReleaseContext() { auto ret = std::move(path_context_); ResetPathValidation(); return ret; } const QuicPathFrameBuffer& QuicPathValidator::GeneratePathChallengePayload() { probing_data_.emplace_back(clock_->Now()); random_->RandBytes(probing_data_.back().frame_buffer.data(), sizeof(QuicPathFrameBuffer)); return probing_data_.back().frame_buffer; } void QuicPathValidator::OnRetryTimeout() { ++retry_count_; if (retry_count_ > kMaxRetryTimes) { CancelPathValidation(); return; } QUIC_DVLOG(1) << "Send another PATH_CHALLENGE on path " << *path_context_; SendPathChallengeAndSetAlarm(); } void QuicPathValidator::SendPathChallengeAndSetAlarm() { bool should_continue = send_delegate_->SendPathChallenge( GeneratePathChallengePayload(), path_context_->self_address(), path_context_->peer_address(), path_context_->effective_peer_address(), path_context_->WriterToUse()); if (!should_continue) { CancelPathValidation(); return; } retry_timer_->Set(send_delegate_->GetRetryTimeout( path_context_->peer_address(), path_context_->WriterToUse())); } bool QuicPathValidator::IsValidatingPeerAddress( const QuicSocketAddress& effective_peer_address) { return path_context_ != nullptr && path_context_->effective_peer_address() == effective_peer_address; } void QuicPathValidator::MaybeWritePacketToAddress( const char* buffer, size_t buf_len, const QuicSocketAddress& peer_address) { if (!HasPendingPathValidation() || path_context_->peer_address() != peer_address) { return; } QUIC_DVLOG(1) << "Path validator is sending packet of size " << buf_len << " from " << path_context_->self_address() << " to " << path_context_->peer_address(); path_context_->WriterToUse()->WritePacket( buffer, buf_len, path_context_->self_address().host(), path_context_->peer_address(), nullptr, QuicPacketWriterParams()); } }
#include "quiche/quic/core/quic_path_validator.h" #include <memory> #include "quiche/quic/core/frames/quic_path_challenge_frame.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_path_validator_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::Invoke; using testing::Return; namespace quic { namespace test { class MockSendDelegate : public QuicPathValidator::SendDelegate { public: MOCK_METHOD(bool, SendPathChallenge, (const QuicPathFrameBuffer&, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*), (override)); MOCK_METHOD(QuicTime, GetRetryTimeout, (const QuicSocketAddress&, QuicPacketWriter*), (const, override)); }; class QuicPathValidatorTest : public QuicTest { public: QuicPathValidatorTest() : path_validator_(&alarm_factory_, &arena_, &send_delegate_, &random_, &clock_, nullptr), context_(new MockQuicPathValidationContext( self_address_, peer_address_, effective_peer_address_, &writer_)), result_delegate_( new testing::StrictMock<MockQuicPathValidationResultDelegate>()) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); ON_CALL(send_delegate_, GetRetryTimeout(_, _)) .WillByDefault( Return(clock_.ApproximateNow() + 3 * QuicTime::Delta::FromMilliseconds(kInitialRttMs))); } protected: quic::test::MockAlarmFactory alarm_factory_; MockSendDelegate send_delegate_; MockRandom random_; MockClock clock_; QuicConnectionArena arena_; QuicPathValidator path_validator_; QuicSocketAddress self_address_{QuicIpAddress::Any4(), 443}; QuicSocketAddress peer_address_{QuicIpAddress::Loopback4(), 443}; QuicSocketAddress effective_peer_address_{QuicIpAddress::Loopback4(), 12345}; MockPacketWriter writer_; MockQuicPathValidationContext* context_; MockQuicPathValidationResultDelegate* result_delegate_; }; TEST_F(QuicPathValidatorTest, PathValidationSuccessOnFirstRound) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)); const QuicTime expected_start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); EXPECT_TRUE(path_validator_.HasPendingPathValidation()); EXPECT_EQ(PathValidationReason::kMultiPort, path_validator_.GetPathValidationReason()); EXPECT_TRUE(path_validator_.IsValidatingPeerAddress(effective_peer_address_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, _)) .WillOnce(Invoke([=](std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { EXPECT_EQ(context.get(), context_); EXPECT_EQ(start_time, expected_start_time); })); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, RespondWithDifferentSelfAddress) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)); const QuicTime expected_start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); const QuicSocketAddress kAlternativeSelfAddress(QuicIpAddress::Any6(), 54321); EXPECT_NE(kAlternativeSelfAddress, self_address_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, kAlternativeSelfAddress); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, _)) .WillOnce(Invoke([=](std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { EXPECT_EQ(context->self_address(), self_address_); EXPECT_EQ(start_time, expected_start_time); })); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, RespondAfter1stRetry) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { EXPECT_NE(payload, challenge_data); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(2u); const QuicTime start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); random_.ChangeValue(); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, start_time)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); } TEST_F(QuicPathValidatorTest, RespondToRetryChallenge) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { EXPECT_NE(challenge_data, payload); memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(2u); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); const QuicTime start_time = clock_.Now(); random_.ChangeValue(); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, start_time)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); } TEST_F(QuicPathValidatorTest, ValidationTimeOut) { EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .Times(3u) .WillRepeatedly(Return(true)); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(3u); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); QuicPathFrameBuffer challenge_data; memset(challenge_data.data(), 'a', challenge_data.size()); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_CALL(*result_delegate_, OnPathValidationFailure(_)) .WillOnce(Invoke([=](std::unique_ptr<QuicPathValidationContext> context) { EXPECT_EQ(context_, context.get()); })); for (size_t i = 0; i <= QuicPathValidator::kMaxRetryTimes; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); } EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, SendPathChallengeError) { EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer&, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { path_validator_.CancelPathValidation(); return false; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(0u); EXPECT_CALL(*result_delegate_, OnPathValidationFailure(_)); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(&path_validator_)->IsSet()); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } } }
252
cpp
google/quiche
quic_crypto_client_stream
quiche/quic/core/quic_crypto_client_stream.cc
quiche/quic/core/quic_crypto_client_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_STREAM_H_ #define QUICHE_QUIC_CORE_QUIC_CRYPTO_CLIENT_STREAM_H_ #include <cstdint> #include <memory> #include <string> #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_crypto_handshaker.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicCryptoClientStreamPeer; } class TlsClientHandshaker; class QUICHE_EXPORT QuicCryptoClientStreamBase : public QuicCryptoStream { public: explicit QuicCryptoClientStreamBase(QuicSession* session); ~QuicCryptoClientStreamBase() override {} virtual bool CryptoConnect() = 0; virtual int num_sent_client_hellos() const = 0; virtual bool ResumptionAttempted() const = 0; virtual bool IsResumption() const = 0; virtual bool EarlyDataAccepted() const = 0; virtual bool ReceivedInchoateReject() const = 0; virtual int num_scup_messages_received() const = 0; bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { QUICHE_NOTREACHED(); return false; } std::string GetAddressToken( const CachedNetworkParameters* ) const override { QUICHE_DCHECK(false); return ""; } bool ValidateAddressToken(absl::string_view ) const override { QUICHE_DCHECK(false); return false; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { QUICHE_DCHECK(false); return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters ) override { QUICHE_DCHECK(false); } }; class QUICHE_EXPORT QuicCryptoClientStream : public QuicCryptoClientStreamBase { public: static const int kMaxClientHellos = 4; class QUICHE_EXPORT HandshakerInterface { public: virtual ~HandshakerInterface() {} virtual bool CryptoConnect() = 0; virtual int num_sent_client_hellos() const = 0; virtual bool ResumptionAttempted() const = 0; virtual bool IsResumption() const = 0; virtual bool EarlyDataAccepted() const = 0; virtual ssl_early_data_reason_t EarlyDataReason() const = 0; virtual bool ReceivedInchoateReject() const = 0; virtual int num_scup_messages_received() const = 0; virtual std::string chlo_hash() const = 0; virtual bool encryption_established() const = 0; virtual bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const = 0; virtual EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const = 0; virtual bool one_rtt_keys_available() const = 0; virtual const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const = 0; virtual CryptoMessageParser* crypto_message_parser() = 0; virtual size_t BufferSizeLimitForLevel(EncryptionLevel level) const = 0; virtual std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; virtual HandshakeState GetHandshakeState() const = 0; virtual void OnOneRttPacketAcknowledged() = 0; virtual void OnHandshakePacketSent() = 0; virtual void OnConnectionClosed(QuicErrorCode error, ConnectionCloseSource source) = 0; virtual void OnHandshakeDoneReceived() = 0; virtual void OnNewTokenReceived(absl::string_view token) = 0; virtual void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) = 0; virtual bool ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) = 0; }; class QUICHE_EXPORT ProofHandler { public: virtual ~ProofHandler() {} virtual void OnProofValid( const QuicCryptoClientConfig::CachedState& cached) = 0; virtual void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) = 0; }; QuicCryptoClientStream(const QuicServerId& server_id, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, ProofHandler* proof_handler, bool has_application_state); QuicCryptoClientStream(const QuicCryptoClientStream&) = delete; QuicCryptoClientStream& operator=(const QuicCryptoClientStream&) = delete; ~QuicCryptoClientStream() override; bool CryptoConnect() override; int num_sent_client_hellos() const override; bool ResumptionAttempted() const override; bool IsResumption() const override; bool EarlyDataAccepted() const override; ssl_early_data_reason_t EarlyDataReason() const override; bool ReceivedInchoateReject() const override; int num_scup_messages_received() const override; bool encryption_established() const override; bool one_rtt_keys_available() const override; const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override; CryptoMessageParser* crypto_message_parser() override; void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override; void OnHandshakePacketSent() override; void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) override; void OnHandshakeDoneReceived() override; void OnNewTokenReceived(absl::string_view token) override; HandshakeState GetHandshakeState() const override; void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) override; size_t BufferSizeLimitForLevel(EncryptionLevel level) const override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; SSL* GetSsl() const override; bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override; EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override; bool ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) override; std::string chlo_hash() const; protected: void set_handshaker(std::unique_ptr<HandshakerInterface> handshaker) { handshaker_ = std::move(handshaker); } private: friend class test::QuicCryptoClientStreamPeer; std::unique_ptr<HandshakerInterface> handshaker_; TlsClientHandshaker* tls_handshaker_{nullptr}; }; } #endif #include "quiche/quic/core/quic_crypto_client_stream.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/quic_crypto_client_handshaker.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/tls_client_handshaker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { const int QuicCryptoClientStream::kMaxClientHellos; QuicCryptoClientStreamBase::QuicCryptoClientStreamBase(QuicSession* session) : QuicCryptoStream(session) {} QuicCryptoClientStream::QuicCryptoClientStream( const QuicServerId& server_id, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, ProofHandler* proof_handler, bool has_application_state) : QuicCryptoClientStreamBase(session) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, session->connection()->perspective()); switch (session->connection()->version().handshake_protocol) { case PROTOCOL_QUIC_CRYPTO: handshaker_ = std::make_unique<QuicCryptoClientHandshaker>( server_id, this, session, std::move(verify_context), crypto_config, proof_handler); break; case PROTOCOL_TLS1_3: { auto handshaker = std::make_unique<TlsClientHandshaker>( server_id, this, session, std::move(verify_context), crypto_config, proof_handler, has_application_state); tls_handshaker_ = handshaker.get(); handshaker_ = std::move(handshaker); break; } case PROTOCOL_UNSUPPORTED: QUIC_BUG(quic_bug_10296_1) << "Attempting to create QuicCryptoClientStream for unknown " "handshake protocol"; } } QuicCryptoClientStream::~QuicCryptoClientStream() {} bool QuicCryptoClientStream::CryptoConnect() { return handshaker_->CryptoConnect(); } int QuicCryptoClientStream::num_sent_client_hellos() const { return handshaker_->num_sent_client_hellos(); } bool QuicCryptoClientStream::ResumptionAttempted() const { return handshaker_->ResumptionAttempted(); } bool QuicCryptoClientStream::IsResumption() const { return handshaker_->IsResumption(); } bool QuicCryptoClientStream::EarlyDataAccepted() const { return handshaker_->EarlyDataAccepted(); } ssl_early_data_reason_t QuicCryptoClientStream::EarlyDataReason() const { return handshaker_->EarlyDataReason(); } bool QuicCryptoClientStream::ReceivedInchoateReject() const { return handshaker_->ReceivedInchoateReject(); } int QuicCryptoClientStream::num_scup_messages_received() const { return handshaker_->num_scup_messages_received(); } bool QuicCryptoClientStream::encryption_established() const { return handshaker_->encryption_established(); } bool QuicCryptoClientStream::one_rtt_keys_available() const { return handshaker_->one_rtt_keys_available(); } const QuicCryptoNegotiatedParameters& QuicCryptoClientStream::crypto_negotiated_params() const { return handshaker_->crypto_negotiated_params(); } CryptoMessageParser* QuicCryptoClientStream::crypto_message_parser() { return handshaker_->crypto_message_parser(); } HandshakeState QuicCryptoClientStream::GetHandshakeState() const { return handshaker_->GetHandshakeState(); } size_t QuicCryptoClientStream::BufferSizeLimitForLevel( EncryptionLevel level) const { return handshaker_->BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> QuicCryptoClientStream::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return handshaker_->AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> QuicCryptoClientStream::CreateCurrentOneRttEncrypter() { return handshaker_->CreateCurrentOneRttEncrypter(); } bool QuicCryptoClientStream::ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) { return handshaker_->ExportKeyingMaterial(label, context, result_len, result); } std::string QuicCryptoClientStream::chlo_hash() const { return handshaker_->chlo_hash(); } void QuicCryptoClientStream::OnOneRttPacketAcknowledged() { handshaker_->OnOneRttPacketAcknowledged(); } void QuicCryptoClientStream::OnHandshakePacketSent() { handshaker_->OnHandshakePacketSent(); } void QuicCryptoClientStream::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { handshaker_->OnConnectionClosed(frame.quic_error_code, source); } void QuicCryptoClientStream::OnHandshakeDoneReceived() { handshaker_->OnHandshakeDoneReceived(); } void QuicCryptoClientStream::OnNewTokenReceived(absl::string_view token) { handshaker_->OnNewTokenReceived(token); } void QuicCryptoClientStream::SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) { handshaker_->SetServerApplicationStateForResumption( std::move(application_state)); } SSL* QuicCryptoClientStream::GetSsl() const { return tls_handshaker_ == nullptr ? nullptr : tls_handshaker_->ssl(); } bool QuicCryptoClientStream::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const { return handshaker_->IsCryptoFrameExpectedForEncryptionLevel(level); } EncryptionLevel QuicCryptoClientStream::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { return handshaker_->GetEncryptionLevelToSendCryptoDataOfSpace(space); } }
#include "quiche/quic/core/quic_crypto_client_stream.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kServerPort = 443; class QuicCryptoClientStreamTest : public QuicTest { public: QuicCryptoClientStreamTest() : supported_versions_(AllSupportedVersionsWithQuicCrypto()), server_id_(kServerHostname, kServerPort, false), crypto_config_(crypto_test_utils::ProofVerifierForTesting(), std::make_unique<test::SimpleSessionCache>()), server_crypto_config_( crypto_test_utils::CryptoServerConfigForTesting()) { CreateConnection(); } void CreateSession() { session_ = std::make_unique<TestQuicSpdyClientSession>( connection_, DefaultQuicConfig(), supported_versions_, server_id_, &crypto_config_); EXPECT_CALL(*session_, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>( {AlpnForVersion(connection_->version())}))); } void CreateConnection() { connection_ = new PacketSavingConnection(&client_helper_, &alarm_factory_, Perspective::IS_CLIENT, supported_versions_); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); CreateSession(); } void CompleteCryptoHandshake() { int proof_verify_details_calls = 1; if (stream()->handshake_protocol() != PROTOCOL_TLS1_3) { EXPECT_CALL(*session_, OnProofValid(testing::_)) .Times(testing::AtLeast(1)); proof_verify_details_calls = 0; } EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AtLeast(proof_verify_details_calls)); stream()->CryptoConnect(); QuicConfig config; crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), AlpnForVersion(connection_->version())); } QuicCryptoClientStream* stream() { return session_->GetMutableCryptoStream(); } MockQuicConnectionHelper server_helper_; MockQuicConnectionHelper client_helper_; MockAlarmFactory alarm_factory_; PacketSavingConnection* connection_; ParsedQuicVersionVector supported_versions_; std::unique_ptr<TestQuicSpdyClientSession> session_; QuicServerId server_id_; CryptoHandshakeMessage message_; QuicCryptoClientConfig crypto_config_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; }; TEST_F(QuicCryptoClientStreamTest, NotInitiallyConected) { EXPECT_FALSE(stream()->encryption_established()); EXPECT_FALSE(stream()->one_rtt_keys_available()); } TEST_F(QuicCryptoClientStreamTest, ConnectedAfterSHLO) { CompleteCryptoHandshake(); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_no_session_offered); } TEST_F(QuicCryptoClientStreamTest, MessageAfterHandshake) { CompleteCryptoHandshake(); EXPECT_CALL( *connection_, CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, _, _)); message_.set_tag(kCHLO); crypto_test_utils::SendHandshakeMessageToStream(stream(), message_, Perspective::IS_CLIENT); } TEST_F(QuicCryptoClientStreamTest, BadMessageType) { stream()->CryptoConnect(); message_.set_tag(kCHLO); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, "Expected REJ", _)); crypto_test_utils::SendHandshakeMessageToStream(stream(), message_, Perspective::IS_CLIENT); } TEST_F(QuicCryptoClientStreamTest, NegotiatedParameters) { CompleteCryptoHandshake(); const QuicConfig* config = session_->config(); EXPECT_EQ(kMaximumIdleTimeoutSecs, config->IdleNetworkTimeout().ToSeconds()); const QuicCryptoNegotiatedParameters& crypto_params( stream()->crypto_negotiated_params()); EXPECT_EQ(crypto_config_.aead[0], crypto_params.aead); EXPECT_EQ(crypto_config_.kexs[0], crypto_params.key_exchange); } TEST_F(QuicCryptoClientStreamTest, ExpiredServerConfig) { CompleteCryptoHandshake(); CreateConnection(); connection_->AdvanceTime( QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5)); EXPECT_CALL(*session_, OnProofValid(testing::_)); stream()->CryptoConnect(); ASSERT_EQ(1u, connection_->encrypted_packets_.size()); EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); } TEST_F(QuicCryptoClientStreamTest, ClientTurnedOffZeroRtt) { CompleteCryptoHandshake(); CreateConnection(); QuicTagVector options; options.push_back(kQNZ2); session_->config()->SetClientConnectionOptions(options); CompleteCryptoHandshake(); EXPECT_EQ(2, stream()->num_sent_client_hellos()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_disabled); } TEST_F(QuicCryptoClientStreamTest, ClockSkew) { connection_->AdvanceTime( QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5)); CompleteCryptoHandshake(); } TEST_F(QuicCryptoClientStreamTest, InvalidCachedServerConfig) { CompleteCryptoHandshake(); CreateConnection(); QuicCryptoClientConfig::CachedState* state = crypto_config_.LookupOrCreate(server_id_); std::vector<std::string> certs = state->certs(); std::string cert_sct = state->cert_sct(); std::string signature = state->signature(); std::string chlo_hash = state->chlo_hash(); state->SetProof(certs, cert_sct, chlo_hash, signature + signature); EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); ASSERT_EQ(1u, connection_->encrypted_packets_.size()); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdate) { CompleteCryptoHandshake(); QuicCryptoClientConfig::CachedState* state = crypto_config_.LookupOrCreate(server_id_); EXPECT_NE("xstk", state->source_address_token()); unsigned char stk[] = {'x', 's', 't', 'k'}; unsigned char scfg[] = { 0x53, 0x43, 0x46, 0x47, 0x01, 0x00, 0x00, 0x00, 0x45, 0x58, 0x50, 0x59, 0x08, 0x00, 0x00, 0x00, '1', '2', '3', '4', '5', '6', '7', '8'}; CryptoHandshakeMessage server_config_update; server_config_update.set_tag(kSCUP); server_config_update.SetValue(kSourceAddressTokenTag, stk); server_config_update.SetValue(kSCFG, scfg); const uint64_t expiry_seconds = 60 * 60 * 24 * 2; server_config_update.SetValue(kSTTL, expiry_seconds); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); EXPECT_EQ("xstk", state->source_address_token()); const std::string& cached_scfg = state->server_config(); quiche::test::CompareCharArraysWithHexError( "scfg", cached_scfg.data(), cached_scfg.length(), reinterpret_cast<char*>(scfg), ABSL_ARRAYSIZE(scfg)); QuicStreamSequencer* sequencer = QuicStreamPeer::sequencer(stream()); EXPECT_FALSE(QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer)); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateWithCert) { CompleteCryptoHandshake(); QuicCryptoServerConfig crypto_config( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); crypto_test_utils::SetupCryptoServerConfigForTest( connection_->clock(), QuicRandom::GetInstance(), &crypto_config); SourceAddressTokens tokens; QuicCompressedCertsCache cache(1); CachedNetworkParameters network_params; CryptoHandshakeMessage server_config_update; class Callback : public BuildServerConfigUpdateMessageResultCallback { public: Callback(bool* ok, CryptoHandshakeMessage* message) : ok_(ok), message_(message) {} void Run(bool ok, const CryptoHandshakeMessage& message) override { *ok_ = ok; *message_ = message; } private: bool* ok_; CryptoHandshakeMessage* message_; }; bool ok = false; crypto_config.BuildServerConfigUpdateMessage( session_->transport_version(), stream()->chlo_hash(), tokens, QuicSocketAddress(QuicIpAddress::Loopback6(), 1234), QuicSocketAddress(QuicIpAddress::Loopback6(), 4321), connection_->clock(), QuicRandom::GetInstance(), &cache, stream()->crypto_negotiated_params(), &network_params, std::unique_ptr<BuildServerConfigUpdateMessageResultCallback>( new Callback(&ok, &server_config_update))); EXPECT_TRUE(ok); EXPECT_CALL(*session_, OnProofValid(testing::_)); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); CreateConnection(); EXPECT_CALL(*session_, OnProofValid(testing::_)); EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateBeforeHandshake) { EXPECT_CALL( *connection_, CloseConnection(QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE, _, _)); CryptoHandshakeMessage server_config_update; server_config_update.set_tag(kSCUP); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); } } } }
253
cpp
google/quiche
quic_connection_context
quiche/quic/core/quic_connection_context.cc
quiche/quic/core/quic_connection_context_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_CONTEXT_H_ #define QUICHE_QUIC_CORE_QUIC_CONNECTION_CONTEXT_H_ #include <memory> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { class QUICHE_EXPORT QuicConnectionTracer { public: virtual ~QuicConnectionTracer() = default; virtual void PrintLiteral(const char* literal) = 0; virtual void PrintString(absl::string_view s) = 0; template <typename... Args> void Printf(const absl::FormatSpec<Args...>& format, const Args&... args) { std::string s = absl::StrFormat(format, args...); PrintString(s); } }; class QUICHE_EXPORT QuicBugListener { public: virtual ~QuicBugListener() = default; virtual void OnQuicBug(const char* bug_id, const char* file, int line, absl::string_view bug_message) = 0; }; class QUICHE_EXPORT QuicConnectionContextListener { public: virtual ~QuicConnectionContextListener() = default; private: friend class QuicConnectionContextSwitcher; virtual void Activate() = 0; virtual void Deactivate() = 0; }; struct QUICHE_EXPORT QuicConnectionContext final { static QuicConnectionContext* Current(); std::unique_ptr<QuicConnectionContextListener> listener; std::unique_ptr<QuicConnectionTracer> tracer; std::unique_ptr<QuicBugListener> bug_listener; }; class QUICHE_EXPORT QuicConnectionContextSwitcher final { public: explicit QuicConnectionContextSwitcher(QuicConnectionContext* new_context); ~QuicConnectionContextSwitcher(); private: QuicConnectionContext* old_context_; }; inline void QUIC_TRACELITERAL(const char* literal) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->PrintLiteral(literal); } } inline void QUIC_TRACESTRING(absl::string_view s) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->PrintString(s); } } template <typename... Args> void QUIC_TRACEPRINTF(const absl::FormatSpec<Args...>& format, const Args&... args) { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->tracer) { current->tracer->Printf(format, args...); } } inline QuicBugListener* CurrentBugListener() { QuicConnectionContext* current = QuicConnectionContext::Current(); return (current != nullptr) ? current->bug_listener.get() : nullptr; } } #endif #include "quiche/quic/core/quic_connection_context.h" #include "absl/base/attributes.h" namespace quic { namespace { ABSL_CONST_INIT thread_local QuicConnectionContext* current_context = nullptr; } QuicConnectionContext* QuicConnectionContext::Current() { return current_context; } QuicConnectionContextSwitcher::QuicConnectionContextSwitcher( QuicConnectionContext* new_context) : old_context_(QuicConnectionContext::Current()) { current_context = new_context; if (new_context && new_context->listener) { new_context->listener->Activate(); } } QuicConnectionContextSwitcher::~QuicConnectionContextSwitcher() { QuicConnectionContext* current = QuicConnectionContext::Current(); if (current && current->listener) { current->listener->Deactivate(); } current_context = old_context_; } }
#include "quiche/quic/core/quic_connection_context.h" #include <memory> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_thread.h" using testing::ElementsAre; namespace quic::test { namespace { class TraceCollector : public QuicConnectionTracer { public: ~TraceCollector() override = default; void PrintLiteral(const char* literal) override { trace_.push_back(literal); } void PrintString(absl::string_view s) override { trace_.push_back(std::string(s)); } const std::vector<std::string>& trace() const { return trace_; } private: std::vector<std::string> trace_; }; struct FakeConnection { FakeConnection() { context.tracer = std::make_unique<TraceCollector>(); } const std::vector<std::string>& trace() const { return static_cast<const TraceCollector*>(context.tracer.get())->trace(); } QuicConnectionContext context; }; void SimpleSwitch() { FakeConnection connection; EXPECT_EQ(QuicConnectionContext::Current(), nullptr); QUIC_TRACELITERAL("before switch: literal"); QUIC_TRACESTRING(std::string("before switch: string")); QUIC_TRACEPRINTF("%s: %s", "before switch", "printf"); { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("literal"); QUIC_TRACESTRING(std::string("string")); QUIC_TRACEPRINTF("%s", "printf"); } EXPECT_EQ(QuicConnectionContext::Current(), nullptr); QUIC_TRACELITERAL("after switch: literal"); QUIC_TRACESTRING(std::string("after switch: string")); QUIC_TRACEPRINTF("%s: %s", "after switch", "printf"); EXPECT_THAT(connection.trace(), ElementsAre("literal", "string", "printf")); } void NestedSwitch() { FakeConnection outer, inner; { QuicConnectionContextSwitcher switcher(&outer.context); QUIC_TRACELITERAL("outer literal 0"); QUIC_TRACESTRING(std::string("outer string 0")); QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 0); { QuicConnectionContextSwitcher nested_switcher(&inner.context); QUIC_TRACELITERAL("inner literal"); QUIC_TRACESTRING(std::string("inner string")); QUIC_TRACEPRINTF("%s %s", "inner", "printf"); } QUIC_TRACELITERAL("outer literal 1"); QUIC_TRACESTRING(std::string("outer string 1")); QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 1); } EXPECT_THAT(outer.trace(), ElementsAre("outer literal 0", "outer string 0", "outer printf 0", "outer literal 1", "outer string 1", "outer printf 1")); EXPECT_THAT(inner.trace(), ElementsAre("inner literal", "inner string", "inner printf")); } void AlternatingSwitch() { FakeConnection zero, one, two; for (int i = 0; i < 15; ++i) { FakeConnection* connection = ((i % 3) == 0) ? &zero : (((i % 3) == 1) ? &one : &two); QuicConnectionContextSwitcher switcher(&connection->context); QUIC_TRACEPRINTF("%d", i); } EXPECT_THAT(zero.trace(), ElementsAre("0", "3", "6", "9", "12")); EXPECT_THAT(one.trace(), ElementsAre("1", "4", "7", "10", "13")); EXPECT_THAT(two.trace(), ElementsAre("2", "5", "8", "11", "14")); } typedef void (*ThreadFunction)(); template <ThreadFunction func> class TestThread : public QuicThread { public: TestThread() : QuicThread("TestThread") {} ~TestThread() override = default; protected: void Run() override { func(); } }; template <ThreadFunction func> void RunInThreads(size_t n_threads) { using ThreadType = TestThread<func>; std::vector<ThreadType> threads(n_threads); for (ThreadType& t : threads) { t.Start(); } for (ThreadType& t : threads) { t.Join(); } } class QuicConnectionContextTest : public QuicTest { protected: }; TEST_F(QuicConnectionContextTest, NullTracerOK) { FakeConnection connection; std::unique_ptr<QuicConnectionTracer> tracer; { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("msg 1 recorded"); } connection.context.tracer.swap(tracer); { QuicConnectionContextSwitcher switcher(&connection.context); QUIC_TRACELITERAL("msg 2 ignored"); } EXPECT_THAT(static_cast<TraceCollector*>(tracer.get())->trace(), ElementsAre("msg 1 recorded")); } TEST_F(QuicConnectionContextTest, TestSimpleSwitch) { RunInThreads<SimpleSwitch>(10); } TEST_F(QuicConnectionContextTest, TestNestedSwitch) { RunInThreads<NestedSwitch>(10); } TEST_F(QuicConnectionContextTest, TestAlternatingSwitch) { RunInThreads<AlternatingSwitch>(10); } } }
254
cpp
google/quiche
quic_stream_send_buffer
quiche/quic/core/quic_stream_send_buffer.cc
quiche/quic/core/quic_stream_send_buffer_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_SEND_BUFFER_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_SEND_BUFFER_H_ #include "absl/types/span.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_interval_deque.h" #include "quiche/quic/core/quic_interval_set.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class QuicStreamSendBufferPeer; class QuicStreamPeer; } class QuicDataWriter; struct QUICHE_EXPORT BufferedSlice { BufferedSlice(quiche::QuicheMemSlice mem_slice, QuicStreamOffset offset); BufferedSlice(BufferedSlice&& other); BufferedSlice& operator=(BufferedSlice&& other); BufferedSlice(const BufferedSlice& other) = delete; BufferedSlice& operator=(const BufferedSlice& other) = delete; ~BufferedSlice(); QuicInterval<std::size_t> interval() const; quiche::QuicheMemSlice slice; QuicStreamOffset offset; }; struct QUICHE_EXPORT StreamPendingRetransmission { constexpr StreamPendingRetransmission(QuicStreamOffset offset, QuicByteCount length) : offset(offset), length(length) {} QuicStreamOffset offset; QuicByteCount length; bool operator==(const StreamPendingRetransmission& other) const; }; class QUICHE_EXPORT QuicStreamSendBuffer { public: explicit QuicStreamSendBuffer(quiche::QuicheBufferAllocator* allocator); QuicStreamSendBuffer(const QuicStreamSendBuffer& other) = delete; QuicStreamSendBuffer(QuicStreamSendBuffer&& other) = delete; ~QuicStreamSendBuffer(); void SaveStreamData(absl::string_view data); void SaveMemSlice(quiche::QuicheMemSlice slice); QuicByteCount SaveMemSliceSpan(absl::Span<quiche::QuicheMemSlice> span); void OnStreamDataConsumed(size_t bytes_consumed); bool WriteStreamData(QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer); bool OnStreamDataAcked(QuicStreamOffset offset, QuicByteCount data_length, QuicByteCount* newly_acked_length); void OnStreamDataLost(QuicStreamOffset offset, QuicByteCount data_length); void OnStreamDataRetransmitted(QuicStreamOffset offset, QuicByteCount data_length); bool HasPendingRetransmission() const; StreamPendingRetransmission NextPendingRetransmission() const; bool IsStreamDataOutstanding(QuicStreamOffset offset, QuicByteCount data_length) const; size_t size() const; QuicStreamOffset stream_offset() const { return stream_offset_; } uint64_t stream_bytes_written() const { return stream_bytes_written_; } uint64_t stream_bytes_outstanding() const { return stream_bytes_outstanding_; } const QuicIntervalSet<QuicStreamOffset>& bytes_acked() const { return bytes_acked_; } const QuicIntervalSet<QuicStreamOffset>& pending_retransmissions() const { return pending_retransmissions_; } private: friend class test::QuicStreamSendBufferPeer; friend class test::QuicStreamPeer; bool FreeMemSlices(QuicStreamOffset start, QuicStreamOffset end); void CleanUpBufferedSlices(); QuicStreamOffset current_end_offset_; QuicIntervalDeque<BufferedSlice> interval_deque_; QuicStreamOffset stream_offset_; quiche::QuicheBufferAllocator* allocator_; uint64_t stream_bytes_written_; uint64_t stream_bytes_outstanding_; QuicIntervalSet<QuicStreamOffset> bytes_acked_; QuicIntervalSet<QuicStreamOffset> pending_retransmissions_; int32_t write_index_; }; } #endif #include "quiche/quic/core/quic_stream_send_buffer.h" #include <algorithm> #include <utility> #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace quic { namespace { struct CompareOffset { bool operator()(const BufferedSlice& slice, QuicStreamOffset offset) const { return slice.offset + slice.slice.length() < offset; } }; } BufferedSlice::BufferedSlice(quiche::QuicheMemSlice mem_slice, QuicStreamOffset offset) : slice(std::move(mem_slice)), offset(offset) {} BufferedSlice::BufferedSlice(BufferedSlice&& other) = default; BufferedSlice& BufferedSlice::operator=(BufferedSlice&& other) = default; BufferedSlice::~BufferedSlice() {} QuicInterval<std::size_t> BufferedSlice::interval() const { const std::size_t length = slice.length(); return QuicInterval<std::size_t>(offset, offset + length); } bool StreamPendingRetransmission::operator==( const StreamPendingRetransmission& other) const { return offset == other.offset && length == other.length; } QuicStreamSendBuffer::QuicStreamSendBuffer( quiche::QuicheBufferAllocator* allocator) : current_end_offset_(0), stream_offset_(0), allocator_(allocator), stream_bytes_written_(0), stream_bytes_outstanding_(0), write_index_(-1) {} QuicStreamSendBuffer::~QuicStreamSendBuffer() {} void QuicStreamSendBuffer::SaveStreamData(absl::string_view data) { QUICHE_DCHECK(!data.empty()); const QuicByteCount max_data_slice_size = GetQuicFlag(quic_send_buffer_max_data_slice_size); while (!data.empty()) { auto slice_len = std::min<absl::string_view::size_type>( data.length(), max_data_slice_size); auto buffer = quiche::QuicheBuffer::Copy(allocator_, data.substr(0, slice_len)); SaveMemSlice(quiche::QuicheMemSlice(std::move(buffer))); data = data.substr(slice_len); } } void QuicStreamSendBuffer::SaveMemSlice(quiche::QuicheMemSlice slice) { QUIC_DVLOG(2) << "Save slice offset " << stream_offset_ << " length " << slice.length(); if (slice.empty()) { QUIC_BUG(quic_bug_10853_1) << "Try to save empty MemSlice to send buffer."; return; } size_t length = slice.length(); if (interval_deque_.Empty()) { const QuicStreamOffset end = stream_offset_ + length; current_end_offset_ = std::max(current_end_offset_, end); } BufferedSlice bs = BufferedSlice(std::move(slice), stream_offset_); interval_deque_.PushBack(std::move(bs)); stream_offset_ += length; } QuicByteCount QuicStreamSendBuffer::SaveMemSliceSpan( absl::Span<quiche::QuicheMemSlice> span) { QuicByteCount total = 0; for (quiche::QuicheMemSlice& slice : span) { if (slice.length() == 0) { continue; } total += slice.length(); SaveMemSlice(std::move(slice)); } return total; } void QuicStreamSendBuffer::OnStreamDataConsumed(size_t bytes_consumed) { stream_bytes_written_ += bytes_consumed; stream_bytes_outstanding_ += bytes_consumed; } bool QuicStreamSendBuffer::WriteStreamData(QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { QUIC_BUG_IF(quic_bug_12823_1, current_end_offset_ < offset) << "Tried to write data out of sequence. last_offset_end:" << current_end_offset_ << ", offset:" << offset; for (auto slice_it = interval_deque_.DataAt(offset); slice_it != interval_deque_.DataEnd(); ++slice_it) { if (data_length == 0 || offset < slice_it->offset) { break; } QuicByteCount slice_offset = offset - slice_it->offset; QuicByteCount available_bytes_in_slice = slice_it->slice.length() - slice_offset; QuicByteCount copy_length = std::min(data_length, available_bytes_in_slice); if (!writer->WriteBytes(slice_it->slice.data() + slice_offset, copy_length)) { QUIC_BUG(quic_bug_10853_2) << "Writer fails to write."; return false; } offset += copy_length; data_length -= copy_length; const QuicStreamOffset new_end = slice_it->offset + slice_it->slice.length(); current_end_offset_ = std::max(current_end_offset_, new_end); } return data_length == 0; } bool QuicStreamSendBuffer::OnStreamDataAcked( QuicStreamOffset offset, QuicByteCount data_length, QuicByteCount* newly_acked_length) { *newly_acked_length = 0; if (data_length == 0) { return true; } if (bytes_acked_.Empty() || offset >= bytes_acked_.rbegin()->max() || bytes_acked_.IsDisjoint( QuicInterval<QuicStreamOffset>(offset, offset + data_length))) { if (stream_bytes_outstanding_ < data_length) { return false; } bytes_acked_.AddOptimizedForAppend(offset, offset + data_length); *newly_acked_length = data_length; stream_bytes_outstanding_ -= data_length; pending_retransmissions_.Difference(offset, offset + data_length); if (!FreeMemSlices(offset, offset + data_length)) { return false; } CleanUpBufferedSlices(); return true; } if (bytes_acked_.Contains(offset, offset + data_length)) { return true; } QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(bytes_acked_); for (const auto& interval : newly_acked) { *newly_acked_length += (interval.max() - interval.min()); } if (stream_bytes_outstanding_ < *newly_acked_length) { return false; } stream_bytes_outstanding_ -= *newly_acked_length; bytes_acked_.Add(offset, offset + data_length); pending_retransmissions_.Difference(offset, offset + data_length); if (newly_acked.Empty()) { return true; } if (!FreeMemSlices(newly_acked.begin()->min(), newly_acked.rbegin()->max())) { return false; } CleanUpBufferedSlices(); return true; } void QuicStreamSendBuffer::OnStreamDataLost(QuicStreamOffset offset, QuicByteCount data_length) { if (data_length == 0) { return; } QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length); bytes_lost.Difference(bytes_acked_); if (bytes_lost.Empty()) { return; } for (const auto& lost : bytes_lost) { pending_retransmissions_.Add(lost.min(), lost.max()); } } void QuicStreamSendBuffer::OnStreamDataRetransmitted( QuicStreamOffset offset, QuicByteCount data_length) { if (data_length == 0) { return; } pending_retransmissions_.Difference(offset, offset + data_length); } bool QuicStreamSendBuffer::HasPendingRetransmission() const { return !pending_retransmissions_.Empty(); } StreamPendingRetransmission QuicStreamSendBuffer::NextPendingRetransmission() const { if (HasPendingRetransmission()) { const auto pending = pending_retransmissions_.begin(); return {pending->min(), pending->max() - pending->min()}; } QUIC_BUG(quic_bug_10853_3) << "NextPendingRetransmission is called unexpected with no " "pending retransmissions."; return {0, 0}; } bool QuicStreamSendBuffer::FreeMemSlices(QuicStreamOffset start, QuicStreamOffset end) { auto it = interval_deque_.DataBegin(); if (it == interval_deque_.DataEnd() || it->slice.empty()) { QUIC_BUG(quic_bug_10853_4) << "Trying to ack stream data [" << start << ", " << end << "), " << (it == interval_deque_.DataEnd() ? "and there is no outstanding data." : "and the first slice is empty."); return false; } if (!it->interval().Contains(start)) { it = std::lower_bound(interval_deque_.DataBegin(), interval_deque_.DataEnd(), start, CompareOffset()); } if (it == interval_deque_.DataEnd() || it->slice.empty()) { QUIC_BUG(quic_bug_10853_5) << "Offset " << start << " with iterator offset: " << it->offset << (it == interval_deque_.DataEnd() ? " does not exist." : " has already been acked."); return false; } for (; it != interval_deque_.DataEnd(); ++it) { if (it->offset >= end) { break; } if (!it->slice.empty() && bytes_acked_.Contains(it->offset, it->offset + it->slice.length())) { it->slice.Reset(); } } return true; } void QuicStreamSendBuffer::CleanUpBufferedSlices() { while (!interval_deque_.Empty() && interval_deque_.DataBegin()->slice.empty()) { QUIC_BUG_IF(quic_bug_12823_2, interval_deque_.DataBegin()->offset > current_end_offset_) << "Fail to pop front from interval_deque_. Front element contained " "a slice whose data has not all be written. Front offset " << interval_deque_.DataBegin()->offset << " length " << interval_deque_.DataBegin()->slice.length(); interval_deque_.PopFront(); } } bool QuicStreamSendBuffer::IsStreamDataOutstanding( QuicStreamOffset offset, QuicByteCount data_length) const { return data_length > 0 && !bytes_acked_.Contains(offset, offset + data_length); } size_t QuicStreamSendBuffer::size() const { return interval_deque_.Size(); } }
#include "quiche/quic/core/quic_stream_send_buffer.h" #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_send_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace test { namespace { class QuicStreamSendBufferTest : public QuicTest { public: QuicStreamSendBufferTest() : send_buffer_(&allocator_) { EXPECT_EQ(0u, send_buffer_.size()); EXPECT_EQ(0u, send_buffer_.stream_bytes_written()); EXPECT_EQ(0u, send_buffer_.stream_bytes_outstanding()); EXPECT_EQ(0u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); std::string data1 = absl::StrCat( std::string(1536, 'a'), std::string(256, 'b'), std::string(256, 'c')); quiche::QuicheBuffer buffer1(&allocator_, 1024); memset(buffer1.data(), 'c', buffer1.size()); quiche::QuicheMemSlice slice1(std::move(buffer1)); quiche::QuicheBuffer buffer2(&allocator_, 768); memset(buffer2.data(), 'd', buffer2.size()); quiche::QuicheMemSlice slice2(std::move(buffer2)); SetQuicFlag(quic_send_buffer_max_data_slice_size, 1024); send_buffer_.SaveStreamData(data1); send_buffer_.SaveMemSlice(std::move(slice1)); EXPECT_TRUE(slice1.empty()); send_buffer_.SaveMemSlice(std::move(slice2)); EXPECT_TRUE(slice2.empty()); EXPECT_EQ(4u, send_buffer_.size()); } void WriteAllData() { char buf[4000]; QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER); send_buffer_.WriteStreamData(0, 3840u, &writer); send_buffer_.OnStreamDataConsumed(3840u); EXPECT_EQ(3840u, send_buffer_.stream_bytes_written()); EXPECT_EQ(3840u, send_buffer_.stream_bytes_outstanding()); } quiche::SimpleBufferAllocator allocator_; QuicStreamSendBuffer send_buffer_; }; TEST_F(QuicStreamSendBufferTest, CopyDataToBuffer) { char buf[4000]; QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER); std::string copy1(1024, 'a'); std::string copy2 = std::string(512, 'a') + std::string(256, 'b') + std::string(256, 'c'); std::string copy3(1024, 'c'); std::string copy4(768, 'd'); ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer)); EXPECT_EQ(copy1, absl::string_view(buf, 1024)); ASSERT_TRUE(send_buffer_.WriteStreamData(1024, 1024, &writer)); EXPECT_EQ(copy2, absl::string_view(buf + 1024, 1024)); ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 1024, &writer)); EXPECT_EQ(copy3, absl::string_view(buf + 2048, 1024)); ASSERT_TRUE(send_buffer_.WriteStreamData(3072, 768, &writer)); EXPECT_EQ(copy4, absl::string_view(buf + 3072, 768)); QuicDataWriter writer2(4000, buf, quiche::HOST_BYTE_ORDER); std::string copy5 = std::string(536, 'a') + std::string(256, 'b') + std::string(232, 'c'); ASSERT_TRUE(send_buffer_.WriteStreamData(1000, 1024, &writer2)); EXPECT_EQ(copy5, absl::string_view(buf, 1024)); ASSERT_TRUE(send_buffer_.WriteStreamData(2500, 1024, &writer2)); std::string copy6 = std::string(572, 'c') + std::string(452, 'd'); EXPECT_EQ(copy6, absl::string_view(buf + 1024, 1024)); QuicDataWriter writer3(4000, buf, quiche::HOST_BYTE_ORDER); EXPECT_FALSE(send_buffer_.WriteStreamData(3000, 1024, &writer3)); EXPECT_QUIC_BUG(send_buffer_.WriteStreamData(0, 4000, &writer3), "Writer fails to write."); send_buffer_.OnStreamDataConsumed(3840); EXPECT_EQ(3840u, send_buffer_.stream_bytes_written()); EXPECT_EQ(3840u, send_buffer_.stream_bytes_outstanding()); } TEST_F(QuicStreamSendBufferTest, WriteStreamDataContainsBothRetransmissionAndNewData) { std::string copy1(1024, 'a'); std::string copy2 = std::string(512, 'a') + std::string(256, 'b') + std::string(256, 'c'); std::string copy3 = std::string(1024, 'c') + std::string(100, 'd'); char buf[6000]; QuicDataWriter writer(6000, buf, quiche::HOST_BYTE_ORDER); EXPECT_EQ(0, QuicStreamSendBufferPeer::write_index(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer)); EXPECT_EQ(copy1, absl::string_view(buf, 1024)); EXPECT_EQ(1, QuicStreamSendBufferPeer::write_index(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(0, 2048, &writer)); EXPECT_EQ(copy1 + copy2, absl::string_view(buf + 1024, 2048)); EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 50, &writer)); EXPECT_EQ(std::string(50, 'c'), absl::string_view(buf + 1024 + 2048, 50)); EXPECT_EQ(3072u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 1124, &writer)); EXPECT_EQ(copy3, absl::string_view(buf + 1024 + 2048 + 50, 1124)); EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); } TEST_F(QuicStreamSendBufferTest, RemoveStreamFrame) { WriteAllData(); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1024, 1024, &newly_acked_length)); EXPECT_EQ(1024u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2048, 1024, &newly_acked_length)); EXPECT_EQ(1024u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1024, &newly_acked_length)); EXPECT_EQ(1024u, newly_acked_length); EXPECT_EQ(1u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(3072, 768, &newly_acked_length)); EXPECT_EQ(768u, newly_acked_length); EXPECT_EQ(0u, send_buffer_.size()); } TEST_F(QuicStreamSendBufferTest, RemoveStreamFrameAcrossBoundries) { WriteAllData(); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2024, 576, &newly_acked_length)); EXPECT_EQ(576u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1000, &newly_acked_length)); EXPECT_EQ(1000u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1000, 1024, &newly_acked_length)); EXPECT_EQ(1024u, newly_acked_length); EXPECT_EQ(2u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2600, 1024, &newly_acked_length)); EXPECT_EQ(1024u, newly_acked_length); EXPECT_EQ(1u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(3624, 216, &newly_acked_length)); EXPECT_EQ(216u, newly_acked_length); EXPECT_EQ(0u, send_buffer_.size()); } TEST_F(QuicStreamSendBufferTest, AckStreamDataMultipleTimes) { WriteAllData(); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(100, 1500, &newly_acked_length)); EXPECT_EQ(1500u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2000, 500, &newly_acked_length)); EXPECT_EQ(500u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 2600, &newly_acked_length)); EXPECT_EQ(600u, newly_acked_length); EXPECT_EQ(2u, send_buffer_.size()); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2200, 1640, &newly_acked_length)); EXPECT_EQ(1240u, newly_acked_length); EXPECT_EQ(0u, send_buffer_.size()); EXPECT_FALSE(send_buffer_.OnStreamDataAcked(4000, 100, &newly_acked_length)); } TEST_F(QuicStreamSendBufferTest, AckStreamDataOutOfOrder) { WriteAllData(); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(500, 1000, &newly_acked_length)); EXPECT_EQ(1000u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_EQ(3840u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_)); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1200, 1000, &newly_acked_length)); EXPECT_EQ(700u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_EQ(2816u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_)); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2000, 1840, &newly_acked_length)); EXPECT_EQ(1640u, newly_acked_length); EXPECT_EQ(4u, send_buffer_.size()); EXPECT_EQ(1024u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_)); EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1000, &newly_acked_length)); EXPECT_EQ(500u, newly_acked_length); EXPECT_EQ(0u, send_buffer_.size()); EXPECT_EQ(0u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_)); } TEST_F(QuicStreamSendBufferTest, PendingRetransmission) { WriteAllData(); EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(0, 3840)); EXPECT_FALSE(send_buffer_.HasPendingRetransmission()); send_buffer_.OnStreamDataLost(0, 1200); send_buffer_.OnStreamDataLost(1500, 500); EXPECT_TRUE(send_buffer_.HasPendingRetransmission()); EXPECT_EQ(StreamPendingRetransmission(0, 1200), send_buffer_.NextPendingRetransmission()); send_buffer_.OnStreamDataRetransmitted(0, 500); EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(0, 500)); EXPECT_EQ(StreamPendingRetransmission(500, 700), send_buffer_.NextPendingRetransmission()); QuicByteCount newly_acked_length = 0; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(500, 700, &newly_acked_length)); EXPECT_FALSE(send_buffer_.IsStreamDataOutstanding(500, 700)); EXPECT_TRUE(send_buffer_.HasPendingRetransmission()); EXPECT_EQ(StreamPendingRetransmission(1500, 500), send_buffer_.NextPendingRetransmission()); send_buffer_.OnStreamDataRetransmitted(1500, 500); EXPECT_FALSE(send_buffer_.HasPendingRetransmission()); send_buffer_.OnStreamDataLost(200, 600); EXPECT_TRUE(send_buffer_.HasPendingRetransmission()); EXPECT_EQ(StreamPendingRetransmission(200, 300), send_buffer_.NextPendingRetransmission()); EXPECT_FALSE(send_buffer_.IsStreamDataOutstanding(100, 0)); EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(400, 800)); } TEST_F(QuicStreamSendBufferTest, EndOffset) { char buf[4000]; QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER); EXPECT_EQ(1024u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer)); EXPECT_EQ(1024u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); ASSERT_TRUE(send_buffer_.WriteStreamData(1024, 512, &writer)); EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); send_buffer_.OnStreamDataConsumed(1024); QuicByteCount newly_acked_length; EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1024, &newly_acked_length)); EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); ASSERT_TRUE( send_buffer_.WriteStreamData(1024 + 512, 3840 - 1024 - 512, &writer)); EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); quiche::QuicheBuffer buffer(&allocator_, 60); memset(buffer.data(), 'e', buffer.size()); quiche::QuicheMemSlice slice(std::move(buffer)); send_buffer_.SaveMemSlice(std::move(slice)); EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_)); } TEST_F(QuicStreamSendBufferTest, SaveMemSliceSpan) { quiche::SimpleBufferAllocator allocator; QuicStreamSendBuffer send_buffer(&allocator); std::string data(1024, 'a'); std::vector<quiche::QuicheMemSlice> buffers; for (size_t i = 0; i < 10; ++i) { buffers.push_back(MemSliceFromString(data)); } EXPECT_EQ(10 * 1024u, send_buffer.SaveMemSliceSpan(absl::MakeSpan(buffers))); EXPECT_EQ(10u, send_buffer.size()); } TEST_F(QuicStreamSendBufferTest, SaveEmptyMemSliceSpan) { quiche::SimpleBufferAllocator allocator; QuicStreamSendBuffer send_buffer(&allocator); std::string data(1024, 'a'); std::vector<quiche::QuicheMemSlice> buffers; for (size_t i = 0; i < 10; ++i) { buffers.push_back(MemSliceFromString(data)); } EXPECT_EQ(10 * 1024u, send_buffer.SaveMemSliceSpan(absl::MakeSpan(buffers))); EXPECT_EQ(10u, send_buffer.size()); } } } }
255
cpp
google/quiche
quic_unacked_packet_map
quiche/quic/core/quic_unacked_packet_map.cc
quiche/quic/core/quic_unacked_packet_map_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_UNACKED_PACKET_MAP_H_ #define QUICHE_QUIC_CORE_QUIC_UNACKED_PACKET_MAP_H_ #include <cstddef> #include <cstdint> #include "absl/container/inlined_vector.h" #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_transmission_info.h" #include "quiche/quic/core/session_notifier_interface.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class QuicUnackedPacketMapPeer; } class QUICHE_EXPORT QuicUnackedPacketMap { public: QuicUnackedPacketMap(Perspective perspective); QuicUnackedPacketMap(const QuicUnackedPacketMap&) = delete; QuicUnackedPacketMap& operator=(const QuicUnackedPacketMap&) = delete; ~QuicUnackedPacketMap(); void AddSentPacket(SerializedPacket* mutable_packet, TransmissionType transmission_type, QuicTime sent_time, bool set_in_flight, bool measure_rtt, QuicEcnCodepoint ecn_codepoint); bool IsUnacked(QuicPacketNumber packet_number) const; bool NotifyFramesAcked(const QuicTransmissionInfo& info, QuicTime::Delta ack_delay, QuicTime receive_timestamp); void NotifyFramesLost(const QuicTransmissionInfo& info, TransmissionType type); bool RetransmitFrames(const QuicFrames& frames, TransmissionType type); void RemoveFromInFlight(QuicTransmissionInfo* info); void RemoveFromInFlight(QuicPacketNumber packet_number); absl::InlinedVector<QuicPacketNumber, 2> NeuterUnencryptedPackets(); absl::InlinedVector<QuicPacketNumber, 2> NeuterHandshakePackets(); bool HasRetransmittableFrames(QuicPacketNumber packet_number) const; bool HasRetransmittableFrames(const QuicTransmissionInfo& info) const; bool HasUnackedRetransmittableFrames() const; bool empty() const { return unacked_packets_.empty(); } QuicPacketNumber largest_sent_packet() const { return largest_sent_packet_; } QuicPacketNumber largest_sent_largest_acked() const { return largest_sent_largest_acked_; } QuicPacketNumber largest_acked() const { return largest_acked_; } QuicByteCount bytes_in_flight() const { return bytes_in_flight_; } QuicPacketCount packets_in_flight() const { return packets_in_flight_; } QuicPacketNumber GetLeastUnacked() const; using const_iterator = quiche::QuicheCircularDeque<QuicTransmissionInfo>::const_iterator; using const_reverse_iterator = quiche::QuicheCircularDeque<QuicTransmissionInfo>::const_reverse_iterator; using iterator = quiche::QuicheCircularDeque<QuicTransmissionInfo>::iterator; const_iterator begin() const { return unacked_packets_.begin(); } const_iterator end() const { return unacked_packets_.end(); } const_reverse_iterator rbegin() const { return unacked_packets_.rbegin(); } const_reverse_iterator rend() const { return unacked_packets_.rend(); } iterator begin() { return unacked_packets_.begin(); } iterator end() { return unacked_packets_.end(); } bool HasInFlightPackets() const; const QuicTransmissionInfo& GetTransmissionInfo( QuicPacketNumber packet_number) const; QuicTransmissionInfo* GetMutableTransmissionInfo( QuicPacketNumber packet_number); QuicTime GetLastInFlightPacketSentTime() const; QuicTime GetLastCryptoPacketSentTime() const; size_t GetNumUnackedPacketsDebugOnly() const; bool HasMultipleInFlightPackets() const; bool HasPendingCryptoPackets() const; bool HasUnackedStreamData() const { return session_notifier_->HasUnackedStreamData(); } void RemoveRetransmittability(QuicTransmissionInfo* info); void RemoveRetransmittability(QuicPacketNumber packet_number); void IncreaseLargestAcked(QuicPacketNumber largest_acked); void MaybeUpdateLargestAckedOfPacketNumberSpace( PacketNumberSpace packet_number_space, QuicPacketNumber packet_number); void RemoveObsoletePackets(); void MaybeAggregateAckedStreamFrame(const QuicTransmissionInfo& info, QuicTime::Delta ack_delay, QuicTime receive_timestamp); void NotifyAggregatedStreamFrameAcked(QuicTime::Delta ack_delay); PacketNumberSpace GetPacketNumberSpace(QuicPacketNumber packet_number) const; PacketNumberSpace GetPacketNumberSpace( EncryptionLevel encryption_level) const; QuicPacketNumber GetLargestAckedOfPacketNumberSpace( PacketNumberSpace packet_number_space) const; QuicPacketNumber GetLargestSentRetransmittableOfPacketNumberSpace( PacketNumberSpace packet_number_space) const; QuicPacketNumber GetLargestSentPacketOfPacketNumberSpace( EncryptionLevel encryption_level) const; QuicTime GetLastInFlightPacketSentTime( PacketNumberSpace packet_number_space) const; const QuicTransmissionInfo* GetFirstInFlightTransmissionInfo() const; const QuicTransmissionInfo* GetFirstInFlightTransmissionInfoOfSpace( PacketNumberSpace packet_number_space) const; void SetSessionNotifier(SessionNotifierInterface* session_notifier); void EnableMultiplePacketNumberSpacesSupport(); int32_t GetLastPacketContent() const; Perspective perspective() const { return perspective_; } bool supports_multiple_packet_number_spaces() const { return supports_multiple_packet_number_spaces_; } void ReserveInitialCapacity(size_t initial_capacity) { unacked_packets_.reserve(initial_capacity); } std::string DebugString() const { return absl::StrCat( "{size: ", unacked_packets_.size(), ", least_unacked: ", least_unacked_.ToString(), ", largest_sent_packet: ", largest_sent_packet_.ToString(), ", largest_acked: ", largest_acked_.ToString(), ", bytes_in_flight: ", bytes_in_flight_, ", packets_in_flight: ", packets_in_flight_, "}"); } private: friend class test::QuicUnackedPacketMapPeer; bool IsPacketUsefulForMeasuringRtt(QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const; bool IsPacketUsefulForCongestionControl( const QuicTransmissionInfo& info) const; bool IsPacketUsefulForRetransmittableData( const QuicTransmissionInfo& info) const; bool IsPacketUseless(QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const; const Perspective perspective_; QuicPacketNumber largest_sent_packet_; QuicPacketNumber largest_sent_retransmittable_packets_[NUM_PACKET_NUMBER_SPACES]; QuicPacketNumber largest_sent_largest_acked_; QuicPacketNumber largest_acked_; QuicPacketNumber largest_acked_packets_[NUM_PACKET_NUMBER_SPACES]; quiche::QuicheCircularDeque<QuicTransmissionInfo> unacked_packets_; QuicPacketNumber least_unacked_; QuicByteCount bytes_in_flight_; QuicByteCount bytes_in_flight_per_packet_number_space_[NUM_PACKET_NUMBER_SPACES]; QuicPacketCount packets_in_flight_; QuicTime last_inflight_packet_sent_time_; QuicTime last_inflight_packets_sent_time_[NUM_PACKET_NUMBER_SPACES]; QuicTime last_crypto_packet_sent_time_; QuicStreamFrame aggregated_stream_frame_; SessionNotifierInterface* session_notifier_; bool supports_multiple_packet_number_spaces_; bool simple_inflight_time_; }; } #endif #include "quiche/quic/core/quic_unacked_packet_map.h" #include <cstddef> #include <limits> #include <type_traits> #include <utility> #include "absl/container/inlined_vector.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" namespace quic { namespace { bool WillStreamFrameLengthSumWrapAround(QuicPacketLength lhs, QuicPacketLength rhs) { static_assert( std::is_unsigned<QuicPacketLength>::value, "This function assumes QuicPacketLength is an unsigned integer type."); return std::numeric_limits<QuicPacketLength>::max() - lhs < rhs; } enum QuicFrameTypeBitfield : uint32_t { kInvalidFrameBitfield = 0, kPaddingFrameBitfield = 1, kRstStreamFrameBitfield = 1 << 1, kConnectionCloseFrameBitfield = 1 << 2, kGoawayFrameBitfield = 1 << 3, kWindowUpdateFrameBitfield = 1 << 4, kBlockedFrameBitfield = 1 << 5, kStopWaitingFrameBitfield = 1 << 6, kPingFrameBitfield = 1 << 7, kCryptoFrameBitfield = 1 << 8, kHandshakeDoneFrameBitfield = 1 << 9, kStreamFrameBitfield = 1 << 10, kAckFrameBitfield = 1 << 11, kMtuDiscoveryFrameBitfield = 1 << 12, kNewConnectionIdFrameBitfield = 1 << 13, kMaxStreamsFrameBitfield = 1 << 14, kStreamsBlockedFrameBitfield = 1 << 15, kPathResponseFrameBitfield = 1 << 16, kPathChallengeFrameBitfield = 1 << 17, kStopSendingFrameBitfield = 1 << 18, kMessageFrameBitfield = 1 << 19, kNewTokenFrameBitfield = 1 << 20, kRetireConnectionIdFrameBitfield = 1 << 21, kAckFrequencyFrameBitfield = 1 << 22, kResetStreamAtFrameBitfield = 1 << 23, }; QuicFrameTypeBitfield GetFrameTypeBitfield(QuicFrameType type) { switch (type) { case PADDING_FRAME: return kPaddingFrameBitfield; case RST_STREAM_FRAME: return kRstStreamFrameBitfield; case CONNECTION_CLOSE_FRAME: return kConnectionCloseFrameBitfield; case GOAWAY_FRAME: return kGoawayFrameBitfield; case WINDOW_UPDATE_FRAME: return kWindowUpdateFrameBitfield; case BLOCKED_FRAME: return kBlockedFrameBitfield; case STOP_WAITING_FRAME: return kStopWaitingFrameBitfield; case PING_FRAME: return kPingFrameBitfield; case CRYPTO_FRAME: return kCryptoFrameBitfield; case HANDSHAKE_DONE_FRAME: return kHandshakeDoneFrameBitfield; case STREAM_FRAME: return kStreamFrameBitfield; case ACK_FRAME: return kAckFrameBitfield; case MTU_DISCOVERY_FRAME: return kMtuDiscoveryFrameBitfield; case NEW_CONNECTION_ID_FRAME: return kNewConnectionIdFrameBitfield; case MAX_STREAMS_FRAME: return kMaxStreamsFrameBitfield; case STREAMS_BLOCKED_FRAME: return kStreamsBlockedFrameBitfield; case PATH_RESPONSE_FRAME: return kPathResponseFrameBitfield; case PATH_CHALLENGE_FRAME: return kPathChallengeFrameBitfield; case STOP_SENDING_FRAME: return kStopSendingFrameBitfield; case MESSAGE_FRAME: return kMessageFrameBitfield; case NEW_TOKEN_FRAME: return kNewTokenFrameBitfield; case RETIRE_CONNECTION_ID_FRAME: return kRetireConnectionIdFrameBitfield; case ACK_FREQUENCY_FRAME: return kAckFrequencyFrameBitfield; case RESET_STREAM_AT_FRAME: return kResetStreamAtFrameBitfield; case NUM_FRAME_TYPES: QUIC_BUG(quic_bug_10518_1) << "Unexpected frame type"; return kInvalidFrameBitfield; } QUIC_BUG(quic_bug_10518_2) << "Unexpected frame type"; return kInvalidFrameBitfield; } } QuicUnackedPacketMap::QuicUnackedPacketMap(Perspective perspective) : perspective_(perspective), least_unacked_(FirstSendingPacketNumber()), bytes_in_flight_(0), bytes_in_flight_per_packet_number_space_{0, 0, 0}, packets_in_flight_(0), last_inflight_packet_sent_time_(QuicTime::Zero()), last_inflight_packets_sent_time_{ {QuicTime::Zero()}, {QuicTime::Zero()}, {QuicTime::Zero()}}, last_crypto_packet_sent_time_(QuicTime::Zero()), session_notifier_(nullptr), supports_multiple_packet_number_spaces_(false) {} QuicUnackedPacketMap::~QuicUnackedPacketMap() { for (QuicTransmissionInfo& transmission_info : unacked_packets_) { DeleteFrames(&(transmission_info.retransmittable_frames)); } } void QuicUnackedPacketMap::AddSentPacket(SerializedPacket* mutable_packet, TransmissionType transmission_type, QuicTime sent_time, bool set_in_flight, bool measure_rtt, QuicEcnCodepoint ecn_codepoint) { const SerializedPacket& packet = *mutable_packet; QuicPacketNumber packet_number = packet.packet_number; QuicPacketLength bytes_sent = packet.encrypted_length; QUIC_BUG_IF(quic_bug_12645_1, largest_sent_packet_.IsInitialized() && largest_sent_packet_ >= packet_number) << "largest_sent_packet_: " << largest_sent_packet_ << ", packet_number: " << packet_number; QUICHE_DCHECK_GE(packet_number, least_unacked_ + unacked_packets_.size()); while (least_unacked_ + unacked_packets_.size() < packet_number) { unacked_packets_.push_back(QuicTransmissionInfo()); unacked_packets_.back().state = NEVER_SENT; } const bool has_crypto_handshake = packet.has_crypto_handshake == IS_HANDSHAKE; QuicTransmissionInfo info(packet.encryption_level, transmission_type, sent_time, bytes_sent, has_crypto_handshake, packet.has_ack_frequency, ecn_codepoint); info.largest_acked = packet.largest_acked; largest_sent_largest_acked_.UpdateMax(packet.largest_acked); if (!measure_rtt) { QUIC_BUG_IF(quic_bug_12645_2, set_in_flight) << "Packet " << mutable_packet->packet_number << ", transmission type " << TransmissionTypeToString(mutable_packet->transmission_type) << ", retransmittable frames: " << QuicFramesToString(mutable_packet->retransmittable_frames) << ", nonretransmittable_frames: " << QuicFramesToString(mutable_packet->nonretransmittable_frames); info.state = NOT_CONTRIBUTING_RTT; } largest_sent_packet_ = packet_number; if (set_in_flight) { const PacketNumberSpace packet_number_space = GetPacketNumberSpace(info.encryption_level); bytes_in_flight_ += bytes_sent; bytes_in_flight_per_packet_number_space_[packet_number_space] += bytes_sent; ++packets_in_flight_; info.in_flight = true; largest_sent_retransmittable_packets_[packet_number_space] = packet_number; last_inflight_packet_sent_time_ = sent_time; last_inflight_packets_sent_time_[packet_number_space] = sent_time; } unacked_packets_.push_back(std::move(info)); if (has_crypto_handshake) { last_crypto_packet_sent_time_ = sent_time; } mutable_packet->retransmittable_frames.swap( unacked_packets_.back().retransmittable_frames); } void QuicUnackedPacketMap::RemoveObsoletePackets() { while (!unacked_packets_.empty()) { if (!IsPacketUseless(least_unacked_, unacked_packets_.front())) { break; } DeleteFrames(&unacked_packets_.front().retransmittable_frames); unacked_packets_.pop_front(); ++least_unacked_; } } bool QuicUnackedPacketMap::HasRetransmittableFrames( QuicPacketNumber packet_number) const { QUICHE_DCHECK_GE(packet_number, least_unacked_); QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size()); return HasRetransmittableFrames( unacked_packets_[packet_number - least_unacked_]); } bool QuicUnackedPacketMap::HasRetransmittableFrames( const QuicTransmissionInfo& info) const { if (!QuicUtils::IsAckable(info.state)) { return false; } for (const auto& frame : info.retransmittable_frames) { if (session_notifier_->IsFrameOutstanding(frame)) { return true; } } return false; } void QuicUnackedPacketMap::RemoveRetransmittability( QuicTransmissionInfo* info) { DeleteFrames(&info->retransmittable_frames); info->first_sent_after_loss.Clear(); } void QuicUnackedPacketMap::RemoveRetransmittability( QuicPacketNumber packet_number) { QUICHE_DCHECK_GE(packet_number, least_unacked_); QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size()); QuicTransmissionInfo* info = &unacked_packets_[packet_number - least_unacked_]; RemoveRetransmittability(info); } void QuicUnackedPacketMap::IncreaseLargestAcked( QuicPacketNumber largest_acked) { QUICHE_DCHECK(!largest_acked_.IsInitialized() || largest_acked_ <= largest_acked); largest_acked_ = largest_acked; } void QuicUnackedPacketMap::MaybeUpdateLargestAckedOfPacketNumberSpace( PacketNumberSpace packet_number_space, QuicPacketNumber packet_number) { largest_acked_packets_[packet_number_space].UpdateMax(packet_number); } bool QuicUnackedPacketMap::IsPacketUsefulForMeasuringRtt( QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const { return QuicUtils::IsAckable(info.state) && (!largest_acked_.IsInitialized() || packet_number > largest_acked_) && info.state != NOT_CONTRIBUTING_RTT; } bool QuicUnackedPacketMap::IsPacketUsefulForCongestionControl( const QuicTransmissionInfo& info) const { return info.in_flight; } bool QuicUnackedPacketMap::IsPacketUsefulForRetransmittableData( const QuicTransmissionInfo& info) const { return info.first_sent_after_loss.IsInitialized() && (!largest_acked_.IsInitialized() || info.first_sent_after_loss > largest_acked_); } bool QuicUnackedPacketMap::IsPacketUseless( QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const { return !IsPacketUsefulForMeasuringRtt(packet_number, info) && !IsPacketUsefulForCongestionControl(info) && !IsPacketUsefulForRetransmittableData(info); } bool QuicUnackedPacketMap::IsUnacked(QuicPacketNumber packet_number) const { if (packet_number < least_unacked_ || packet_number >= least_unacked_ + unacked_packets_.size()) { return false; } return !IsPacketUseless(packet_number, unacked_packets_[packet_number - least_unacked_]); } void QuicUnackedPacketMap::RemoveFromInFlight(QuicTransmissionInfo* info) { if (info->in_flight) { QUIC_BUG_IF(quic_bug_12645_3, bytes_in_flight_ < info->bytes_sent); QUIC_BUG_IF(quic_bug_12645_4, packets_in_flight_ == 0); bytes_in_flight_ -= info->bytes_sent; --packets_in_flight_; const PacketNumberSpace packet_number_space = GetPacketNumberSpace(info->encryption_level); if (bytes_in_flight_per_packet_number_space_[packet_number_space] < info->bytes_sent) { QUIC_BUG(quic_bug_10518_3) << "bytes_in_flight: " << bytes_in_flight_per_packet_number_space_[packet_number_space] << " is smaller than bytes_sent: " << info->bytes_sent << " for packet number space: " << PacketNumberSpaceToString(packet_number_space); bytes_in_flight_per_packet_number_space_[packet_number_space] = 0; } else { bytes_in_flight_per_packet_number_space_[packet_number_space] -= info->bytes_sent; } if (bytes_in_flight_per_packet_number_space_[packet_number_space] == 0) { last_inflight_packets_sent_time_[packet_number_space] = QuicTime::Zero(); } info->in_flight = false; } } void QuicUnackedPacketMap::RemoveFromInFlight(QuicPacketNumber packet_number) { QUICHE_DCHECK_GE(packet_number, least_unacked_); QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size()); QuicTransmissionInfo* info = &unacked_packets_[packet_number - least_unacked_]; RemoveFromInFlight(info); } absl::InlinedVector<QuicPacketNumber, 2> QuicUnackedPacketMap::NeuterUnencryptedPackets() { absl::InlinedVector<QuicPacketNumber, 2> neutered_packets; QuicPacketNumber packet_number = GetLeastUnacked(); for (QuicUnackedPacketMap::iterator it = begin(); it != end(); ++it, ++packet_number) { if (!it->retransmittable_frames.empty() && it->encryption_level == ENCRYPTION_INITIAL) { QUIC_DVLOG(2) << "Neutering unencrypted packet " << packet_number; RemoveFromInFlight(packet_number); it->state = NEUTERED; neutered_packets.push_back(packet_number); NotifyFramesAcked(*it, QuicTime::Delta::Zero(), QuicTime::Zero()); QUICHE_DCHECK(!HasRetransmittableFrames(*it)); } } QUICHE_DCHECK(!supports_multiple_packet_number_spaces_ || last_inflight_packets_sent_time_[INITIAL_DATA] == QuicTime::Zero()); return neutered_packets; } absl::InlinedVector<QuicPacketNumber, 2> QuicUnackedPacketMap::NeuterHandshakePackets() { absl::InlinedVector<QuicPacketNumber, 2> neutered_packets; QuicPacketNumber packet_number = GetLeastUnacked(); for (QuicUnackedPacketMap::iterator it = begin(); it != end(); ++it, ++packet_number) { if (!it->retransmittable_frames.empty() && GetPacketNumberSpace(it->encryption_level) == HANDSHAKE_DATA) { QUIC_DVLOG(2) << "Neutering handshake packet " << packet_number; RemoveFromInFlight(packet_number); it->state = NEUTERED; neutered_packets.push_back(packet_number); NotifyFramesAcked(*it, QuicTime::Delta::Zero(), QuicTime::Zero()); } } QUICHE_DCHECK(!supports_multiple_packet_number_spaces() || last_inflight_packets_sent_time_[HANDSHAKE_DATA] == QuicTime::Zero()); return neutered_packets; } bool QuicUnackedPacketMap::HasInFlightPackets() const { return bytes_in_flight_ > 0; } const QuicTransmissionInfo& QuicUnackedPacketMap::GetTransmissionInfo( QuicPacketNumber packet_number) const { return unacked_packets_[packet_number - least_unacked_]; } QuicTransmissionInfo* QuicUnackedPacketMap::GetMutableTransmissionInfo( QuicPacketNumber packet_number) { return &unacked_packets_[packet_number - least_unacked_]; } QuicTime QuicUnackedPacketMap::GetLastInFlightPacketSentTime() const { return last_inflight_packet_sent_time_; } QuicTime QuicUnackedPacketMap::GetLastCryptoPacketSentTime() const { return last_crypto_packet_sent_time_; } size_t QuicUnackedPacketMap::GetNumUnackedPacketsDebugOnly() const { size_t unacked_packet_count = 0; QuicPacketNumber packet_number = least_unacked_; for (auto it = begin(); it != end(); ++it, ++packet_number) { if (!IsPacketUseless(packet_number, *it)) { ++unacked_packet_count; } } return unacked_packet_count; } bool QuicUnackedPacketMap::HasMultipleInFlightPackets() const { if (bytes_in_flight_ > kDefaultTCPMSS) { return true; } size_t num_in_flight = 0; for (auto it = rbegin(); it != rend(); ++it) { if (it->in_flight) { ++num_in_flight; } if (num_in_flight > 1) { return true; } } return false; } bool QuicUnackedPacketMap::HasPendingCryptoPackets() const { return session_notifier_->HasUnackedCryptoData(); } bool QuicUnackedPacketMap::HasUnackedRetransmittableFrames() const { for (auto it = rbegin(); it != rend(); ++it) { if (it->in_flight && HasRetransmittableFrames(*it)) { return true; } } return false; } QuicPacketNumber QuicUnackedPacketMap::GetLeastUnacked() const { return least_unacked_; } void QuicUnackedPacketMap::SetSessionNotifier( SessionNotifierInterface* session_notifier) { session_notifier_ = session_notifier; } bool QuicUnackedPacketMap::NotifyFramesAcked(const QuicTransmissionInfo& info, QuicTime::Delta ack_delay, QuicTime receive_timestamp) { if (session_notifier_ == nullptr) { return false; } bool new_data_acked = false; for (const QuicFrame& frame : info.retransmittable_frames) { if (session_notifier_->OnFrameAcked(frame, ack_delay, receive_timestamp)) { new_data_acked = true; } } return new_data_acked; } void QuicUnackedPacketMap::NotifyFramesLost(const QuicTransmissionInfo& info, TransmissionType ) { for (const QuicFrame& frame : info.retransmittable_frames) { session_notifier_->OnFrameLost(frame); } } bool QuicUnackedPacketMap::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { return session_notifier_->RetransmitFrames(frames, type); } void QuicUnackedPacketMap::MaybeAggregateAckedStreamFrame( const QuicTransmissionInfo& info, QuicTime::Delta ack_delay, QuicTime receive_timestamp) { if (session_notifier_ == nullptr) { return; } for (const auto& frame : info.retransmittable_frames) { const bool can_aggregate = frame.type == STREAM_FRAME && frame.stream_frame.stream_id == aggregated_stream_frame_.stream_id && frame.stream_frame.offset == aggregated_stream_frame_.offset + aggregat
#include "quiche/quic/core/quic_unacked_packet_map.h" #include <cstddef> #include <limits> #include <vector> #include "absl/base/macros.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_transmission_info.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/quic_unacked_packet_map_peer.h" using testing::_; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { const uint32_t kDefaultLength = 1000; class QuicUnackedPacketMapTest : public QuicTestWithParam<Perspective> { protected: QuicUnackedPacketMapTest() : unacked_packets_(GetParam()), now_(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1000)) { unacked_packets_.SetSessionNotifier(&notifier_); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(true)); EXPECT_CALL(notifier_, OnStreamFrameRetransmitted(_)) .Times(testing::AnyNumber()); } ~QuicUnackedPacketMapTest() override {} SerializedPacket CreateRetransmittablePacket(uint64_t packet_number) { return CreateRetransmittablePacketForStream( packet_number, QuicUtils::GetFirstBidirectionalStreamId( CurrentSupportedVersions()[0].transport_version, Perspective::IS_CLIENT)); } SerializedPacket CreateRetransmittablePacketForStream( uint64_t packet_number, QuicStreamId stream_id) { SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); QuicStreamFrame frame; frame.stream_id = stream_id; packet.retransmittable_frames.push_back(QuicFrame(frame)); return packet; } SerializedPacket CreateNonRetransmittablePacket(uint64_t packet_number) { return SerializedPacket(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); } void VerifyInFlightPackets(uint64_t* packets, size_t num_packets) { unacked_packets_.RemoveObsoletePackets(); if (num_packets == 0) { EXPECT_FALSE(unacked_packets_.HasInFlightPackets()); EXPECT_FALSE(unacked_packets_.HasMultipleInFlightPackets()); return; } if (num_packets == 1) { EXPECT_TRUE(unacked_packets_.HasInFlightPackets()); EXPECT_FALSE(unacked_packets_.HasMultipleInFlightPackets()); ASSERT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[0]))); EXPECT_TRUE( unacked_packets_.GetTransmissionInfo(QuicPacketNumber(packets[0])) .in_flight); } for (size_t i = 0; i < num_packets; ++i) { ASSERT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[i]))); EXPECT_TRUE( unacked_packets_.GetTransmissionInfo(QuicPacketNumber(packets[i])) .in_flight); } size_t in_flight_count = 0; for (auto it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { if (it->in_flight) { ++in_flight_count; } } EXPECT_EQ(num_packets, in_flight_count); } void VerifyUnackedPackets(uint64_t* packets, size_t num_packets) { unacked_packets_.RemoveObsoletePackets(); if (num_packets == 0) { EXPECT_TRUE(unacked_packets_.empty()); EXPECT_FALSE(unacked_packets_.HasUnackedRetransmittableFrames()); return; } EXPECT_FALSE(unacked_packets_.empty()); for (size_t i = 0; i < num_packets; ++i) { EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[i]))) << packets[i]; } EXPECT_EQ(num_packets, unacked_packets_.GetNumUnackedPacketsDebugOnly()); } void VerifyRetransmittablePackets(uint64_t* packets, size_t num_packets) { unacked_packets_.RemoveObsoletePackets(); size_t num_retransmittable_packets = 0; for (auto it = unacked_packets_.begin(); it != unacked_packets_.end(); ++it) { if (unacked_packets_.HasRetransmittableFrames(*it)) { ++num_retransmittable_packets; } } EXPECT_EQ(num_packets, num_retransmittable_packets); for (size_t i = 0; i < num_packets; ++i) { EXPECT_TRUE(unacked_packets_.HasRetransmittableFrames( QuicPacketNumber(packets[i]))) << " packets[" << i << "]:" << packets[i]; } } void UpdatePacketState(uint64_t packet_number, SentPacketState state) { unacked_packets_ .GetMutableTransmissionInfo(QuicPacketNumber(packet_number)) ->state = state; } void RetransmitAndSendPacket(uint64_t old_packet_number, uint64_t new_packet_number, TransmissionType transmission_type) { QUICHE_DCHECK(unacked_packets_.HasRetransmittableFrames( QuicPacketNumber(old_packet_number))); QuicTransmissionInfo* info = unacked_packets_.GetMutableTransmissionInfo( QuicPacketNumber(old_packet_number)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( CurrentSupportedVersions()[0].transport_version, Perspective::IS_CLIENT); for (const auto& frame : info->retransmittable_frames) { if (frame.type == STREAM_FRAME) { stream_id = frame.stream_frame.stream_id; break; } } UpdatePacketState( old_packet_number, QuicUtils::RetransmissionTypeToPacketState(transmission_type)); info->first_sent_after_loss = QuicPacketNumber(new_packet_number); SerializedPacket packet( CreateRetransmittablePacketForStream(new_packet_number, stream_id)); unacked_packets_.AddSentPacket(&packet, transmission_type, now_, true, true, ECN_NOT_ECT); } QuicUnackedPacketMap unacked_packets_; QuicTime now_; StrictMock<MockSessionNotifier> notifier_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicUnackedPacketMapTest, ::testing::ValuesIn({Perspective::IS_CLIENT, Perspective::IS_SERVER}), ::testing::PrintToStringParamName()); TEST_P(QuicUnackedPacketMapTest, RttOnly) { SerializedPacket packet(CreateNonRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, false, true, ECN_NOT_ECT); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(nullptr, 0); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1)); VerifyUnackedPackets(nullptr, 0); VerifyInFlightPackets(nullptr, 0); VerifyRetransmittablePackets(nullptr, 0); } TEST_P(QuicUnackedPacketMapTest, RetransmittableInflightAndRtt) { SerializedPacket packet(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(unacked, ABSL_ARRAYSIZE(unacked)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(1)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); VerifyUnackedPackets(nullptr, 0); VerifyInFlightPackets(nullptr, 0); VerifyRetransmittablePackets(nullptr, 0); } TEST_P(QuicUnackedPacketMapTest, StopRetransmission) { const QuicStreamId stream_id = 2; SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id)); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); uint64_t retransmittable[] = {1}; VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); } TEST_P(QuicUnackedPacketMapTest, StopRetransmissionOnOtherStream) { const QuicStreamId stream_id = 2; SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id)); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); uint64_t retransmittable[] = {1}; VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); } TEST_P(QuicUnackedPacketMapTest, StopRetransmissionAfterRetransmission) { const QuicStreamId stream_id = 2; SerializedPacket packet1(CreateRetransmittablePacketForStream(1, stream_id)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); RetransmitAndSendPacket(1, 2, LOSS_RETRANSMISSION); uint64_t unacked[] = {1, 2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); std::vector<uint64_t> retransmittable = {1, 2}; VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size()); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); } TEST_P(QuicUnackedPacketMapTest, RetransmittedPacket) { SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); RetransmitAndSendPacket(1, 2, LOSS_RETRANSMISSION); uint64_t unacked[] = {1, 2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); std::vector<uint64_t> retransmittable = {1, 2}; VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size()); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(1)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2)); VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); uint64_t unacked2[] = {1}; VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2)); VerifyInFlightPackets(unacked2, ABSL_ARRAYSIZE(unacked2)); VerifyRetransmittablePackets(nullptr, 0); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); VerifyUnackedPackets(nullptr, 0); VerifyInFlightPackets(nullptr, 0); VerifyRetransmittablePackets(nullptr, 0); } TEST_P(QuicUnackedPacketMapTest, RetransmitThreeTimes) { SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); SerializedPacket packet2(CreateRetransmittablePacket(2)); unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked[] = {1, 2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); uint64_t retransmittable[] = {1, 2}; VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); RetransmitAndSendPacket(1, 3, LOSS_RETRANSMISSION); SerializedPacket packet4(CreateRetransmittablePacket(4)); unacked_packets_.AddSentPacket(&packet4, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked2[] = {1, 3, 4}; VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2)); uint64_t pending2[] = {3, 4}; VerifyInFlightPackets(pending2, ABSL_ARRAYSIZE(pending2)); std::vector<uint64_t> retransmittable2 = {1, 3, 4}; VerifyRetransmittablePackets(&retransmittable2[0], retransmittable2.size()); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(4)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(4)); RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION); SerializedPacket packet6(CreateRetransmittablePacket(6)); unacked_packets_.AddSentPacket(&packet6, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); std::vector<uint64_t> unacked3 = {3, 5, 6}; std::vector<uint64_t> retransmittable3 = {3, 5, 6}; VerifyUnackedPackets(&unacked3[0], unacked3.size()); VerifyRetransmittablePackets(&retransmittable3[0], retransmittable3.size()); uint64_t pending3[] = {3, 5, 6}; VerifyInFlightPackets(pending3, ABSL_ARRAYSIZE(pending3)); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(6)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(6)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(6)); RetransmitAndSendPacket(5, 7, LOSS_RETRANSMISSION); std::vector<uint64_t> unacked4 = {3, 5, 7}; std::vector<uint64_t> retransmittable4 = {3, 5, 7}; VerifyUnackedPackets(&unacked4[0], unacked4.size()); VerifyRetransmittablePackets(&retransmittable4[0], retransmittable4.size()); uint64_t pending4[] = {3, 5, 7}; VerifyInFlightPackets(pending4, ABSL_ARRAYSIZE(pending4)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(5)); uint64_t pending5[] = {7}; VerifyInFlightPackets(pending5, ABSL_ARRAYSIZE(pending5)); } TEST_P(QuicUnackedPacketMapTest, RetransmitFourTimes) { SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); SerializedPacket packet2(CreateRetransmittablePacket(2)); unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked[] = {1, 2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked)); uint64_t retransmittable[] = {1, 2}; VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); RetransmitAndSendPacket(1, 3, LOSS_RETRANSMISSION); uint64_t unacked2[] = {1, 3}; VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2)); uint64_t pending2[] = {3}; VerifyInFlightPackets(pending2, ABSL_ARRAYSIZE(pending2)); std::vector<uint64_t> retransmittable2 = {1, 3}; VerifyRetransmittablePackets(&retransmittable2[0], retransmittable2.size()); RetransmitAndSendPacket(3, 4, PTO_RETRANSMISSION); SerializedPacket packet5(CreateRetransmittablePacket(5)); unacked_packets_.AddSentPacket(&packet5, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); uint64_t unacked3[] = {1, 3, 4, 5}; VerifyUnackedPackets(unacked3, ABSL_ARRAYSIZE(unacked3)); uint64_t pending3[] = {3, 4, 5}; VerifyInFlightPackets(pending3, ABSL_ARRAYSIZE(pending3)); std::vector<uint64_t> retransmittable3 = {1, 3, 4, 5}; VerifyRetransmittablePackets(&retransmittable3[0], retransmittable3.size()); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(5)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(5)); unacked_packets_.RemoveRetransmittability(QuicPacketNumber(5)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); RetransmitAndSendPacket(4, 6, LOSS_RETRANSMISSION); std::vector<uint64_t> unacked4 = {4, 6}; VerifyUnackedPackets(&unacked4[0], unacked4.size()); uint64_t pending4[] = {6}; VerifyInFlightPackets(pending4, ABSL_ARRAYSIZE(pending4)); std::vector<uint64_t> retransmittable4 = {4, 6}; VerifyRetransmittablePackets(&retransmittable4[0], retransmittable4.size()); } TEST_P(QuicUnackedPacketMapTest, SendWithGap) { SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); SerializedPacket packet3(CreateRetransmittablePacket(3)); unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION); EXPECT_EQ(QuicPacketNumber(1u), unacked_packets_.GetLeastUnacked()); EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(1))); EXPECT_FALSE(unacked_packets_.IsUnacked(QuicPacketNumber(2))); EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(3))); EXPECT_FALSE(unacked_packets_.IsUnacked(QuicPacketNumber(4))); EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(5))); EXPECT_EQ(QuicPacketNumber(5u), unacked_packets_.largest_sent_packet()); } TEST_P(QuicUnackedPacketMapTest, AggregateContiguousAckedStreamFrames) { testing::InSequence s; EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.NotifyAggregatedStreamFrameAcked(QuicTime::Delta::Zero()); QuicTransmissionInfo info1; QuicStreamFrame stream_frame1(3, false, 0, 100); info1.retransmittable_frames.push_back(QuicFrame(stream_frame1)); QuicTransmissionInfo info2; QuicStreamFrame stream_frame2(3, false, 100, 100); info2.retransmittable_frames.push_back(QuicFrame(stream_frame2)); QuicTransmissionInfo info3; QuicStreamFrame stream_frame3(3, false, 200, 100); info3.retransmittable_frames.push_back(QuicFrame(stream_frame3)); QuicTransmissionInfo info4; QuicStreamFrame stream_frame4(3, true, 300, 0); info4.retransmittable_frames.push_back(QuicFrame(stream_frame4)); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.MaybeAggregateAckedStreamFrame( info1, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.MaybeAggregateAckedStreamFrame( info2, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.MaybeAggregateAckedStreamFrame( info3, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1); unacked_packets_.MaybeAggregateAckedStreamFrame( info4, QuicTime::Delta::Zero(), QuicTime::Zero()); } TEST_P(QuicUnackedPacketMapTest, CannotAggregateIfDataLengthOverflow) { QuicByteCount kMaxAggregatedDataLength = std::numeric_limits<decltype(QuicStreamFrame().data_length)>::max(); QuicStreamId stream_id = 2; for (const QuicPacketLength acked_stream_length : {512, 1300}) { ++stream_id; QuicStreamOffset offset = 0; QuicByteCount aggregated_data_length = 0; while (offset < 1e6) { QuicTransmissionInfo info; QuicStreamFrame stream_frame(stream_id, false, offset, acked_stream_length); info.retransmittable_frames.push_back(QuicFrame(stream_frame)); const QuicStreamFrame& aggregated_stream_frame = QuicUnackedPacketMapPeer::GetAggregatedStreamFrame(unacked_packets_); if (aggregated_stream_frame.data_length + acked_stream_length <= kMaxAggregatedDataLength) { EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.MaybeAggregateAckedStreamFrame( info, QuicTime::Delta::Zero(), QuicTime::Zero()); aggregated_data_length += acked_stream_length; testing::Mock::VerifyAndClearExpectations(&notifier_); } else { EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1); unacked_packets_.MaybeAggregateAckedStreamFrame( info, QuicTime::Delta::Zero(), QuicTime::Zero()); aggregated_data_length = acked_stream_length; testing::Mock::VerifyAndClearExpectations(&notifier_); } EXPECT_EQ(aggregated_data_length, aggregated_stream_frame.data_length); offset += acked_stream_length; } QuicTransmissionInfo info; QuicStreamFrame stream_frame(stream_id, true, offset, acked_stream_length); info.retransmittable_frames.push_back(QuicFrame(stream_frame)); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1); unacked_packets_.MaybeAggregateAckedStreamFrame( info, QuicTime::Delta::Zero(), QuicTime::Zero()); testing::Mock::VerifyAndClearExpectations(&notifier_); } } TEST_P(QuicUnackedPacketMapTest, CannotAggregateAckedControlFrames) { testing::InSequence s; QuicWindowUpdateFrame window_update(1, 5, 100); QuicStreamFrame stream_frame1(3, false, 0, 100); QuicStreamFrame stream_frame2(3, false, 100, 100); QuicBlockedFrame blocked(2, 5, 0); QuicGoAwayFrame go_away(3, QUIC_PEER_GOING_AWAY, 5, "Going away."); QuicTransmissionInfo info1; info1.retransmittable_frames.push_back(QuicFrame(window_update)); info1.retransmittable_frames.push_back(QuicFrame(stream_frame1)); info1.retransmittable_frames.push_back(QuicFrame(stream_frame2)); QuicTransmissionInfo info2; info2.retransmittable_frames.push_back(QuicFrame(blocked)); info2.retransmittable_frames.push_back(QuicFrame(&go_away)); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1); unacked_packets_.MaybeAggregateAckedStreamFrame( info1, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(3); unacked_packets_.MaybeAggregateAckedStreamFrame( info2, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0); unacked_packets_.NotifyAggregatedStreamFrameAcked(QuicTime::Delta::Zero()); } TEST_P(QuicUnackedPacketMapTest, LargestSentPacketMultiplePacketNumberSpaces) { unacked_packets_.EnableMultiplePacketNumberSpacesSupport(); EXPECT_FALSE( unacked_packets_ .GetLargestSentRetransmittableOfPacketNumberSpace(INITIAL_DATA) .IsInitialized()); SerializedPacket packet1(CreateRetransmittablePacket(1)); packet1.encryption_level = ENCRYPTION_INITIAL; unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); EXPECT_EQ(QuicPacketNumber(1u), unacked_packets_.largest_sent_packet()); EXPECT_EQ(QuicPacketNumber(1), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( INITIAL_DATA)); EXPECT_FALSE( unacked_packets_ .GetLargestSentRetransmittableOfPacketNumberSpace(HANDSHAKE_DATA) .IsInitialized()); SerializedPacket packet2(CreateRetransmittablePacket(2)); packet2.encryption_level = ENCRYPTION_HANDSHAKE; unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); EXPECT_EQ(QuicPacketNumber(2u), unacked_packets_.largest_sent_packet()); EXPECT_EQ(QuicPacketNumber(1), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( INITIAL_DATA)); EXPECT_EQ(QuicPacketNumber(2), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( HANDSHAKE_DATA)); EXPECT_FALSE( unacked_packets_ .GetLargestSentRetransmittableOfPacketNumberSpace(APPLICATION_DATA) .IsInitialized()); SerializedPacket packet3(CreateRetransmittablePacket(3)); packet3.encryption_level = ENCRYPTION_ZERO_RTT; unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); EXPECT_EQ(QuicPacketNumber(3u), unacked_packets_.largest_sent_packet()); EXPECT_EQ(QuicPacketNumber(1), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( INITIAL_DATA)); EXPECT_EQ(QuicPacketNumber(2), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( HANDSHAKE_DATA)); EXPECT_EQ(QuicPacketNumber(3), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( APPLICATION_DATA)); EXPECT_EQ(QuicPacketNumber(3), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( APPLICATION_DATA)); SerializedPacket packet4(CreateRetransmittablePacket(4)); packet4.encryption_level = ENCRYPTION_FORWARD_SECURE; unacked_packets_.AddSentPacket(&packet4, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); EXPECT_EQ(QuicPacketNumber(4u), unacked_packets_.largest_sent_packet()); EXPECT_EQ(QuicPacketNumber(1), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( INITIAL_DATA)); EXPECT_EQ(QuicPacketNumber(2), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( HANDSHAKE_DATA)); EXPECT_EQ(QuicPacketNumber(4), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( APPLICATION_DATA)); EXPECT_EQ(QuicPacketNumber(4), unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace( APPLICATION_DATA)); EXPECT_TRUE(unacked_packets_.GetLastPacketContent() & (1 << STREAM_FRAME)); EXPECT_FALSE(unacked_packets_.GetLastPacketContent() & (1 << ACK_FRAME)); } TEST_P(QuicUnackedPacketMapTest, ReserveInitialCapacityTest) { QuicUnackedPacketMap unacked_packets(GetParam()); ASSERT_EQ(QuicUnackedPacketMapPeer::GetCapacity(unacked_packets), 0u); unacked_packets.ReserveInitialCapacity(16); QuicStreamId stream_id(1); SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id)); unacked_packets.AddSentPacket(&packet, TransmissionType::NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); ASSERT_EQ(QuicUnackedPacketMapPeer::GetCapacity(unacked_packets), 16u); } TEST_P(QuicUnackedPacketMapTest, DebugString) { EXPECT_EQ(unacked_packets_.DebugString(), "{size: 0, least_unacked: 1, largest_sent_packet: uninitialized, " "largest_acked: uninitialized, bytes_in_flight: 0, " "packets_in_flight: 0}"); SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); EXPECT_EQ( unacked_packets_.DebugString(), "{size: 1, least_unacked: 1, largest_sent_packet: 1, largest_acked: " "uninitialized, bytes_in_flight: 1000, packets_in_flight: 1}"); SerializedPacket packet2(CreateRetransmittablePacket(2)); unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1)); unacked_packets_.RemoveObsoletePackets(); EXPECT_EQ( unacked_packets_.DebugString(), "{size: 1, least_unacked: 2, largest_sent_packet: 2, largest_acked: 1, " "bytes_in_flight: 1000, packets_in_flight: 1}"); } TEST_P(QuicUnackedPacketMapTest, EcnInfoStored) { SerializedPacket packet1(CreateRetransmittablePacket(1)); unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true, ECN_NOT_ECT); SerializedPacket packet2(CreateRetransmittablePacket(2)); unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true, ECN_ECT0); SerializedPacket packet3(CreateRetransmittablePacket(3)); unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true, ECN_ECT1); EXPECT_EQ( unacked_packets_.GetTransmissionInfo(QuicPacketNumber(1)).ecn_codepoint, ECN_NOT_ECT); EXPECT_EQ( unacked_packets_.GetTransmissionInfo(QuicPacketNumber(2)).ecn_codepoint, ECN_ECT0); EXPECT_EQ( unacked_packets_.GetTransmissionInfo(QuicPacketNumber(3)).ecn_codepoint, ECN_ECT1); } } } }
256
cpp
google/quiche
quic_buffered_packet_store
quiche/quic/core/quic_buffered_packet_store.cc
quiche/quic/core/quic_buffered_packet_store_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_BUFFERED_PACKET_STORE_H_ #define QUICHE_QUIC_CORE_QUIC_BUFFERED_PACKET_STORE_H_ #include <cstdint> #include <list> #include <memory> #include <optional> #include <string> #include <vector> #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_stream_send_buffer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_chlo_extractor.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { namespace test { class QuicBufferedPacketStorePeer; } class QUICHE_EXPORT QuicBufferedPacketStore { public: enum EnqueuePacketResult { SUCCESS = 0, TOO_MANY_PACKETS, TOO_MANY_CONNECTIONS }; struct QUICHE_EXPORT BufferedPacket { BufferedPacket(std::unique_ptr<QuicReceivedPacket> packet, QuicSocketAddress self_address, QuicSocketAddress peer_address); BufferedPacket(BufferedPacket&& other); BufferedPacket& operator=(BufferedPacket&& other); ~BufferedPacket(); std::unique_ptr<QuicReceivedPacket> packet; QuicSocketAddress self_address; QuicSocketAddress peer_address; }; struct QUICHE_EXPORT BufferedPacketList { BufferedPacketList(); BufferedPacketList(BufferedPacketList&& other); BufferedPacketList& operator=(BufferedPacketList&& other); ~BufferedPacketList(); std::list<BufferedPacket> buffered_packets; QuicTime creation_time; std::optional<ParsedClientHello> parsed_chlo; bool ietf_quic; ParsedQuicVersion version; TlsChloExtractor tls_chlo_extractor; ConnectionIdGeneratorInterface* connection_id_generator = nullptr; }; using BufferedPacketMap = quiche::QuicheLinkedHashMap<QuicConnectionId, BufferedPacketList, QuicConnectionIdHash>; class QUICHE_EXPORT VisitorInterface { public: virtual ~VisitorInterface() {} virtual void OnExpiredPackets(QuicConnectionId connection_id, BufferedPacketList early_arrived_packets) = 0; }; QuicBufferedPacketStore(VisitorInterface* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory); QuicBufferedPacketStore(const QuicBufferedPacketStore&) = delete; ~QuicBufferedPacketStore(); QuicBufferedPacketStore& operator=(const QuicBufferedPacketStore&) = delete; EnqueuePacketResult EnqueuePacket( const ReceivedPacketInfo& packet_info, std::optional<ParsedClientHello> parsed_chlo, ConnectionIdGeneratorInterface* connection_id_generator); bool HasBufferedPackets(QuicConnectionId connection_id) const; bool IngestPacketForTlsChloExtraction( const QuicConnectionId& connection_id, const ParsedQuicVersion& version, const QuicReceivedPacket& packet, std::vector<uint16_t>* out_supported_groups, std::vector<std::string>* out_alpns, std::string* out_sni, bool* out_resumption_attempted, bool* out_early_data_attempted, std::optional<uint8_t>* tls_alert); BufferedPacketList DeliverPackets(QuicConnectionId connection_id); void DiscardPackets(QuicConnectionId connection_id); void DiscardAllPackets(); void OnExpirationTimeout(); BufferedPacketList DeliverPacketsForNextConnection( QuicConnectionId* connection_id); bool HasChloForConnection(QuicConnectionId connection_id); bool HasChlosBuffered() const; private: friend class test::QuicBufferedPacketStorePeer; void MaybeSetExpirationAlarm(); bool ShouldNotBufferPacket(bool is_chlo); BufferedPacketMap undecryptable_packets_; const QuicTime::Delta connection_life_span_; VisitorInterface* visitor_; const QuicClock* clock_; std::unique_ptr<QuicAlarm> expiration_alarm_; quiche::QuicheLinkedHashMap<QuicConnectionId, bool, QuicConnectionIdHash> connections_with_chlo_; }; class QUICHE_NO_EXPORT PacketCollector : public QuicPacketCreator::DelegateInterface, public QuicStreamFrameDataProducer { public: explicit PacketCollector(quiche::QuicheBufferAllocator* allocator) : send_buffer_(allocator) {} ~PacketCollector() override = default; void OnSerializedPacket(SerializedPacket serialized_packet) override { packets_.emplace_back( new QuicEncryptedPacket(CopyBuffer(serialized_packet), serialized_packet.encrypted_length, true)); } QuicPacketBuffer GetPacketBuffer() override { return {nullptr, nullptr}; } void OnUnrecoverableError(QuicErrorCode , const std::string& ) override {} bool ShouldGeneratePacket(HasRetransmittableData , IsHandshake ) override { QUICHE_DCHECK(false); return true; } void MaybeBundleOpportunistically( TransmissionType ) override { QUICHE_DCHECK(false); } QuicByteCount GetFlowControlSendWindowSize(QuicStreamId ) override { QUICHE_DCHECK(false); return std::numeric_limits<QuicByteCount>::max(); } SerializedPacketFate GetSerializedPacketFate( bool , EncryptionLevel ) override { return SEND_TO_WRITER; } WriteStreamDataResult WriteStreamData(QuicStreamId , QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override { if (send_buffer_.WriteStreamData(offset, data_length, writer)) { return WRITE_SUCCESS; } return WRITE_FAILED; } bool WriteCryptoData(EncryptionLevel , QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override { return send_buffer_.WriteStreamData(offset, data_length, writer); } std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets() { return &packets_; } private: std::vector<std::unique_ptr<QuicEncryptedPacket>> packets_; QuicStreamSendBuffer send_buffer_; }; } #endif #include "quiche/quic/core/quic_buffered_packet_store.h" #include <cstddef> #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; namespace { class ConnectionExpireAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ConnectionExpireAlarm(QuicBufferedPacketStore* store) : connection_store_(store) {} void OnAlarm() override { connection_store_->OnExpirationTimeout(); } ConnectionExpireAlarm(const ConnectionExpireAlarm&) = delete; ConnectionExpireAlarm& operator=(const ConnectionExpireAlarm&) = delete; private: QuicBufferedPacketStore* connection_store_; }; } BufferedPacket::BufferedPacket(std::unique_ptr<QuicReceivedPacket> packet, QuicSocketAddress self_address, QuicSocketAddress peer_address) : packet(std::move(packet)), self_address(self_address), peer_address(peer_address) {} BufferedPacket::BufferedPacket(BufferedPacket&& other) = default; BufferedPacket& BufferedPacket::operator=(BufferedPacket&& other) = default; BufferedPacket::~BufferedPacket() {} BufferedPacketList::BufferedPacketList() : creation_time(QuicTime::Zero()), ietf_quic(false), version(ParsedQuicVersion::Unsupported()) {} BufferedPacketList::BufferedPacketList(BufferedPacketList&& other) = default; BufferedPacketList& BufferedPacketList::operator=(BufferedPacketList&& other) = default; BufferedPacketList::~BufferedPacketList() {} QuicBufferedPacketStore::QuicBufferedPacketStore( VisitorInterface* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory) : connection_life_span_( QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs)), visitor_(visitor), clock_(clock), expiration_alarm_( alarm_factory->CreateAlarm(new ConnectionExpireAlarm(this))) {} QuicBufferedPacketStore::~QuicBufferedPacketStore() { if (expiration_alarm_ != nullptr) { expiration_alarm_->PermanentCancel(); } } EnqueuePacketResult QuicBufferedPacketStore::EnqueuePacket( const ReceivedPacketInfo& packet_info, std::optional<ParsedClientHello> parsed_chlo, ConnectionIdGeneratorInterface* connection_id_generator) { QuicConnectionId connection_id = packet_info.destination_connection_id; const QuicReceivedPacket& packet = packet_info.packet; const QuicSocketAddress& self_address = packet_info.self_address; const QuicSocketAddress& peer_address = packet_info.peer_address; const ParsedQuicVersion& version = packet_info.version; const bool ietf_quic = packet_info.form != GOOGLE_QUIC_PACKET; const bool is_chlo = parsed_chlo.has_value(); QUIC_BUG_IF(quic_bug_12410_1, !GetQuicFlag(quic_allow_chlo_buffering)) << "Shouldn't buffer packets if disabled via flag."; QUIC_BUG_IF(quic_bug_12410_2, is_chlo && connections_with_chlo_.contains(connection_id)) << "Shouldn't buffer duplicated CHLO on connection " << connection_id; QUIC_BUG_IF(quic_bug_12410_4, is_chlo && !version.IsKnown()) << "Should have version for CHLO packet."; const bool is_first_packet = !undecryptable_packets_.contains(connection_id); if (is_first_packet) { if (ShouldNotBufferPacket(is_chlo)) { return TOO_MANY_CONNECTIONS; } undecryptable_packets_.emplace( std::make_pair(connection_id, BufferedPacketList())); undecryptable_packets_.back().second.ietf_quic = ietf_quic; undecryptable_packets_.back().second.version = version; } QUICHE_CHECK(undecryptable_packets_.contains(connection_id)); BufferedPacketList& queue = undecryptable_packets_.find(connection_id)->second; if (!is_chlo) { size_t num_non_chlo_packets = connections_with_chlo_.contains(connection_id) ? (queue.buffered_packets.size() - 1) : queue.buffered_packets.size(); if (num_non_chlo_packets >= kDefaultMaxUndecryptablePackets) { return TOO_MANY_PACKETS; } } if (queue.buffered_packets.empty()) { queue.creation_time = clock_->ApproximateNow(); } BufferedPacket new_entry(std::unique_ptr<QuicReceivedPacket>(packet.Clone()), self_address, peer_address); if (is_chlo) { queue.buffered_packets.push_front(std::move(new_entry)); queue.parsed_chlo = std::move(parsed_chlo); connections_with_chlo_[connection_id] = false; queue.version = version; queue.connection_id_generator = connection_id_generator; } else { queue.buffered_packets.push_back(std::move(new_entry)); if (is_first_packet) { queue.tls_chlo_extractor.IngestPacket(version, packet); QUIC_BUG_IF(quic_bug_12410_5, queue.tls_chlo_extractor.HasParsedFullChlo()) << "First packet in list should not contain full CHLO"; } } MaybeSetExpirationAlarm(); return SUCCESS; } bool QuicBufferedPacketStore::HasBufferedPackets( QuicConnectionId connection_id) const { return undecryptable_packets_.contains(connection_id); } bool QuicBufferedPacketStore::HasChlosBuffered() const { return !connections_with_chlo_.empty(); } BufferedPacketList QuicBufferedPacketStore::DeliverPackets( QuicConnectionId connection_id) { BufferedPacketList packets_to_deliver; auto it = undecryptable_packets_.find(connection_id); if (it != undecryptable_packets_.end()) { packets_to_deliver = std::move(it->second); undecryptable_packets_.erase(connection_id); std::list<BufferedPacket> initial_packets; std::list<BufferedPacket> other_packets; for (auto& packet : packets_to_deliver.buffered_packets) { QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; PacketHeaderFormat unused_format; bool unused_version_flag; bool unused_use_length_prefix; QuicVersionLabel unused_version_label; ParsedQuicVersion unused_parsed_version = UnsupportedQuicVersion(); QuicConnectionId unused_destination_connection_id; QuicConnectionId unused_source_connection_id; std::optional<absl::string_view> unused_retry_token; std::string unused_detailed_error; QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( *packet.packet, connection_id.length(), &unused_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); if (error_code == QUIC_NO_ERROR && long_packet_type == INITIAL) { initial_packets.push_back(std::move(packet)); } else { other_packets.push_back(std::move(packet)); } } initial_packets.splice(initial_packets.end(), other_packets); packets_to_deliver.buffered_packets = std::move(initial_packets); } return packets_to_deliver; } void QuicBufferedPacketStore::DiscardPackets(QuicConnectionId connection_id) { undecryptable_packets_.erase(connection_id); connections_with_chlo_.erase(connection_id); } void QuicBufferedPacketStore::DiscardAllPackets() { undecryptable_packets_.clear(); connections_with_chlo_.clear(); expiration_alarm_->Cancel(); } void QuicBufferedPacketStore::OnExpirationTimeout() { QuicTime expiration_time = clock_->ApproximateNow() - connection_life_span_; while (!undecryptable_packets_.empty()) { auto& entry = undecryptable_packets_.front(); if (entry.second.creation_time > expiration_time) { break; } QuicConnectionId connection_id = entry.first; visitor_->OnExpiredPackets(connection_id, std::move(entry.second)); undecryptable_packets_.pop_front(); connections_with_chlo_.erase(connection_id); } if (!undecryptable_packets_.empty()) { MaybeSetExpirationAlarm(); } } void QuicBufferedPacketStore::MaybeSetExpirationAlarm() { if (!expiration_alarm_->IsSet()) { expiration_alarm_->Set(clock_->ApproximateNow() + connection_life_span_); } } bool QuicBufferedPacketStore::ShouldNotBufferPacket(bool is_chlo) { bool is_store_full = undecryptable_packets_.size() >= kDefaultMaxConnectionsInStore; if (is_chlo) { return is_store_full; } size_t num_connections_without_chlo = undecryptable_packets_.size() - connections_with_chlo_.size(); bool reach_non_chlo_limit = num_connections_without_chlo >= kMaxConnectionsWithoutCHLO; return is_store_full || reach_non_chlo_limit; } BufferedPacketList QuicBufferedPacketStore::DeliverPacketsForNextConnection( QuicConnectionId* connection_id) { if (connections_with_chlo_.empty()) { return BufferedPacketList(); } *connection_id = connections_with_chlo_.front().first; connections_with_chlo_.pop_front(); BufferedPacketList packets = DeliverPackets(*connection_id); QUICHE_DCHECK(!packets.buffered_packets.empty() && packets.parsed_chlo.has_value()) << "Try to deliver connectons without CHLO. # packets:" << packets.buffered_packets.size() << ", has_parsed_chlo:" << packets.parsed_chlo.has_value(); return packets; } bool QuicBufferedPacketStore::HasChloForConnection( QuicConnectionId connection_id) { return connections_with_chlo_.contains(connection_id); } bool QuicBufferedPacketStore::IngestPacketForTlsChloExtraction( const QuicConnectionId& connection_id, const ParsedQuicVersion& version, const QuicReceivedPacket& packet, std::vector<uint16_t>* out_supported_groups, std::vector<std::string>* out_alpns, std::string* out_sni, bool* out_resumption_attempted, bool* out_early_data_attempted, std::optional<uint8_t>* tls_alert) { QUICHE_DCHECK_NE(out_alpns, nullptr); QUICHE_DCHECK_NE(out_sni, nullptr); QUICHE_DCHECK_NE(tls_alert, nullptr); QUICHE_DCHECK_EQ(version.handshake_protocol, PROTOCOL_TLS1_3); auto it = undecryptable_packets_.find(connection_id); if (it == undecryptable_packets_.end()) { QUIC_BUG(quic_bug_10838_1) << "Cannot ingest packet for unknown connection ID " << connection_id; return false; } it->second.tls_chlo_extractor.IngestPacket(version, packet); if (!it->second.tls_chlo_extractor.HasParsedFullChlo()) { *tls_alert = it->second.tls_chlo_extractor.tls_alert(); return false; } const TlsChloExtractor& tls_chlo_extractor = it->second.tls_chlo_extractor; *out_supported_groups = tls_chlo_extractor.supported_groups(); *out_alpns = tls_chlo_extractor.alpns(); *out_sni = tls_chlo_extractor.server_name(); *out_resumption_attempted = tls_chlo_extractor.resumption_attempted(); *out_early_data_attempted = tls_chlo_extractor.early_data_attempted(); return true; } }
#include "quiche/quic/core/quic_buffered_packet_store.h" #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/first_flight.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/quic_buffered_packet_store_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; namespace test { namespace { const std::optional<ParsedClientHello> kNoParsedChlo; const std::optional<ParsedClientHello> kDefaultParsedChlo = absl::make_optional<ParsedClientHello>(); using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; using ::testing::A; using ::testing::Conditional; using ::testing::Each; using ::testing::ElementsAre; using ::testing::Ne; using ::testing::SizeIs; using ::testing::Truly; EnqueuePacketResult EnqueuePacketToStore( QuicBufferedPacketStore& store, QuicConnectionId connection_id, PacketHeaderFormat form, const QuicReceivedPacket& packet, QuicSocketAddress self_address, QuicSocketAddress peer_address, const ParsedQuicVersion& version, std::optional<ParsedClientHello> parsed_chlo, ConnectionIdGeneratorInterface* connection_id_generator) { ReceivedPacketInfo packet_info(self_address, peer_address, packet); packet_info.destination_connection_id = connection_id; packet_info.form = form; packet_info.version = version; return store.EnqueuePacket(packet_info, std::move(parsed_chlo), connection_id_generator); } class QuicBufferedPacketStoreVisitor : public QuicBufferedPacketStore::VisitorInterface { public: QuicBufferedPacketStoreVisitor() {} ~QuicBufferedPacketStoreVisitor() override {} void OnExpiredPackets(QuicConnectionId , BufferedPacketList early_arrived_packets) override { last_expired_packet_queue_ = std::move(early_arrived_packets); } BufferedPacketList last_expired_packet_queue_; }; class QuicBufferedPacketStoreTest : public QuicTest { public: QuicBufferedPacketStoreTest() : store_(&visitor_, &clock_, &alarm_factory_), self_address_(QuicIpAddress::Any6(), 65535), peer_address_(QuicIpAddress::Any6(), 65535), packet_content_("some encrypted content"), packet_time_(QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(42)), packet_(packet_content_.data(), packet_content_.size(), packet_time_), invalid_version_(UnsupportedQuicVersion()), valid_version_(CurrentSupportedVersions().front()) {} protected: QuicBufferedPacketStoreVisitor visitor_; MockClock clock_; MockAlarmFactory alarm_factory_; QuicBufferedPacketStore store_; QuicSocketAddress self_address_; QuicSocketAddress peer_address_; std::string packet_content_; QuicTime packet_time_; QuicReceivedPacket packet_; const ParsedQuicVersion invalid_version_; const ParsedQuicVersion valid_version_; MockConnectionIdGenerator connection_id_generator_; }; TEST_F(QuicBufferedPacketStoreTest, SimpleEnqueueAndDeliverPacket) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); auto packets = store_.DeliverPackets(connection_id); const std::list<BufferedPacket>& queue = packets.buffered_packets; ASSERT_EQ(1u, queue.size()); ASSERT_FALSE(packets.parsed_chlo.has_value()); EXPECT_EQ(invalid_version_, packets.version); EXPECT_EQ(packet_content_, queue.front().packet->AsStringPiece()); EXPECT_EQ(packet_time_, queue.front().packet->receipt_time()); EXPECT_EQ(peer_address_, queue.front().peer_address); EXPECT_EQ(self_address_, queue.front().self_address); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); } TEST_F(QuicBufferedPacketStoreTest, DifferentPacketAddressOnOneConnection) { QuicSocketAddress addr_with_new_port(QuicIpAddress::Any4(), 256); QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, addr_with_new_port, invalid_version_, kNoParsedChlo, nullptr); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; ASSERT_EQ(2u, queue.size()); EXPECT_EQ(peer_address_, queue.front().peer_address); EXPECT_EQ(addr_with_new_port, queue.back().peer_address); } TEST_F(QuicBufferedPacketStoreTest, EnqueueAndDeliverMultiplePacketsOnMultipleConnections) { size_t num_connections = 10; for (uint64_t conn_id = 1; conn_id <= num_connections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); } for (uint64_t conn_id = num_connections; conn_id > 0; --conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; ASSERT_EQ(2u, queue.size()); } } TEST_F(QuicBufferedPacketStoreTest, FailToBufferTooManyPacketsOnExistingConnection) { size_t num_packets = kDefaultMaxUndecryptablePackets + 1; QuicConnectionId connection_id = TestConnectionId(1); EXPECT_EQ(QuicBufferedPacketStore::SUCCESS, EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, nullptr)); for (size_t i = 1; i <= num_packets; ++i) { EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); if (i <= kDefaultMaxUndecryptablePackets) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_PACKETS, result); } } EXPECT_EQ(kDefaultMaxUndecryptablePackets + 1, store_.DeliverPackets(connection_id).buffered_packets.size()); } TEST_F(QuicBufferedPacketStoreTest, ReachNonChloConnectionUpperLimit) { const size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); if (conn_id <= kMaxConnectionsWithoutCHLO) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, result); } } for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; if (conn_id <= kMaxConnectionsWithoutCHLO) { EXPECT_EQ(1u, queue.size()); } else { EXPECT_EQ(0u, queue.size()); } } } TEST_F(QuicBufferedPacketStoreTest, FullStoreFailToBufferDataPacketOnNewConnection) { size_t num_chlos = kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= num_chlos; ++conn_id) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, TestConnectionId(conn_id), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, nullptr)); } for (uint64_t conn_id = num_chlos + 1; conn_id <= (kDefaultMaxConnectionsInStore + 1); ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, nullptr); if (conn_id <= kDefaultMaxConnectionsInStore) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, result); } } } TEST_F(QuicBufferedPacketStoreTest, BasicGeneratorBuffering) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, &connection_id_generator_)); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(delivered_conn_id, TestConnectionId(1)); EXPECT_EQ(&connection_id_generator_, packet_list.connection_id_generator); } TEST_F(QuicBufferedPacketStoreTest, NullGeneratorOk) { EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, nullptr)); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(delivered_conn_id, TestConnectionId(1)); EXPECT_EQ(packet_list.connection_id_generator, nullptr); } TEST_F(QuicBufferedPacketStoreTest, GeneratorIgnoredForNonChlo) { MockConnectionIdGenerator generator2; EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, &connection_id_generator_)); EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, &generator2)); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(2u, packet_list.buffered_packets.size()); EXPECT_EQ(delivered_conn_id, TestConnectionId(1)); EXPECT_EQ(packet_list.connection_id_generator, &connection_id_generator_); } TEST_F(QuicBufferedPacketStoreTest, EnqueueChloOnTooManyDifferentConnections) { for (uint64_t conn_id = 1; conn_id <= kMaxConnectionsWithoutCHLO; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, &connection_id_generator_)); } for (size_t i = kMaxConnectionsWithoutCHLO + 1; i <= kDefaultMaxConnectionsInStore + 1; ++i) { QuicConnectionId connection_id = TestConnectionId(i); EnqueuePacketResult rs = EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, &connection_id_generator_); if (i <= kDefaultMaxConnectionsInStore) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, rs); EXPECT_TRUE(store_.HasChloForConnection(connection_id)); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, rs); EXPECT_FALSE(store_.HasChloForConnection(connection_id)); } } EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, &connection_id_generator_)); EXPECT_TRUE(store_.HasChloForConnection(TestConnectionId(1))); QuicConnectionId delivered_conn_id; for (size_t i = 0; i < kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO + 1; ++i) { BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); if (i < kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO) { EXPECT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(TestConnectionId(i + kMaxConnectionsWithoutCHLO + 1), delivered_conn_id); } else { EXPECT_EQ(2u, packet_list.buffered_packets.size()); EXPECT_EQ(TestConnectionId(1u), delivered_conn_id); } EXPECT_EQ(packet_list.connection_id_generator, &connection_id_generator_); } EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, PacketQueueExpiredBeforeDelivery) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, &connection_id_generator_); EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, &connection_id_generator_)); QuicConnectionId connection_id2 = TestConnectionId(2); EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id2, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, &connection_id_generator_)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicConnectionId connection_id3 = TestConnectionId(3); QuicSocketAddress another_client_address(QuicIpAddress::Any4(), 255); EnqueuePacketToStore(store_, connection_id3, GOOGLE_QUIC_PACKET, packet_, self_address_, another_client_address, valid_version_, kDefaultParsedChlo, &connection_id_generator_); clock_.AdvanceTime( QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline() - clock_.ApproximateNow()); ASSERT_GE(clock_.ApproximateNow(), QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline()); alarm_factory_.FireAlarm( QuicBufferedPacketStorePeer::expiration_alarm(&store_)); EXPECT_EQ(1u, visitor_.last_expired_packet_queue_.buffered_packets.size()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasBufferedPackets(connection_id2)); ASSERT_EQ(0u, store_.DeliverPackets(connection_id).buffered_packets.size()); ASSERT_EQ(0u, store_.DeliverPackets(connection_id2).buffered_packets.size()); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(connection_id3, delivered_conn_id); EXPECT_EQ(packet_list.connection_id_generator, &connection_id_generator_); ASSERT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(another_client_address, packet_list.buffered_packets.front().peer_address); QuicConnectionId connection_id4 = TestConnectionId(4); EnqueuePacketToStore(store_, connection_id4, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id4, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); clock_.AdvanceTime( QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline() - clock_.ApproximateNow()); alarm_factory_.FireAlarm( QuicBufferedPacketStorePeer::expiration_alarm(&store_)); EXPECT_EQ(2u, visitor_.last_expired_packet_queue_.buffered_packets.size()); } TEST_F(QuicBufferedPacketStoreTest, SimpleDiscardPackets) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, DiscardWithCHLOs) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_TRUE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, MultipleDiscardPackets) { QuicConnectionId connection_id_1 = TestConnectionId(1); QuicConnectionId connection_id_2 = TestConnectionId(2); EnqueuePacketToStore(store_, connection_id_1, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id_1, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, nullptr); ParsedClientHello parsed_chlo; parsed_chlo.alpns.push_back("h3"); parsed_chlo.sni = TestHostname(); EnqueuePacketToStore(store_, connection_id_2, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, parsed_chlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_1)); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_2)); EXPECT_TRUE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id_1); EXPECT_TRUE(store_.DeliverPackets(connection_id_1).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id_1)); EXPECT_TRUE(store_.HasChlosBuffered()); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_2)); auto packets = store_.DeliverPackets(connection_id_2); EXPECT_EQ(1u, packets.buffered_packets.size()); ASSERT_EQ(1u, packets.parsed_chlo->alpns.size()); EXPECT_EQ("h3", packets.parsed_chlo->alpns[0]); EXPECT_EQ(TestHostname(), packets.parsed_chlo->sni); EXPECT_EQ(valid_version_, packets.version); EXPECT_TRUE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id_2); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, DiscardPacketsEmpty) { QuicConnectionId connection_id = TestConnectionId(11235); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, IngestPacketForTlsChloExtraction) { QuicConnectionId connection_id = TestConnectionId(1); std::vector<std::string> alpns; std::vector<uint16_t> supported_groups; std::string sni; bool resumption_attempted = false; bool early_data_attempted = false; QuicConfig config; std::optional<uint8_t> tls_alert; EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, packet_, &supported_groups, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); store_.DiscardPackets(connection_id); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); config.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; auto packets = GetFirstFlightOfPackets(valid_version_, config); ASSERT_EQ(packets.size(), 2u); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, *packets[0], self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, *packets[1], self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, *packets[0], &supported_groups, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); EXPECT_TRUE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, *packets[1], &supported_groups, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); EXPECT_THAT(alpns, ElementsAre(AlpnForVersion(valid_version_))); EXPECT_FALSE(supported_groups.empty()); EXPECT_EQ(sni, TestHostname()); EXPECT_FALSE(resumption_attempted); EXPECT_FALSE(early_data_attempted); } TEST_F(QuicBufferedPacketStoreTest, DeliverInitialPacketsFirst) { QuicConfig config; QuicConnectionId connection_id = TestConnectionId(1); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string custom_parameter_value(2000, '-'); config.custom_transport_parameters_to_send()[kCustomParameterId] = custom_parameter_value; auto initial_packets = GetFirstFlightOfPackets(valid_version_, config); ASSERT_THAT(initial_packets, SizeIs(2)); EXPECT_THAT( initial_packets, Each(Truly([](const std::unique_ptr<QuicReceivedPacket>& packet) { QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; PacketHeaderFormat unused_format; bool unused_version_flag; bool unused_use_length_prefix; QuicVersionLabel unused_version_label; ParsedQuicVersion unused_parsed_version = UnsupportedQuicVersion(); QuicConnectionId unused_destination_connection_id; QuicConnectionId unused_source_connection_id; std::optional<absl::string_view> unused_retry_token; std::string unused_detailed_error; QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( *packet, kQuicDefaultConnectionIdLength, &unused_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); return error_code == QUIC_NO_ERROR && long_packet_type == INITIAL; }))); QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; PacketHeaderFormat unused_format; bool unused_version_flag; bool unused_use_length_prefix; QuicVersionLabel unused_version_label; ParsedQuicVersion unused_parsed_version = UnsupportedQuicVersion(); QuicConnectionId unused_destination_connection_id; QuicConnectionId unused_source_connection_id; std::optional<absl::string_view> unused_retry_token; std::string unused_detailed_error; QuicErrorCode error_code = QUIC_NO_ERROR; error_code = QuicFramer::ParsePublicHeaderDispatcher( packet_, kQuicDefaultConnectionIdLength, &unused_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_NE(long_packet_type, INITIAL); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, *initial_packets[0], self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, *initial_packets[1], self_address_, peer_address_, valid_version_, kNoParsedChlo, nullptr); BufferedPacketList delivered_packets = store_.DeliverPackets(connection_id); EXPECT_THAT(delivered_packets.buffered_packets, SizeIs(3)); QuicLongHeaderType previous_packet_type = INITIAL; for (const auto& packet : delivered_packets.buffered_packets) { error_code = QuicFramer::ParsePublicHeaderDispatcher( *packet.packet, kQuicDefaultConnectionIdLength, &unused_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_THAT(long_packet_type, Conditional(previous_packet_type == INITIAL, A<QuicLongHeaderType>(), Ne(INITIAL))); previous_packet_type = long_packet_type; } } TEST_F(QuicBufferedPacketStoreTest, BufferedPacketRetainsEcn) { QuicConnectionId connection_id = TestConnectionId(1); QuicReceivedPacket ect1_packet(packet_content_.data(), packet_content_.size(), packet_time_, false, 0, true, nullptr, 0, false, ECN_ECT1); EnqueuePacketToStore(stor
257
cpp
google/quiche
quic_flow_controller
quiche/quic/core/quic_flow_controller.cc
quiche/quic/core/quic_flow_controller_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_FLOW_CONTROLLER_H_ #define QUICHE_QUIC_CORE_QUIC_FLOW_CONTROLLER_H_ #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicFlowControllerPeer; } class QuicConnection; class QuicSession; inline constexpr float kSessionFlowControlMultiplier = 1.5; class QUICHE_EXPORT QuicFlowControllerInterface { public: virtual ~QuicFlowControllerInterface() {} virtual void EnsureWindowAtLeast(QuicByteCount window_size) = 0; }; class QUICHE_EXPORT QuicFlowController : public QuicFlowControllerInterface { public: QuicFlowController(QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller); QuicFlowController(const QuicFlowController&) = delete; QuicFlowController(QuicFlowController&&) = default; QuicFlowController& operator=(const QuicFlowController&) = delete; ~QuicFlowController() override {} bool UpdateHighestReceivedOffset(QuicStreamOffset new_offset); void AddBytesConsumed(QuicByteCount bytes_consumed); void AddBytesSent(QuicByteCount bytes_sent); bool UpdateSendWindowOffset(QuicStreamOffset new_send_window_offset); void EnsureWindowAtLeast(QuicByteCount window_size) override; QuicByteCount SendWindowSize() const; QuicByteCount receive_window_size() const { return receive_window_size_; } void MaybeSendBlocked(); bool IsBlocked() const; bool FlowControlViolation(); void SendWindowUpdate(); QuicByteCount bytes_consumed() const { return bytes_consumed_; } QuicByteCount bytes_sent() const { return bytes_sent_; } QuicStreamOffset send_window_offset() const { return send_window_offset_; } QuicStreamOffset highest_received_byte_offset() const { return highest_received_byte_offset_; } void set_receive_window_size_limit(QuicByteCount receive_window_size_limit) { QUICHE_DCHECK_GE(receive_window_size_limit, receive_window_size_limit_); receive_window_size_limit_ = receive_window_size_limit; } void UpdateReceiveWindowSize(QuicStreamOffset size); bool auto_tune_receive_window() { return auto_tune_receive_window_; } private: friend class test::QuicFlowControllerPeer; void MaybeSendWindowUpdate(); void MaybeIncreaseMaxWindowSize(); void UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window); void IncreaseWindowSize(); std::string LogLabel(); QuicSession* session_; QuicConnection* connection_; QuicStreamId id_; bool is_connection_flow_controller_; Perspective perspective_; QuicByteCount bytes_sent_; QuicStreamOffset send_window_offset_; QuicByteCount bytes_consumed_; QuicStreamOffset highest_received_byte_offset_; QuicStreamOffset receive_window_offset_; QuicByteCount receive_window_size_; QuicByteCount receive_window_size_limit_; bool auto_tune_receive_window_; QuicFlowControllerInterface* session_flow_controller_; QuicByteCount WindowUpdateThreshold(); QuicStreamOffset last_blocked_send_window_offset_; QuicTime prev_window_update_time_; }; } #endif #include "quiche/quic/core/quic_flow_controller.h" #include <algorithm> #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") std::string QuicFlowController::LogLabel() { if (is_connection_flow_controller_) { return "connection"; } return absl::StrCat("stream ", id_); } QuicFlowController::QuicFlowController( QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller) : session_(session), connection_(session->connection()), id_(id), is_connection_flow_controller_(is_connection_flow_controller), perspective_(session->perspective()), bytes_sent_(0), send_window_offset_(send_window_offset), bytes_consumed_(0), highest_received_byte_offset_(0), receive_window_offset_(receive_window_offset), receive_window_size_(receive_window_offset), receive_window_size_limit_(receive_window_size_limit), auto_tune_receive_window_(should_auto_tune_receive_window), session_flow_controller_(session_flow_controller), last_blocked_send_window_offset_(0), prev_window_update_time_(QuicTime::Zero()) { QUICHE_DCHECK_LE(receive_window_size_, receive_window_size_limit_); QUICHE_DCHECK_EQ( is_connection_flow_controller_, QuicUtils::GetInvalidStreamId(session_->transport_version()) == id_); QUIC_DVLOG(1) << ENDPOINT << "Created flow controller for " << LogLabel() << ", setting initial receive window offset to: " << receive_window_offset_ << ", max receive window to: " << receive_window_size_ << ", max receive window limit to: " << receive_window_size_limit_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " consumed " << bytes_consumed_ << " bytes."; MaybeSendWindowUpdate(); } bool QuicFlowController::UpdateHighestReceivedOffset( QuicStreamOffset new_offset) { if (new_offset <= highest_received_byte_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " highest byte offset increased from " << highest_received_byte_offset_ << " to " << new_offset; highest_received_byte_offset_ = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { QUIC_BUG(quic_bug_10836_1) << ENDPOINT << LogLabel() << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; connection_->CloseConnection( QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, absl::StrCat(send_window_offset_ - (bytes_sent_ + bytes_sent), "bytes over send window offset"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } bytes_sent_ += bytes_sent; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " sent " << bytes_sent_ << " bytes."; } bool QuicFlowController::FlowControlViolation() { if (highest_received_byte_offset_ > receive_window_offset_) { QUIC_DLOG(INFO) << ENDPOINT << "Flow control violation on " << LogLabel() << ", receive window offset: " << receive_window_offset_ << ", highest received byte offset: " << highest_received_byte_offset_; return true; } return false; } void QuicFlowController::MaybeIncreaseMaxWindowSize() { QuicTime now = connection_->clock()->ApproximateNow(); QuicTime prev = prev_window_update_time_; prev_window_update_time_ = now; if (!prev.IsInitialized()) { QUIC_DVLOG(1) << ENDPOINT << "first window update for " << LogLabel(); return; } if (!auto_tune_receive_window_) { return; } QuicTime::Delta rtt = connection_->sent_packet_manager().GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { QUIC_DVLOG(1) << ENDPOINT << "rtt zero for " << LogLabel(); return; } QuicTime::Delta since_last = now - prev; QuicTime::Delta two_rtt = 2 * rtt; if (since_last >= two_rtt) { return; } QuicByteCount old_window = receive_window_size_; IncreaseWindowSize(); if (receive_window_size_ > old_window) { QUIC_DVLOG(1) << ENDPOINT << "New max window increase for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. max wndw: " << receive_window_size_; if (session_flow_controller_ != nullptr) { session_flow_controller_->EnsureWindowAtLeast( kSessionFlowControlMultiplier * receive_window_size_); } } else { QUIC_LOG_FIRST_N(INFO, 1) << ENDPOINT << "Max window at limit for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. Limit size: " << receive_window_size_; } } void QuicFlowController::IncreaseWindowSize() { receive_window_size_ *= 2; receive_window_size_ = std::min(receive_window_size_, receive_window_size_limit_); } QuicByteCount QuicFlowController::WindowUpdateThreshold() { return receive_window_size_ / 2; } void QuicFlowController::MaybeSendWindowUpdate() { if (!session_->connection()->connected()) { return; } QUICHE_DCHECK_LE(bytes_consumed_, receive_window_offset_); QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; QuicByteCount threshold = WindowUpdateThreshold(); if (!prev_window_update_time_.IsInitialized()) { prev_window_update_time_ = connection_->clock()->ApproximateNow(); } if (available_window >= threshold) { QUIC_DVLOG(1) << ENDPOINT << "Not sending WindowUpdate for " << LogLabel() << ", available window: " << available_window << " >= threshold: " << threshold; return; } MaybeIncreaseMaxWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } void QuicFlowController::UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window) { receive_window_offset_ += (receive_window_size_ - available_window); QUIC_DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for " << LogLabel() << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << WindowUpdateThreshold() << ", and receive window size: " << receive_window_size_ << ". New receive window offset is: " << receive_window_offset_; SendWindowUpdate(); } void QuicFlowController::MaybeSendBlocked() { if (SendWindowSize() != 0 || last_blocked_send_window_offset_ >= send_window_offset_) { return; } QUIC_DLOG(INFO) << ENDPOINT << LogLabel() << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; last_blocked_send_window_offset_ = send_window_offset_; session_->SendBlocked(id_, last_blocked_send_window_offset_); } bool QuicFlowController::UpdateSendWindowOffset( QuicStreamOffset new_send_window_offset) { if (new_send_window_offset <= send_window_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << "UpdateSendWindowOffset for " << LogLabel() << " with new offset " << new_send_window_offset << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; const bool was_previously_blocked = IsBlocked(); send_window_offset_ = new_send_window_offset; return was_previously_blocked; } void QuicFlowController::EnsureWindowAtLeast(QuicByteCount window_size) { if (receive_window_size_limit_ >= window_size) { return; } QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; IncreaseWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64_t QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } void QuicFlowController::UpdateReceiveWindowSize(QuicStreamOffset size) { QUICHE_DCHECK_LE(size, receive_window_size_limit_); QUIC_DVLOG(1) << ENDPOINT << "UpdateReceiveWindowSize for " << LogLabel() << ": " << size; if (receive_window_size_ != receive_window_offset_) { QUIC_BUG(quic_bug_10836_2) << "receive_window_size_:" << receive_window_size_ << " != receive_window_offset:" << receive_window_offset_; return; } receive_window_size_ = size; receive_window_offset_ = size; } void QuicFlowController::SendWindowUpdate() { QuicStreamId id = id_; if (is_connection_flow_controller_) { id = QuicUtils::GetInvalidStreamId(connection_->transport_version()); } session_->SendWindowUpdate(id, receive_window_offset_); } }
#include "quiche/quic/core/quic_flow_controller.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::Invoke; using testing::StrictMock; namespace quic { namespace test { const int64_t kRtt = 100; class MockFlowController : public QuicFlowControllerInterface { public: MockFlowController() {} MockFlowController(const MockFlowController&) = delete; MockFlowController& operator=(const MockFlowController&) = delete; ~MockFlowController() override {} MOCK_METHOD(void, EnsureWindowAtLeast, (QuicByteCount), (override)); }; class QuicFlowControllerTest : public QuicTest { public: void Initialize() { connection_ = new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_); flow_controller_ = std::make_unique<QuicFlowController>( session_.get(), stream_id_, false, send_window_, receive_window_, kStreamReceiveWindowLimit, should_auto_tune_receive_window_, &session_flow_controller_); } protected: QuicStreamId stream_id_ = 1234; QuicByteCount send_window_ = kInitialSessionFlowControlWindowForTest; QuicByteCount receive_window_ = kInitialSessionFlowControlWindowForTest; std::unique_ptr<QuicFlowController> flow_controller_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<StrictMock<MockQuicSession>> session_; MockFlowController session_flow_controller_; bool should_auto_tune_receive_window_ = false; }; TEST_F(QuicFlowControllerTest, SendingBytes) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_ / 2, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); EXPECT_TRUE(flow_controller_->UpdateSendWindowOffset(2 * send_window_)); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); EXPECT_FALSE(flow_controller_->UpdateSendWindowOffset(send_window_ / 10)); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); EXPECT_QUIC_BUG( { EXPECT_CALL( *connection_, CloseConnection(QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, _, _)); flow_controller_->AddBytesSent(send_window_ * 10); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); }, absl::StrCat("Trying to send an extra ", send_window_ * 10, " bytes")); } TEST_F(QuicFlowControllerTest, ReceivingBytes) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_TRUE( flow_controller_->UpdateHighestReceivedOffset(1 + receive_window_ / 2)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); flow_controller_->AddBytesConsumed(1 + receive_window_ / 2); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); } TEST_F(QuicFlowControllerTest, Move) { Initialize(); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_ / 2, flow_controller_->SendWindowSize()); EXPECT_TRUE( flow_controller_->UpdateHighestReceivedOffset(1 + receive_window_ / 2)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicFlowController flow_controller2(std::move(*flow_controller_)); EXPECT_EQ(send_window_ / 2, flow_controller2.SendWindowSize()); EXPECT_FALSE(flow_controller2.FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(&flow_controller2)); } TEST_F(QuicFlowControllerTest, OnlySendBlockedFrameOncePerOffset) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(0); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); EXPECT_TRUE(flow_controller_->UpdateSendWindowOffset(2 * send_window_)); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); } TEST_F(QuicFlowControllerTest, ReceivingBytesFastIncreasesFlowWindow) { should_auto_tune_receive_window_ = true; Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); EXPECT_TRUE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL( session_flow_controller_, EnsureWindowAtLeast(kInitialSessionFlowControlWindowForTest * 2 * 1.5)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(2 * kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt - 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_GT(new_threshold, threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesFastNoAutoTune) { Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_FALSE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt - 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesNormalStableFlowWindow) { should_auto_tune_receive_window_ = true; Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); EXPECT_TRUE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL( session_flow_controller_, EnsureWindowAtLeast(kInitialSessionFlowControlWindowForTest * 2 * 1.5)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(2 * kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt + 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, 2 * threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesNormalNoAutoTune) { Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_FALSE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt + 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, threshold); } } }
258
cpp
google/quiche
tls_chlo_extractor
quiche/quic/core/tls_chlo_extractor.cc
quiche/quic/core/tls_chlo_extractor_test.cc
#ifndef QUICHE_QUIC_CORE_TLS_CHLO_EXTRACTOR_H_ #define QUICHE_QUIC_CORE_TLS_CHLO_EXTRACTOR_H_ #include <cstdint> #include <memory> #include <string> #include <vector> #include "absl/types/span.h" #include "openssl/ssl.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_sequencer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT TlsChloExtractor : public QuicFramerVisitorInterface, public QuicStreamSequencer::StreamInterface { public: TlsChloExtractor(); TlsChloExtractor(const TlsChloExtractor&) = delete; TlsChloExtractor(TlsChloExtractor&&); TlsChloExtractor& operator=(const TlsChloExtractor&) = delete; TlsChloExtractor& operator=(TlsChloExtractor&&); enum class State : uint8_t { kInitial = 0, kParsedFullSinglePacketChlo = 1, kParsedFullMultiPacketChlo = 2, kParsedPartialChloFragment = 3, kUnrecoverableFailure = 4, }; State state() const { return state_; } std::vector<std::string> alpns() const { return alpns_; } std::string server_name() const { return server_name_; } bool resumption_attempted() const { return resumption_attempted_; } bool early_data_attempted() const { return early_data_attempted_; } const std::vector<uint16_t>& supported_groups() const { return supported_groups_; } absl::Span<const uint8_t> client_hello_bytes() const { return client_hello_bytes_; } static std::string StateToString(State state); void IngestPacket(const ParsedQuicVersion& version, const QuicReceivedPacket& packet); bool HasParsedFullChlo() const { return state_ == State::kParsedFullSinglePacketChlo || state_ == State::kParsedFullMultiPacketChlo; } std::optional<uint8_t> tls_alert() const { QUICHE_DCHECK(!tls_alert_.has_value() || state_ == State::kUnrecoverableFailure); return tls_alert_; } void OnError(QuicFramer* ) override {} bool OnProtocolVersionMismatch(ParsedQuicVersion version) override; void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& ) override {} void OnRetryPacket(QuicConnectionId , QuicConnectionId , absl::string_view , absl::string_view , absl::string_view ) override {} bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& ) override { return true; } void OnDecryptedPacket(size_t , EncryptionLevel ) override {} bool OnPacketHeader(const QuicPacketHeader& ) override { return true; } void OnCoalescedPacket(const QuicEncryptedPacket& ) override {} void OnUndecryptablePacket(const QuicEncryptedPacket& , EncryptionLevel , bool ) override {} bool OnStreamFrame(const QuicStreamFrame& ) override { return true; } bool OnCryptoFrame(const QuicCryptoFrame& frame) override; bool OnAckFrameStart(QuicPacketNumber , QuicTime::Delta ) override { return true; } bool OnAckRange(QuicPacketNumber , QuicPacketNumber ) override { return true; } bool OnAckTimestamp(QuicPacketNumber , QuicTime ) override { return true; } bool OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) override { return true; } bool OnStopWaitingFrame(const QuicStopWaitingFrame& ) override { return true; } bool OnPingFrame(const QuicPingFrame& ) override { return true; } bool OnRstStreamFrame(const QuicRstStreamFrame& ) override { return true; } bool OnConnectionCloseFrame( const QuicConnectionCloseFrame& ) override { return true; } bool OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& ) override { return true; } bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& ) override { return true; } bool OnNewTokenFrame(const QuicNewTokenFrame& ) override { return true; } bool OnStopSendingFrame(const QuicStopSendingFrame& ) override { return true; } bool OnPathChallengeFrame(const QuicPathChallengeFrame& ) override { return true; } bool OnPathResponseFrame(const QuicPathResponseFrame& ) override { return true; } bool OnGoAwayFrame(const QuicGoAwayFrame& ) override { return true; } bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& ) override { return true; } bool OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& ) override { return true; } bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& ) override { return true; } bool OnBlockedFrame(const QuicBlockedFrame& ) override { return true; } bool OnPaddingFrame(const QuicPaddingFrame& ) override { return true; } bool OnMessageFrame(const QuicMessageFrame& ) override { return true; } bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& ) override { return true; } bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& ) override { return true; } bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& ) override { return true; } void OnPacketComplete() override {} bool IsValidStatelessResetToken( const StatelessResetToken& ) const override { return true; } void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& ) override {} void OnKeyUpdate(KeyUpdateReason ) override {} void OnDecryptedFirstPacketInKeyPhase() override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } void OnDataAvailable() override; void OnFinRead() override {} void AddBytesConsumed(QuicByteCount ) override {} void ResetWithError(QuicResetStreamError ) override {} void OnUnrecoverableError(QuicErrorCode error, const std::string& details) override; void OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) override; QuicStreamId id() const override { return 0; } ParsedQuicVersion version() const override { return framer_->version(); } private: bool MaybeAttemptToParseChloLength(); void AttemptToParseFullChlo(); void HandleUnrecoverableError(const std::string& error_details); static std::pair<SSL_CTX*, int> GetSharedSslHandles(); void SetupSslHandle(); static TlsChloExtractor* GetInstanceFromSSL(SSL* ssl); static enum ssl_select_cert_result_t SelectCertCallback( const SSL_CLIENT_HELLO* client_hello); static int SetReadSecretCallback(SSL* ssl, enum ssl_encryption_level_t level, const SSL_CIPHER* cipher, const uint8_t* secret, size_t secret_length); static int SetWriteSecretCallback(SSL* ssl, enum ssl_encryption_level_t level, const SSL_CIPHER* cipher, const uint8_t* secret, size_t secret_length); static int WriteMessageCallback(SSL* ssl, enum ssl_encryption_level_t level, const uint8_t* data, size_t len); static int FlushFlightCallback(SSL* ssl); static int SendAlertCallback(SSL* ssl, enum ssl_encryption_level_t level, uint8_t desc); void HandleParsedChlo(const SSL_CLIENT_HELLO* client_hello); void HandleUnexpectedCallback(const std::string& callback_name); void SendAlert(uint8_t tls_alert_value); std::unique_ptr<QuicFramer> framer_; QuicStreamSequencer crypto_stream_sequencer_; bssl::UniquePtr<SSL> ssl_; State state_; std::string error_details_; bool parsed_crypto_frame_in_this_packet_; std::vector<uint16_t> supported_groups_; std::vector<std::string> alpns_; std::string server_name_; bool resumption_attempted_ = false; bool early_data_attempted_ = false; std::optional<uint8_t> tls_alert_; std::vector<uint8_t> client_hello_bytes_; }; QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const TlsChloExtractor::State& state); } #endif #include "quiche/quic/core/tls_chlo_extractor.h" #include <cstdint> #include <cstring> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { namespace { bool HasExtension(const SSL_CLIENT_HELLO* client_hello, uint16_t extension) { const uint8_t* unused_extension_bytes; size_t unused_extension_len; return 1 == SSL_early_callback_ctx_extension_get(client_hello, extension, &unused_extension_bytes, &unused_extension_len); } std::vector<uint16_t> GetSupportedGroups(const SSL_CLIENT_HELLO* client_hello) { const uint8_t* extension_data; size_t extension_len; int rv = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_supported_groups, &extension_data, &extension_len); if (rv != 1) { return {}; } QuicDataReader named_groups_reader( reinterpret_cast<const char*>(extension_data), extension_len); uint16_t named_groups_len; if (!named_groups_reader.ReadUInt16(&named_groups_len) || named_groups_len + sizeof(uint16_t) != extension_len) { QUIC_CODE_COUNT(quic_chlo_supported_groups_invalid_length); return {}; } std::vector<uint16_t> named_groups; while (!named_groups_reader.IsDoneReading()) { uint16_t named_group; if (!named_groups_reader.ReadUInt16(&named_group)) { QUIC_CODE_COUNT(quic_chlo_supported_groups_odd_length); QUIC_LOG_FIRST_N(WARNING, 10) << "Failed to read named groups"; break; } named_groups.push_back(named_group); } return named_groups; } } TlsChloExtractor::TlsChloExtractor() : crypto_stream_sequencer_(this), state_(State::kInitial), parsed_crypto_frame_in_this_packet_(false) {} TlsChloExtractor::TlsChloExtractor(TlsChloExtractor&& other) : TlsChloExtractor() { *this = std::move(other); } TlsChloExtractor& TlsChloExtractor::operator=(TlsChloExtractor&& other) { framer_ = std::move(other.framer_); if (framer_) { framer_->set_visitor(this); } crypto_stream_sequencer_ = std::move(other.crypto_stream_sequencer_); crypto_stream_sequencer_.set_stream(this); ssl_ = std::move(other.ssl_); if (ssl_) { std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); int ex_data_index = shared_handles.second; const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this); QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data"; } state_ = other.state_; error_details_ = std::move(other.error_details_); parsed_crypto_frame_in_this_packet_ = other.parsed_crypto_frame_in_this_packet_; supported_groups_ = std::move(other.supported_groups_); alpns_ = std::move(other.alpns_); server_name_ = std::move(other.server_name_); client_hello_bytes_ = std::move(other.client_hello_bytes_); return *this; } void TlsChloExtractor::IngestPacket(const ParsedQuicVersion& version, const QuicReceivedPacket& packet) { if (state_ == State::kUnrecoverableFailure) { QUIC_DLOG(ERROR) << "Not ingesting packet after unrecoverable error"; return; } if (version == UnsupportedQuicVersion()) { QUIC_DLOG(ERROR) << "Not ingesting packet with unsupported version"; return; } if (version.handshake_protocol != PROTOCOL_TLS1_3) { QUIC_DLOG(ERROR) << "Not ingesting packet with non-TLS version " << version; return; } if (framer_) { if (!framer_->IsSupportedVersion(version)) { QUIC_DLOG(ERROR) << "Not ingesting packet with version mismatch, expected " << framer_->version() << ", got " << version; return; } } else { framer_ = std::make_unique<QuicFramer>( ParsedQuicVersionVector{version}, QuicTime::Zero(), Perspective::IS_SERVER, 0); framer_->set_visitor(this); } parsed_crypto_frame_in_this_packet_ = false; const bool parse_success = framer_->ProcessPacket(packet); if (state_ == State::kInitial && parsed_crypto_frame_in_this_packet_) { state_ = State::kParsedPartialChloFragment; } if (!parse_success) { QUIC_DLOG(ERROR) << "Failed to process packet"; return; } } bool TlsChloExtractor::OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) { if (header.form != IETF_QUIC_LONG_HEADER_PACKET) { QUIC_DLOG(ERROR) << "Not parsing non-long-header packet " << header; return false; } if (header.long_packet_type != INITIAL) { QUIC_DLOG(ERROR) << "Not parsing non-initial packet " << header; return false; } framer_->SetInitialObfuscators(header.destination_connection_id); return true; } bool TlsChloExtractor::OnProtocolVersionMismatch(ParsedQuicVersion version) { QUIC_BUG(quic_bug_10855_1) << "Unexpected version mismatch, expected " << framer_->version() << ", got " << version; return false; } void TlsChloExtractor::OnUnrecoverableError(QuicErrorCode error, const std::string& details) { HandleUnrecoverableError(absl::StrCat( "Crypto stream error ", QuicErrorCodeToString(error), ": ", details)); } void TlsChloExtractor::OnUnrecoverableError( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { HandleUnrecoverableError(absl::StrCat( "Crypto stream error ", QuicErrorCodeToString(error), "(", QuicIetfTransportErrorCodeString(ietf_error), "): ", details)); } bool TlsChloExtractor::OnCryptoFrame(const QuicCryptoFrame& frame) { if (frame.level != ENCRYPTION_INITIAL) { QUIC_BUG(quic_bug_10855_2) << "Parsed bad-level CRYPTO frame " << frame; return false; } parsed_crypto_frame_in_this_packet_ = true; crypto_stream_sequencer_.OnCryptoFrame(frame); return true; } void TlsChloExtractor::OnDataAvailable() { SetupSslHandle(); struct iovec iov; while (crypto_stream_sequencer_.GetReadableRegion(&iov)) { const int rv = SSL_provide_quic_data( ssl_.get(), ssl_encryption_initial, reinterpret_cast<const uint8_t*>(iov.iov_base), iov.iov_len); if (rv != 1) { HandleUnrecoverableError("SSL_provide_quic_data failed"); return; } crypto_stream_sequencer_.MarkConsumed(iov.iov_len); } (void)SSL_do_handshake(ssl_.get()); } TlsChloExtractor* TlsChloExtractor::GetInstanceFromSSL(SSL* ssl) { std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); int ex_data_index = shared_handles.second; return reinterpret_cast<TlsChloExtractor*>( SSL_get_ex_data(ssl, ex_data_index)); } int TlsChloExtractor::SetReadSecretCallback( SSL* ssl, enum ssl_encryption_level_t , const SSL_CIPHER* , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetReadSecretCallback"); return 0; } int TlsChloExtractor::SetWriteSecretCallback( SSL* ssl, enum ssl_encryption_level_t , const SSL_CIPHER* , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetWriteSecretCallback"); return 0; } int TlsChloExtractor::WriteMessageCallback( SSL* ssl, enum ssl_encryption_level_t , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("WriteMessageCallback"); return 0; } int TlsChloExtractor::FlushFlightCallback(SSL* ssl) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("FlushFlightCallback"); return 0; } void TlsChloExtractor::HandleUnexpectedCallback( const std::string& callback_name) { std::string error_details = absl::StrCat("Unexpected callback ", callback_name); QUIC_BUG(quic_bug_10855_3) << error_details; HandleUnrecoverableError(error_details); } int TlsChloExtractor::SendAlertCallback(SSL* ssl, enum ssl_encryption_level_t , uint8_t desc) { GetInstanceFromSSL(ssl)->SendAlert(desc); return 0; } void TlsChloExtractor::SendAlert(uint8_t tls_alert_value) { if (tls_alert_value == SSL3_AD_HANDSHAKE_FAILURE && HasParsedFullChlo()) { return; } HandleUnrecoverableError(absl::StrCat( "BoringSSL attempted to send alert ", static_cast<int>(tls_alert_value), " ", SSL_alert_desc_string_long(tls_alert_value))); if (state_ == State::kUnrecoverableFailure) { tls_alert_ = tls_alert_value; } } enum ssl_select_cert_result_t TlsChloExtractor::SelectCertCallback( const SSL_CLIENT_HELLO* client_hello) { GetInstanceFromSSL(client_hello->ssl)->HandleParsedChlo(client_hello); return ssl_select_cert_error; } void TlsChloExtractor::HandleParsedChlo(const SSL_CLIENT_HELLO* client_hello) { const char* server_name = SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name); if (server_name) { server_name_ = std::string(server_name); } resumption_attempted_ = HasExtension(client_hello, TLSEXT_TYPE_pre_shared_key); early_data_attempted_ = HasExtension(client_hello, TLSEXT_TYPE_early_data); QUICHE_DCHECK(client_hello_bytes_.empty()); client_hello_bytes_.assign( client_hello->client_hello, client_hello->client_hello + client_hello->client_hello_len); const uint8_t* alpn_data; size_t alpn_len; int rv = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_application_layer_protocol_negotiation, &alpn_data, &alpn_len); if (rv == 1) { QuicDataReader alpns_reader(reinterpret_cast<const char*>(alpn_data), alpn_len); absl::string_view alpns_payload; if (!alpns_reader.ReadStringPiece16(&alpns_payload)) { HandleUnrecoverableError("Failed to read alpns_payload"); return; } QuicDataReader alpns_payload_reader(alpns_payload); while (!alpns_payload_reader.IsDoneReading()) { absl::string_view alpn_payload; if (!alpns_payload_reader.ReadStringPiece8(&alpn_payload)) { HandleUnrecoverableError("Failed to read alpn_payload"); return; } alpns_.emplace_back(std::string(alpn_payload)); } } supported_groups_ = GetSupportedGroups(client_hello); if (state_ == State::kInitial) { state_ = State::kParsedFullSinglePacketChlo; } else if (state_ == State::kParsedPartialChloFragment) { state_ = State::kParsedFullMultiPacketChlo; } else { QUIC_BUG(quic_bug_10855_4) << "Unexpected state on successful parse " << StateToString(state_); } } std::pair<SSL_CTX*, int> TlsChloExtractor::GetSharedSslHandles() { static std::pair<SSL_CTX*, int>* shared_handles = []() { CRYPTO_library_init(); SSL_CTX* ssl_ctx = SSL_CTX_new(TLS_with_buffers_method()); SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION); static const SSL_QUIC_METHOD kQuicCallbacks{ TlsChloExtractor::SetReadSecretCallback, TlsChloExtractor::SetWriteSecretCallback, TlsChloExtractor::WriteMessageCallback, TlsChloExtractor::FlushFlightCallback, TlsChloExtractor::SendAlertCallback}; SSL_CTX_set_quic_method(ssl_ctx, &kQuicCallbacks); SSL_CTX_set_select_certificate_cb(ssl_ctx, TlsChloExtractor::SelectCertCallback); int ex_data_index = SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); return new std::pair<SSL_CTX*, int>(ssl_ctx, ex_data_index); }(); return *shared_handles; } void TlsChloExtractor::SetupSslHandle() { if (ssl_) { return; } std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); SSL_CTX* ssl_ctx = shared_handles.first; int ex_data_index = shared_handles.second; ssl_ = bssl::UniquePtr<SSL>(SSL_new(ssl_ctx)); const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this); QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data"; SSL_set_accept_state(ssl_.get()); int use_legacy_extension = 0; if (framer_->version().UsesLegacyTlsExtension()) { use_legacy_extension = 1; } SSL_set_quic_use_legacy_codepoint(ssl_.get(), use_legacy_extension); } void TlsChloExtractor::HandleUnrecoverableError( const std::string& error_details) { if (HasParsedFullChlo()) { QUIC_DLOG(ERROR) << "Ignoring error: " << error_details; return; } QUIC_DLOG(ERROR) << "Handling error: " << error_details; state_ = State::kUnrecoverableFailure; if (error_details_.empty()) { error_details_ = error_details; } else { error_details_ = absl::StrCat(error_details_, "; ", error_details); } } std::string TlsChloExtractor::StateToString(State state) { switch (state) { case State::kInitial: return "Initial"; case State::kParsedFullSinglePacketChlo: return "ParsedFullSinglePacketChlo"; case State::kParsedFullMultiPacketChlo: return "ParsedFullMultiPacketChlo"; case State::kParsedPartialChloFragment: return "ParsedPartialChloFragment"; case State::kUnrecoverableFailure: return "UnrecoverableFailure"; } return absl::StrCat("Unknown(", static_cast<int>(state), ")"); } std::ostream& operator<<(std::ostream& os, const TlsChloExtractor::State& state) { os << TlsChloExtractor::StateToString(state); return os; } }
#include "quiche/quic/core/tls_chlo_extractor.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "openssl/ssl.h" #include "quiche/quic/core/http/quic_spdy_client_session.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/first_flight.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" namespace quic { namespace test { namespace { using testing::_; using testing::AnyNumber; class TlsChloExtractorTest : public QuicTestWithParam<ParsedQuicVersion> { protected: TlsChloExtractorTest() : version_(GetParam()), server_id_(TestServerId()) {} void Initialize() { tls_chlo_extractor_ = std::make_unique<TlsChloExtractor>(); AnnotatedPackets packets = GetAnnotatedFirstFlightOfPackets(version_, config_); packets_ = std::move(packets.packets); crypto_stream_size_ = packets.crypto_stream_size; QUIC_DLOG(INFO) << "Initialized with " << packets_.size() << " packets with crypto_stream_size:" << crypto_stream_size_; } void Initialize(std::unique_ptr<QuicCryptoClientConfig> crypto_config) { tls_chlo_extractor_ = std::make_unique<TlsChloExtractor>(); AnnotatedPackets packets = GetAnnotatedFirstFlightOfPackets( version_, config_, TestConnectionId(), EmptyQuicConnectionId(), std::move(crypto_config)); packets_ = std::move(packets.packets); crypto_stream_size_ = packets.crypto_stream_size; QUIC_DLOG(INFO) << "Initialized with " << packets_.size() << " packets with crypto_stream_size:" << crypto_stream_size_; } void PerformFullHandshake(QuicCryptoClientConfig* crypto_config) const { ASSERT_NE(crypto_config->session_cache(), nullptr); MockQuicConnectionHelper client_helper, server_helper; MockAlarmFactory alarm_factory; ParsedQuicVersionVector supported_versions = {version_}; PacketSavingConnection* client_connection = new PacketSavingConnection(&client_helper, &alarm_factory, Perspective::IS_CLIENT, supported_versions); client_connection->AdvanceTime(QuicTime::Delta::FromSeconds(1)); QuicSpdyClientSession client_session(config_, supported_versions, client_connection, server_id_, crypto_config); client_session.Initialize(); std::unique_ptr<QuicCryptoServerConfig> server_crypto_config = crypto_test_utils::CryptoServerConfigForTesting(); QuicConfig server_config; EXPECT_CALL(*client_connection, SendCryptoData(_, _, _)).Times(AnyNumber()); client_session.GetMutableCryptoStream()->CryptoConnect(); crypto_test_utils::HandshakeWithFakeServer( &server_config, server_crypto_config.get(), &server_helper, &alarm_factory, client_connection, client_session.GetMutableCryptoStream(), AlpnForVersion(client_connection->version())); SettingsFrame server_settings; server_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = kDefaultQpackMaxDynamicTableCapacity; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(server_settings); client_session.GetMutableCryptoStream() ->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>( settings_frame.data(), settings_frame.data() + settings_frame.length())); } void IngestPackets() { for (const std::unique_ptr<QuicReceivedPacket>& packet : packets_) { ReceivedPacketInfo packet_info( QuicSocketAddress(TestPeerIPAddress(), kTestPort), QuicSocketAddress(TestPeerIPAddress(), kTestPort), *packet); std::string detailed_error; std::optional<absl::string_view> retry_token; const QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher( *packet, 0, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &retry_token, &detailed_error); ASSERT_THAT(error, IsQuicNoError()) << detailed_error; tls_chlo_extractor_->IngestPacket(packet_info.version, packet_info.packet); } packets_.clear(); } void ValidateChloDetails(const TlsChloExtractor* extractor = nullptr) const { if (extractor == nullptr) { extractor = tls_chlo_extractor_.get(); } EXPECT_TRUE(extractor->HasParsedFullChlo()); std::vector<std::string> alpns = extractor->alpns(); ASSERT_EQ(alpns.size(), 1u); EXPECT_EQ(alpns[0], AlpnForVersion(version_)); EXPECT_EQ(extractor->server_name(), TestHostname()); EXPECT_EQ(extractor->client_hello_bytes().size(), crypto_stream_size_ - 4); } void IncreaseSizeOfChlo() { constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); config_.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; } ParsedQuicVersion version_; QuicServerId server_id_; std::unique_ptr<TlsChloExtractor> tls_chlo_extractor_; QuicConfig config_; std::vector<std::unique_ptr<QuicReceivedPacket>> packets_; uint64_t crypto_stream_size_; }; INSTANTIATE_TEST_SUITE_P(TlsChloExtractorTests, TlsChloExtractorTest, ::testing::ValuesIn(AllSupportedVersionsWithTls()), ::testing::PrintToStringParamName()); TEST_P(TlsChloExtractorTest, Simple) { Initialize(); EXPECT_EQ(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); EXPECT_FALSE(tls_chlo_extractor_->resumption_attempted()); EXPECT_FALSE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_ResumptionOnly) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<SimpleSessionCache>()); PerformFullHandshake(crypto_client_config.get()); SSL_CTX_set_early_data_enabled(crypto_client_config->ssl_ctx(), 0); Initialize(std::move(crypto_client_config)); EXPECT_GE(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); EXPECT_TRUE(tls_chlo_extractor_->resumption_attempted()); EXPECT_FALSE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_ZeroRtt) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<SimpleSessionCache>()); PerformFullHandshake(crypto_client_config.get()); IncreaseSizeOfChlo(); Initialize(std::move(crypto_client_config)); EXPECT_GE(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); EXPECT_TRUE(tls_chlo_extractor_->resumption_attempted()); EXPECT_TRUE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_SupportedGroups) { const std::vector<std::vector<uint16_t>> preferred_groups_to_test = { {SSL_GROUP_X25519}, {SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519}, }; for (const std::vector<uint16_t>& preferred_groups : preferred_groups_to_test) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting()); crypto_client_config->set_preferred_groups(preferred_groups); Initialize(std::move(crypto_client_config)); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->supported_groups(), preferred_groups); } } TEST_P(TlsChloExtractorTest, MultiPacket) { IncreaseSizeOfChlo(); Initialize(); EXPECT_EQ(packets_.size(), 2u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } TEST_P(TlsChloExtractorTest, MultiPacketReordered) { IncreaseSizeOfChlo(); Initialize(); ASSERT_EQ(packets_.size(), 2u); std::swap(packets_[0], packets_[1]); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } TEST_P(TlsChloExtractorTest, MoveAssignment) { Initialize(); EXPECT_EQ(packets_.size(), 1u); TlsChloExtractor other_extractor; *tls_chlo_extractor_ = std::move(other_extractor); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); } TEST_P(TlsChloExtractorTest, MoveAssignmentAfterExtraction) { Initialize(); EXPECT_EQ(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); TlsChloExtractor other_extractor = std::move(*tls_chlo_extractor_); EXPECT_EQ(other_extractor.state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); ValidateChloDetails(&other_extractor); } TEST_P(TlsChloExtractorTest, MoveAssignmentBetweenPackets) { IncreaseSizeOfChlo(); Initialize(); ASSERT_EQ(packets_.size(), 2u); TlsChloExtractor other_extractor; ReceivedPacketInfo packet_info( QuicSocketAddress(TestPeerIPAddress(), kTestPort), QuicSocketAddress(TestPeerIPAddress(), kTestPort), *packets_[0]); std::string detailed_error; std::optional<absl::string_view> retry_token; const QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher( *packets_[0], 0, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &retry_token, &detailed_error); ASSERT_THAT(error, IsQuicNoError()) << detailed_error; other_extractor.IngestPacket(packet_info.version, packet_info.packet); packets_.erase(packets_.begin()); EXPECT_EQ(packets_.size(), 1u); *tls_chlo_extractor_ = std::move(other_extractor); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } } } }
259
cpp
google/quiche
quic_stream_sequencer_buffer
quiche/quic/core/quic_stream_sequencer_buffer.cc
quiche/quic/core/quic_stream_sequencer_buffer_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_SEQUENCER_BUFFER_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_SEQUENCER_BUFFER_H_ #include <cstddef> #include <functional> #include <list> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_interval_set.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_iovec.h" namespace quic { namespace test { class QuicStreamSequencerBufferPeer; } class QUICHE_EXPORT QuicStreamSequencerBuffer { public: static const size_t kBlockSizeBytes = 8 * 1024; struct QUICHE_EXPORT BufferBlock { char buffer[kBlockSizeBytes]; }; explicit QuicStreamSequencerBuffer(size_t max_capacity_bytes); QuicStreamSequencerBuffer(const QuicStreamSequencerBuffer&) = delete; QuicStreamSequencerBuffer(QuicStreamSequencerBuffer&&) = default; QuicStreamSequencerBuffer& operator=(const QuicStreamSequencerBuffer&) = delete; QuicStreamSequencerBuffer& operator=(QuicStreamSequencerBuffer&&) = default; ~QuicStreamSequencerBuffer(); void Clear(); bool Empty() const; QuicErrorCode OnStreamData(QuicStreamOffset offset, absl::string_view data, size_t* bytes_buffered, std::string* error_details); QuicErrorCode Readv(const struct iovec* dest_iov, size_t dest_count, size_t* bytes_read, std::string* error_details); int GetReadableRegions(struct iovec* iov, int iov_len) const; bool GetReadableRegion(iovec* iov) const; bool PeekRegion(QuicStreamOffset offset, iovec* iov) const; bool MarkConsumed(size_t bytes_consumed); size_t FlushBufferedFrames(); void ReleaseWholeBuffer(); bool HasBytesToRead() const; QuicStreamOffset BytesConsumed() const; size_t BytesBuffered() const; size_t ReadableBytes() const; QuicStreamOffset FirstMissingByte() const; QuicStreamOffset NextExpectedByte() const; std::string ReceivedFramesDebugString() const; private: friend class test::QuicStreamSequencerBufferPeer; bool CopyStreamData(QuicStreamOffset offset, absl::string_view data, size_t* bytes_copy, std::string* error_details); bool RetireBlock(size_t index); bool RetireBlockIfEmpty(size_t block_index); size_t GetBlockCapacity(size_t index) const; size_t GetBlockIndex(QuicStreamOffset offset) const; size_t GetInBlockOffset(QuicStreamOffset offset) const; size_t ReadOffset() const; size_t NextBlockToRead() const; void MaybeAddMoreBlocks(QuicStreamOffset next_expected_byte); size_t max_buffer_capacity_bytes_; size_t max_blocks_count_; size_t current_blocks_count_; QuicStreamOffset total_bytes_read_; std::unique_ptr<BufferBlock*[]> blocks_; size_t num_bytes_buffered_; QuicIntervalSet<QuicStreamOffset> bytes_received_; }; } #endif #include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include <algorithm> #include <cstddef> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_interval.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { size_t CalculateBlockCount(size_t max_capacity_bytes) { return (max_capacity_bytes + QuicStreamSequencerBuffer::kBlockSizeBytes - 1) / QuicStreamSequencerBuffer::kBlockSizeBytes; } const size_t kMaxNumDataIntervalsAllowed = 2 * kMaxPacketGap; constexpr size_t kInitialBlockCount = 8u; constexpr int kBlocksGrowthFactor = 4; } QuicStreamSequencerBuffer::QuicStreamSequencerBuffer(size_t max_capacity_bytes) : max_buffer_capacity_bytes_(max_capacity_bytes), max_blocks_count_(CalculateBlockCount(max_capacity_bytes)), current_blocks_count_(0u), total_bytes_read_(0), blocks_(nullptr) { QUICHE_DCHECK_GE(max_blocks_count_, kInitialBlockCount); Clear(); } QuicStreamSequencerBuffer::~QuicStreamSequencerBuffer() { Clear(); } void QuicStreamSequencerBuffer::Clear() { if (blocks_ != nullptr) { for (size_t i = 0; i < current_blocks_count_; ++i) { if (blocks_[i] != nullptr) { RetireBlock(i); } } } num_bytes_buffered_ = 0; bytes_received_.Clear(); bytes_received_.Add(0, total_bytes_read_); } bool QuicStreamSequencerBuffer::RetireBlock(size_t index) { if (blocks_[index] == nullptr) { QUIC_BUG(quic_bug_10610_1) << "Try to retire block twice"; return false; } delete blocks_[index]; blocks_[index] = nullptr; QUIC_DVLOG(1) << "Retired block with index: " << index; return true; } void QuicStreamSequencerBuffer::MaybeAddMoreBlocks( QuicStreamOffset next_expected_byte) { if (current_blocks_count_ == max_blocks_count_) { return; } QuicStreamOffset last_byte = next_expected_byte - 1; size_t num_of_blocks_needed; if (last_byte < max_buffer_capacity_bytes_) { num_of_blocks_needed = std::max(GetBlockIndex(last_byte) + 1, kInitialBlockCount); } else { num_of_blocks_needed = max_blocks_count_; } if (current_blocks_count_ >= num_of_blocks_needed) { return; } size_t new_block_count = kBlocksGrowthFactor * current_blocks_count_; new_block_count = std::min(std::max(new_block_count, num_of_blocks_needed), max_blocks_count_); auto new_blocks = std::make_unique<BufferBlock*[]>(new_block_count); if (blocks_ != nullptr) { memcpy(new_blocks.get(), blocks_.get(), current_blocks_count_ * sizeof(BufferBlock*)); } blocks_ = std::move(new_blocks); current_blocks_count_ = new_block_count; } QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, absl::string_view data, size_t* const bytes_buffered, std::string* error_details) { *bytes_buffered = 0; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } if (starting_offset + size > total_bytes_read_ + max_buffer_capacity_bytes_ || starting_offset + size < starting_offset) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (bytes_received_.Empty() || starting_offset >= bytes_received_.rbegin()->max() || bytes_received_.IsDisjoint(QuicInterval<QuicStreamOffset>( starting_offset, starting_offset + size))) { bytes_received_.AddOptimizedForAppend(starting_offset, starting_offset + size); if (bytes_received_.Size() >= kMaxNumDataIntervalsAllowed) { *error_details = "Too many data intervals received for this stream."; return QUIC_TOO_MANY_STREAM_DATA_INTERVALS; } MaybeAddMoreBlocks(starting_offset + size); size_t bytes_copy = 0; if (!CopyStreamData(starting_offset, data, &bytes_copy, error_details)) { return QUIC_STREAM_SEQUENCER_INVALID_STATE; } *bytes_buffered += bytes_copy; num_bytes_buffered_ += *bytes_buffered; return QUIC_NO_ERROR; } QuicIntervalSet<QuicStreamOffset> newly_received(starting_offset, starting_offset + size); newly_received.Difference(bytes_received_); if (newly_received.Empty()) { return QUIC_NO_ERROR; } bytes_received_.Add(starting_offset, starting_offset + size); if (bytes_received_.Size() >= kMaxNumDataIntervalsAllowed) { *error_details = "Too many data intervals received for this stream."; return QUIC_TOO_MANY_STREAM_DATA_INTERVALS; } MaybeAddMoreBlocks(starting_offset + size); for (const auto& interval : newly_received) { const QuicStreamOffset copy_offset = interval.min(); const QuicByteCount copy_length = interval.max() - interval.min(); size_t bytes_copy = 0; if (!CopyStreamData(copy_offset, data.substr(copy_offset - starting_offset, copy_length), &bytes_copy, error_details)) { return QUIC_STREAM_SEQUENCER_INVALID_STATE; } *bytes_buffered += bytes_copy; } num_bytes_buffered_ += *bytes_buffered; return QUIC_NO_ERROR; } bool QuicStreamSequencerBuffer::CopyStreamData(QuicStreamOffset offset, absl::string_view data, size_t* bytes_copy, std::string* error_details) { *bytes_copy = 0; size_t source_remaining = data.size(); if (source_remaining == 0) { return true; } const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); size_t current_blocks_count = current_blocks_count_; QUICHE_DCHECK_GT(current_blocks_count, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (write_block_num >= current_blocks_count) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " current_blocks_count_ = ", current_blocks_count); return false; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return false; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Received frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return false; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; *bytes_copy += bytes_to_copy; } return true; } QuicErrorCode QuicStreamSequencerBuffer::Readv(const iovec* dest_iov, size_t dest_count, size_t* bytes_read, std::string* error_details) { *bytes_read = 0; for (size_t i = 0; i < dest_count && ReadableBytes() > 0; ++i) { char* dest = reinterpret_cast<char*>(dest_iov[i].iov_base); QUICHE_DCHECK(dest != nullptr); size_t dest_remaining = dest_iov[i].iov_len; while (dest_remaining > 0 && ReadableBytes() > 0) { size_t block_idx = NextBlockToRead(); size_t start_offset_in_block = ReadOffset(); size_t block_capacity = GetBlockCapacity(block_idx); size_t bytes_available_in_block = std::min<size_t>( ReadableBytes(), block_capacity - start_offset_in_block); size_t bytes_to_copy = std::min<size_t>(bytes_available_in_block, dest_remaining); QUICHE_DCHECK_GT(bytes_to_copy, 0u); if (blocks_[block_idx] == nullptr || dest == nullptr) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error:" " Readv() dest == nullptr: ", (dest == nullptr), " blocks_[", block_idx, "] == nullptr: ", (blocks_[block_idx] == nullptr), " Received frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, blocks_[block_idx]->buffer + start_offset_in_block, bytes_to_copy); dest += bytes_to_copy; dest_remaining -= bytes_to_copy; num_bytes_buffered_ -= bytes_to_copy; total_bytes_read_ += bytes_to_copy; *bytes_read += bytes_to_copy; if (bytes_to_copy == bytes_available_in_block) { bool retire_successfully = RetireBlockIfEmpty(block_idx); if (!retire_successfully) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: fail to retire block ", block_idx, " as the block is already released, total_bytes_read_ = ", total_bytes_read_, " Received frames: ", ReceivedFramesDebugString()); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } } } } return QUIC_NO_ERROR; } int QuicStreamSequencerBuffer::GetReadableRegions(struct iovec* iov, int iov_len) const { QUICHE_DCHECK(iov != nullptr); QUICHE_DCHECK_GT(iov_len, 0); if (ReadableBytes() == 0) { iov[0].iov_base = nullptr; iov[0].iov_len = 0; return 0; } size_t start_block_idx = NextBlockToRead(); QuicStreamOffset readable_offset_end = FirstMissingByte() - 1; QUICHE_DCHECK_GE(readable_offset_end + 1, total_bytes_read_); size_t end_block_offset = GetInBlockOffset(readable_offset_end); size_t end_block_idx = GetBlockIndex(readable_offset_end); if (start_block_idx == end_block_idx && ReadOffset() <= end_block_offset) { iov[0].iov_base = blocks_[start_block_idx]->buffer + ReadOffset(); iov[0].iov_len = ReadableBytes(); QUIC_DVLOG(1) << "Got only a single block with index: " << start_block_idx; return 1; } iov[0].iov_base = blocks_[start_block_idx]->buffer + ReadOffset(); iov[0].iov_len = GetBlockCapacity(start_block_idx) - ReadOffset(); QUIC_DVLOG(1) << "Got first block " << start_block_idx << " with len " << iov[0].iov_len; QUICHE_DCHECK_GT(readable_offset_end + 1, total_bytes_read_ + iov[0].iov_len) << "there should be more available data"; int iov_used = 1; size_t block_idx = (start_block_idx + iov_used) % max_blocks_count_; while (block_idx != end_block_idx && iov_used < iov_len) { QUICHE_DCHECK(nullptr != blocks_[block_idx]); iov[iov_used].iov_base = blocks_[block_idx]->buffer; iov[iov_used].iov_len = GetBlockCapacity(block_idx); QUIC_DVLOG(1) << "Got block with index: " << block_idx; ++iov_used; block_idx = (start_block_idx + iov_used) % max_blocks_count_; } if (iov_used < iov_len) { QUICHE_DCHECK(nullptr != blocks_[block_idx]); iov[iov_used].iov_base = blocks_[end_block_idx]->buffer; iov[iov_used].iov_len = end_block_offset + 1; QUIC_DVLOG(1) << "Got last block with index: " << end_block_idx; ++iov_used; } return iov_used; } bool QuicStreamSequencerBuffer::GetReadableRegion(iovec* iov) const { return GetReadableRegions(iov, 1) == 1; } bool QuicStreamSequencerBuffer::PeekRegion(QuicStreamOffset offset, iovec* iov) const { QUICHE_DCHECK(iov); if (offset < total_bytes_read_) { return false; } if (offset >= FirstMissingByte()) { return false; } size_t block_idx = GetBlockIndex(offset); size_t block_offset = GetInBlockOffset(offset); iov->iov_base = blocks_[block_idx]->buffer + block_offset; size_t end_block_idx = GetBlockIndex(FirstMissingByte()); if (block_idx == end_block_idx) { iov->iov_len = GetInBlockOffset(FirstMissingByte()) - block_offset; } else { iov->iov_len = GetBlockCapacity(block_idx) - block_offset; } return true; } bool QuicStreamSequencerBuffer::MarkConsumed(size_t bytes_consumed) { if (bytes_consumed > ReadableBytes()) { return false; } size_t bytes_to_consume = bytes_consumed; while (bytes_to_consume > 0) { size_t block_idx = NextBlockToRead(); size_t offset_in_block = ReadOffset(); size_t bytes_available = std::min<size_t>( ReadableBytes(), GetBlockCapacity(block_idx) - offset_in_block); size_t bytes_read = std::min<size_t>(bytes_to_consume, bytes_available); total_bytes_read_ += bytes_read; num_bytes_buffered_ -= bytes_read; bytes_to_consume -= bytes_read; if (bytes_available == bytes_read) { RetireBlockIfEmpty(block_idx); } } return true; } size_t QuicStreamSequencerBuffer::FlushBufferedFrames() { size_t prev_total_bytes_read = total_bytes_read_; total_bytes_read_ = NextExpectedByte(); Clear(); return total_bytes_read_ - prev_total_bytes_read; } void QuicStreamSequencerBuffer::ReleaseWholeBuffer() { Clear(); current_blocks_count_ = 0; blocks_.reset(nullptr); } size_t QuicStreamSequencerBuffer::ReadableBytes() const { return FirstMissingByte() - total_bytes_read_; } bool QuicStreamSequencerBuffer::HasBytesToRead() const { return ReadableBytes() > 0; } QuicStreamOffset QuicStreamSequencerBuffer::BytesConsumed() const { return total_bytes_read_; } size_t QuicStreamSequencerBuffer::BytesBuffered() const { return num_bytes_buffered_; } size_t QuicStreamSequencerBuffer::GetBlockIndex(QuicStreamOffset offset) const { return (offset % max_buffer_capacity_bytes_) / kBlockSizeBytes; } size_t QuicStreamSequencerBuffer::GetInBlockOffset( QuicStreamOffset offset) const { return (offset % max_buffer_capacity_bytes_) % kBlockSizeBytes; } size_t QuicStreamSequencerBuffer::ReadOffset() const { return GetInBlockOffset(total_bytes_read_); } size_t QuicStreamSequencerBuffer::NextBlockToRead() const { return GetBlockIndex(total_bytes_read_); } bool QuicStreamSequencerBuffer::RetireBlockIfEmpty(size_t block_index) { QUICHE_DCHECK(ReadableBytes() == 0 || GetInBlockOffset(total_bytes_read_) == 0) << "RetireBlockIfEmpty() should only be called when advancing to next " << "block or a gap has been reached."; if (Empty()) { return RetireBlock(block_index); } if (GetBlockIndex(NextExpectedByte() - 1) == block_index) { return true; } if (NextBlockToRead() == block_index) { if (bytes_received_.Size() > 1) { auto it = bytes_received_.begin(); ++it; if (GetBlockIndex(it->min()) == block_index) { return true; } } else { QUIC_BUG(quic_bug_10610_2) << "Read stopped at where it shouldn't."; return false; } } return RetireBlock(block_index); } bool QuicStreamSequencerBuffer::Empty() const { return bytes_received_.Empty() || (bytes_received_.Size() == 1 && total_bytes_read_ > 0 && bytes_received_.begin()->max() == total_bytes_read_); } size_t QuicStreamSequencerBuffer::GetBlockCapacity(size_t block_index) const { if ((block_index + 1) == max_blocks_count_) { size_t result = max_buffer_capacity_bytes_ % kBlockSizeBytes; if (result == 0) { result = kBlockSizeBytes; } return result; } else { return kBlockSizeBytes; } } std::string QuicStreamSequencerBuffer::ReceivedFramesDebugString() const { return bytes_received_.ToString(); } QuicStreamOffset QuicStreamSequencerBuffer::FirstMissingByte() const { if (bytes_received_.Empty() || bytes_received_.begin()->min() > 0) { return 0; } return bytes_received_.begin()->max(); } QuicStreamOffset QuicStreamSequencerBuffer::NextExpectedByte() const { if (bytes_received_.Empty()) { return 0; } return bytes_received_.rbegin()->max(); } }
#include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_sequencer_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { absl::string_view IovecToStringPiece(iovec iov) { return absl::string_view(reinterpret_cast<const char*>(iov.iov_base), iov.iov_len); } char GetCharFromIOVecs(size_t offset, iovec iov[], size_t count) { size_t start_offset = 0; for (size_t i = 0; i < count; i++) { if (iov[i].iov_len == 0) { continue; } size_t end_offset = start_offset + iov[i].iov_len - 1; if (offset >= start_offset && offset <= end_offset) { const char* buf = reinterpret_cast<const char*>(iov[i].iov_base); return buf[offset - start_offset]; } start_offset += iov[i].iov_len; } QUIC_LOG(ERROR) << "Could not locate char at offset " << offset << " in " << count << " iovecs"; for (size_t i = 0; i < count; ++i) { QUIC_LOG(ERROR) << " iov[" << i << "].iov_len = " << iov[i].iov_len; } return '\0'; } const size_t kMaxNumGapsAllowed = 2 * kMaxPacketGap; static const size_t kBlockSizeBytes = QuicStreamSequencerBuffer::kBlockSizeBytes; using BufferBlock = QuicStreamSequencerBuffer::BufferBlock; namespace { class QuicStreamSequencerBufferTest : public QuicTest { public: void SetUp() override { Initialize(); } void ResetMaxCapacityBytes(size_t max_capacity_bytes) { max_capacity_bytes_ = max_capacity_bytes; Initialize(); } protected: void Initialize() { buffer_ = std::make_unique<QuicStreamSequencerBuffer>((max_capacity_bytes_)); helper_ = std::make_unique<QuicStreamSequencerBufferPeer>((buffer_.get())); } size_t max_capacity_bytes_ = 8.5 * kBlockSizeBytes; std::unique_ptr<QuicStreamSequencerBuffer> buffer_; std::unique_ptr<QuicStreamSequencerBufferPeer> helper_; size_t written_ = 0; std::string error_details_; }; TEST_F(QuicStreamSequencerBufferTest, InitializeWithMaxRecvWindowSize) { ResetMaxCapacityBytes(16 * 1024 * 1024); EXPECT_EQ(2 * 1024u, helper_->max_blocks_count()); EXPECT_EQ(max_capacity_bytes_, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); } TEST_F(QuicStreamSequencerBufferTest, InitializationWithDifferentSizes) { const size_t kCapacity = 16 * QuicStreamSequencerBuffer::kBlockSizeBytes; ResetMaxCapacityBytes(kCapacity); EXPECT_EQ(max_capacity_bytes_, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); const size_t kCapacity1 = 32 * QuicStreamSequencerBuffer::kBlockSizeBytes; ResetMaxCapacityBytes(kCapacity1); EXPECT_EQ(kCapacity1, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); } TEST_F(QuicStreamSequencerBufferTest, ClearOnEmpty) { buffer_->Clear(); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamData0length) { QuicErrorCode error = buffer_->OnStreamData(800, "", &written_, &error_details_); EXPECT_THAT(error, IsError(QUIC_EMPTY_STREAM_FRAME_NO_FIN)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithinBlock) { EXPECT_FALSE(helper_->IsBufferAllocated()); std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); BufferBlock* block_ptr = helper_->GetBlock(0); for (size_t i = 0; i < source.size(); ++i) { ASSERT_EQ('a', block_ptr->buffer[helper_->GetInBlockOffset(800) + i]); } EXPECT_EQ(2, helper_->IntervalSize()); EXPECT_EQ(0u, helper_->ReadableBytes()); EXPECT_EQ(1u, helper_->bytes_received().Size()); EXPECT_EQ(800u, helper_->bytes_received().begin()->min()); EXPECT_EQ(1824u, helper_->bytes_received().begin()->max()); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_TRUE(helper_->IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, Move) { EXPECT_FALSE(helper_->IsBufferAllocated()); std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); BufferBlock* block_ptr = helper_->GetBlock(0); for (size_t i = 0; i < source.size(); ++i) { ASSERT_EQ('a', block_ptr->buffer[helper_->GetInBlockOffset(800) + i]); } QuicStreamSequencerBuffer buffer2(std::move(*buffer_)); QuicStreamSequencerBufferPeer helper2(&buffer2); EXPECT_FALSE(helper_->IsBufferAllocated()); EXPECT_EQ(2, helper2.IntervalSize()); EXPECT_EQ(0u, helper2.ReadableBytes()); EXPECT_EQ(1u, helper2.bytes_received().Size()); EXPECT_EQ(800u, helper2.bytes_received().begin()->min()); EXPECT_EQ(1824u, helper2.bytes_received().begin()->max()); EXPECT_TRUE(helper2.CheckBufferInvariants()); EXPECT_TRUE(helper2.IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, DISABLED_OnStreamDataInvalidSource) { absl::string_view source; source = absl::string_view(nullptr, 1024); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsError(QUIC_STREAM_SEQUENCER_INVALID_STATE)); EXPECT_EQ(0u, error_details_.find(absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData() " "dest == nullptr: ", false, " source == nullptr: ", true))); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithOverlap) { std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(0, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(1024, source, &written_, &error_details_), IsQuicNoError()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataOverlapAndDuplicateCornerCases) { std::string source(1024, 'a'); buffer_->OnStreamData(800, source, &written_, &error_details_); source = std::string(800, 'b'); std::string one_byte = "c"; EXPECT_THAT(buffer_->OnStreamData(1, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(0, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(1823, one_byte, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(0u, written_); EXPECT_THAT(buffer_->OnStreamData(1824, one_byte, &written_, &error_details_), IsQuicNoError()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithoutOverlap) { std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); source = std::string(100, 'b'); EXPECT_THAT(buffer_->OnStreamData(kBlockSizeBytes * 2 - 20, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(3, helper_->IntervalSize()); EXPECT_EQ(1024u + 100u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataInLongStreamWithOverlap) { uint64_t total_bytes_read = pow(2, 32) - 1; helper_->set_total_bytes_read(total_bytes_read); helper_->AddBytesReceived(0, total_bytes_read); const size_t kBytesToWrite = 100; std::string source(kBytesToWrite, 'a'); QuicStreamOffset offset = pow(2, 32) + 500; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(2, helper_->IntervalSize()); offset = pow(2, 32) + 700; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(3, helper_->IntervalSize()); offset = pow(2, 32) + 300; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(4, helper_->IntervalSize()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataTillEnd) { const size_t kBytesToWrite = 50; std::string source(kBytesToWrite, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - kBytesToWrite, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(50u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataTillEndCorner) { const size_t kBytesToWrite = 1; std::string source(kBytesToWrite, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - kBytesToWrite, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(1u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataBeyondCapacity) { std::string source(60, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - 50, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); source = "b"; EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ * 1000, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_THAT(buffer_->OnStreamData(static_cast<QuicStreamOffset>(-1), source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); source = "bbb"; EXPECT_THAT(buffer_->OnStreamData(static_cast<QuicStreamOffset>(-2), source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_EQ(0u, buffer_->BytesBuffered()); } TEST_F(QuicStreamSequencerBufferTest, Readv100Bytes) { std::string source(1024, 'a'); buffer_->OnStreamData(kBlockSizeBytes, source, &written_, &error_details_); EXPECT_FALSE(buffer_->HasBytesToRead()); source = std::string(100, 'b'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_TRUE(buffer_->HasBytesToRead()); char dest[120]; iovec iovecs[3]{iovec{dest, 40}, iovec{dest + 40, 40}, iovec{dest + 80, 40}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 3, &read, &error_details_), IsQuicNoError()); QUIC_LOG(ERROR) << error_details_; EXPECT_EQ(100u, read); EXPECT_EQ(100u, buffer_->BytesConsumed()); EXPECT_EQ(source, absl::string_view(dest, read)); EXPECT_EQ(nullptr, helper_->GetBlock(0)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvAcrossBlocks) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_EQ(source.size(), helper_->ReadableBytes()); char dest[512]; while (helper_->ReadableBytes()) { std::fill(dest, dest + 512, 0); iovec iovecs[2]{iovec{dest, 256}, iovec{dest + 256, 256}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 2, &read, &error_details_), IsQuicNoError()); } EXPECT_EQ(std::string(50, 'a'), std::string(dest, 50)); EXPECT_EQ(0, dest[50]) << "Dest[50] shouln't be filled."; EXPECT_EQ(source.size(), buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ClearAfterRead) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); buffer_->Clear(); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataAcrossLastBlockAndFillCapacity) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(source.size(), written_); source = std::string(0.5 * kBlockSizeBytes + 512, 'b'); EXPECT_THAT(buffer_->OnStreamData(2 * kBlockSizeBytes, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(source.size(), written_); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataAcrossLastBlockAndExceedCapacity) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); source = std::string(0.5 * kBlockSizeBytes + 512 + 1, 'b'); EXPECT_THAT(buffer_->OnStreamData(8 * kBlockSizeBytes, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvAcrossLastBlock) { std::string source(max_capacity_bytes_, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); source = std::string(256, 'b'); buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_); EXPECT_TRUE(helper_->CheckBufferInvariants()); std::unique_ptr<char[]> dest1{new char[max_capacity_bytes_]}; dest1[0] = 0; const iovec iov1{dest1.get(), max_capacity_bytes_}; EXPECT_THAT(buffer_->Readv(&iov1, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(max_capacity_bytes_ - 512 + 256, read); EXPECT_EQ(max_capacity_bytes_ + 256, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvEmpty) { char dest[512]{0}; iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(0u, read); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsEmpty) { iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(0, iov_count); EXPECT_EQ(nullptr, iovs[iov_count].iov_base); EXPECT_EQ(0u, iovs[iov_count].iov_len); } TEST_F(QuicStreamSequencerBufferTest, ReleaseWholeBuffer) { std::string source(100, 'b'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_TRUE(buffer_->HasBytesToRead()); char dest[120]; iovec iovecs[3]{iovec{dest, 40}, iovec{dest + 40, 40}, iovec{dest + 80, 40}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 3, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(100u, read); EXPECT_EQ(100u, buffer_->BytesConsumed()); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_TRUE(helper_->IsBufferAllocated()); buffer_->ReleaseWholeBuffer(); EXPECT_FALSE(helper_->IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsBlockedByGap) { std::string source(1023, 'a'); buffer_->OnStreamData(1, source, &written_, &error_details_); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(0, iov_count); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsTillEndOfBlock) { std::string source(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(1, iov_count); EXPECT_EQ(std::string(kBlockSizeBytes - 256, 'a'), IovecToStringPiece(iovs[0])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsWithinOneBlock) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(1, iov_count); EXPECT_EQ(std::string(1024 - 256, 'a'), IovecToStringPiece(iovs[0])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsAcrossBlockWithLongIOV) { std::string source(2 * kBlockSizeBytes + 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); iovec iovs[4]; int iov_count = buffer_->GetReadableRegions(iovs, 4); EXPECT_EQ(3, iov_count); EXPECT_EQ(kBlockSizeBytes - 1024, iovs[0].iov_len); EXPECT_EQ(kBlockSizeBytes, iovs[1].iov_len); EXPECT_EQ(1024u, iovs[2].iov_len); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsWithMultipleIOVsAcrossEnd) { std::string source(8.5 * kBlockSizeBytes - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); source = std::string(1024 + 512, 'b'); buffer_->OnStreamData(8.5 * kBlockSizeBytes - 1024, source, &written_, &error_details_); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(2, iov_count); EXPECT_EQ(kBlockSizeBytes - 1024, iovs[0].iov_len); EXPECT_EQ(kBlockSizeBytes, iovs[1].iov_len); iovec iovs1[11]; EXPECT_EQ(10, buffer_->GetReadableRegions(iovs1, 11)); EXPECT_EQ(0.5 * kBlockSizeBytes, iovs1[8].iov_len); EXPECT_EQ(512u, iovs1[9].iov_len); EXPECT_EQ(std::string(512, 'b'), IovecToStringPiece(iovs1[9])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionEmpty) { iovec iov; EXPECT_FALSE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(nullptr, iov.iov_base); EXPECT_EQ(0u, iov.iov_len); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionBeforeGap) { std::string source(1023, 'a'); buffer_->OnStreamData(1, source, &written_, &error_details_); iovec iov; EXPECT_FALSE(buffer_->GetReadableRegion(&iov)); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionTillEndOfBlock) { std::string source(kBlockSizeBytes + 1, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(std::string(kBlockSizeBytes - 256, 'a'), IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionTillGap) { std::string source(kBlockSizeBytes - 1, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(std::string(kBlockSizeBytes - 1 - 256, 'a'), IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekEmptyBuffer) { iovec iov; EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1, &iov)); EXPECT_FALSE(buffer_->PeekRegion(100, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekSingleBlock) { std::string source(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(100, &iov)); EXPECT_EQ(absl::string_view(source).substr(100), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_FALSE(buffer_->PeekRegion(kBlockSizeBytes + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekTwoWritesInSingleBlock) { const size_t length1 = 1024; std::string source1(length1, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); const size_t length2 = 800; std::string source2(length2, 'b'); buffer_->OnStreamData(length1, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(length1, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); const QuicStreamOffset offset1 = 500; EXPECT_TRUE(buffer_->PeekRegion(offset1, &iov)); EXPECT_EQ(absl::string_view(source1).substr(offset1), IovecToStringPiece(iov).substr(0, length1 - offset1)); EXPECT_EQ(absl::string_view(source2), IovecToStringPiece(iov).substr(length1 - offset1)); const QuicStreamOffset offset2 = 1500; EXPECT_TRUE(buffer_->PeekRegion(offset2, &iov)); EXPECT_EQ(absl::string_view(source2).substr(offset2 - length1), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2, &iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2 + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekBufferWithMultipleBlocks) { const size_t length1 = 1024; std::string source1(length1, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); const size_t length2 = kBlockSizeBytes + 2; std::string source2(length2, 'b'); buffer_->OnStreamData(length1, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(kBlockSizeBytes, iov.iov_len); EXPECT_EQ(source1, IovecToStringPiece(iov).substr(0, length1)); EXPECT_EQ(absl::string_view(source2).substr(0, kBlockSizeBytes - length1), IovecToStringPiece(iov).substr(length1)); EXPECT_TRUE(buffer_->PeekRegion(length1, &iov)); EXPECT_EQ(absl::string_view(source2).substr(0, kBlockSizeBytes - length1), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(absl::string_view(source2).substr(kBlockSizeBytes - length1), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2, &iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2 + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekAfterConsumed) { std::string source1(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->MarkConsumed(1024)); EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(512, &iov)); EXPECT_TRUE(buffer_->PeekRegion(1024, &iov)); EXPECT_EQ(absl::string_view(source1).substr(1024), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(1500, &iov)); EXPECT_EQ(absl::string_view(source1).substr(1500), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->MarkConsumed(kBlockSizeBytes - 1024)); std::string source2(300, 'b'); buffer_->OnStreamData(kBlockSizeBytes, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes + 128, &iov)); EXPECT_EQ(absl::string_view(source2).substr(128), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(512, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1024, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1500, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekContinously) { std::string source1(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); std::string source2(kBlockSizeBytes, 'b'); buffer_->OnStreamData(kBlockSizeBytes, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedInOneBlock) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); EXPECT_TRUE(buffer_->MarkConsumed(512)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); EXPECT_EQ(256u, helper_->ReadableBytes()); buffer_->MarkConsumed(256); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedNotEnoughBytes) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); EXPECT_TRUE(buffer_->MarkConsumed(512)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); EXPECT_EQ(256u, helper_->ReadableBytes()); EXPECT_FALSE(buffer_->MarkConsumed(257)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedAcrossBlock) { std::string source(2 * kBlockSizeBytes + 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); buffer_->MarkConsumed(2 * kBlockSizeBytes); EXPECT_EQ(source.size(), buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedAcrossEnd) { std::string source(8.5 * kBlockSizeBytes - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); source = std::string(1024 + 512, 'b'); buffer_->OnStreamData(8.5 * kBlockSizeBytes - 1024, source, &written_, &error_details_); EXPECT_EQ(1024u, buffer_->BytesConsumed()); buffer_->MarkConsumed(8 * kBlockSizeBytes - 1024); EXPECT_EQ(8 * kBlockSizeBytes, buffer_->BytesConsumed()); buffer_->MarkConsumed(0.5 * kBlockSizeBytes + 500); EXPECT_EQ(max_capacity_bytes_ + 500, buffer_->BytesConsumed()); EXPECT_EQ(12u, helper_->ReadableBytes()); buffer_->MarkConsumed(12); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, FlushBufferedFrames) { std::string source(max_capacity_bytes_ - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); EXPECT_EQ(1024u, buffer_->BytesConsumed()); source = std::string(512, 'b'); buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_); EXPECT_EQ(512u, written_); EXPECT_EQ(max_capacity_bytes_ - 1024 + 512, buffer_->FlushBufferedFrames()); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); buffer_->Clear(); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(helper_->CheckBuffe
260
cpp
google/quiche
quic_utils
quiche/quic/core/quic_utils.cc
quiche/quic/core/quic_utils_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_UTILS_H_ #define QUICHE_QUIC_CORE_QUIC_UTILS_H_ #include <cstddef> #include <cstdint> #include <initializer_list> #include <optional> #include <string> #include <type_traits> #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace quic { class QUICHE_EXPORT QuicUtils { public: QuicUtils() = delete; static uint64_t FNV1a_64_Hash(absl::string_view data); static absl::uint128 FNV1a_128_Hash(absl::string_view data); static absl::uint128 FNV1a_128_Hash_Two(absl::string_view data1, absl::string_view data2); static absl::uint128 FNV1a_128_Hash_Three(absl::string_view data1, absl::string_view data2, absl::string_view data3); static void SerializeUint128Short(absl::uint128 v, uint8_t* out); static std::string AddressChangeTypeToString(AddressChangeType type); static const char* SentPacketStateToString(SentPacketState state); static const char* QuicLongHeaderTypetoString(QuicLongHeaderType type); static const char* AckResultToString(AckResult result); static AddressChangeType DetermineAddressChangeType( const QuicSocketAddress& old_address, const QuicSocketAddress& new_address); static constexpr Perspective InvertPerspective(Perspective perspective) { return perspective == Perspective::IS_CLIENT ? Perspective::IS_SERVER : Perspective::IS_CLIENT; } static bool IsAckable(SentPacketState state); static bool IsRetransmittableFrame(QuicFrameType type); static bool IsHandshakeFrame(const QuicFrame& frame, QuicTransportVersion transport_version); static bool ContainsFrameType(const QuicFrames& frames, QuicFrameType type); static SentPacketState RetransmissionTypeToPacketState( TransmissionType retransmission_type); static bool IsIetfPacketHeader(uint8_t first_byte); static bool IsIetfPacketShortHeader(uint8_t first_byte); static QuicStreamId GetInvalidStreamId(QuicTransportVersion version); static QuicStreamId GetCryptoStreamId(QuicTransportVersion version); static bool IsCryptoStreamId(QuicTransportVersion version, QuicStreamId id); static QuicStreamId GetHeadersStreamId(QuicTransportVersion version); static bool IsClientInitiatedStreamId(QuicTransportVersion version, QuicStreamId id); static bool IsServerInitiatedStreamId(QuicTransportVersion version, QuicStreamId id); static bool IsOutgoingStreamId(ParsedQuicVersion version, QuicStreamId id, Perspective perspective); static bool IsBidirectionalStreamId(QuicStreamId id, ParsedQuicVersion version); static StreamType GetStreamType(QuicStreamId id, Perspective perspective, bool peer_initiated, ParsedQuicVersion version); static QuicStreamId StreamIdDelta(QuicTransportVersion version); static QuicStreamId GetFirstBidirectionalStreamId( QuicTransportVersion version, Perspective perspective); static QuicStreamId GetFirstUnidirectionalStreamId( QuicTransportVersion version, Perspective perspective); static QuicStreamId GetMaxClientInitiatedBidirectionalStreamId( QuicTransportVersion version); static QuicConnectionId CreateRandomConnectionId(); static QuicConnectionId CreateRandomConnectionId(QuicRandom* random); static QuicConnectionId CreateRandomConnectionId( uint8_t connection_id_length); static QuicConnectionId CreateRandomConnectionId(uint8_t connection_id_length, QuicRandom* random); static bool IsConnectionIdLengthValidForVersion( size_t connection_id_length, QuicTransportVersion transport_version); static bool IsConnectionIdValidForVersion( QuicConnectionId connection_id, QuicTransportVersion transport_version); static QuicConnectionId CreateZeroConnectionId(QuicTransportVersion version); static StatelessResetToken GenerateStatelessResetToken( QuicConnectionId connection_id); static PacketNumberSpace GetPacketNumberSpace( EncryptionLevel encryption_level); static EncryptionLevel GetEncryptionLevelToSendAckofSpace( PacketNumberSpace packet_number_space); static QuicStreamCount GetMaxStreamCount(); static bool IsProbingFrame(QuicFrameType type); static bool AreStatelessResetTokensEqual(const StatelessResetToken& token1, const StatelessResetToken& token2); static bool IsAckElicitingFrame(QuicFrameType type); }; bool IsValidWebTransportSessionId(WebTransportSessionId id, ParsedQuicVersion transport_version); QuicByteCount MemSliceSpanTotalSize(absl::Span<quiche::QuicheMemSlice> span); QUICHE_EXPORT std::string RawSha256(absl::string_view input); template <typename Index, typename Mask = uint64_t> class QUICHE_EXPORT BitMask { public: explicit constexpr BitMask(std::initializer_list<Index> bits) { for (Index bit : bits) { mask_ |= MakeMask(bit); } } BitMask() = default; BitMask(const BitMask& other) = default; BitMask& operator=(const BitMask& other) = default; constexpr void Set(Index bit) { mask_ |= MakeMask(bit); } constexpr void Set(std::initializer_list<Index> bits) { mask_ |= BitMask(bits).mask(); } constexpr bool IsSet(Index bit) const { return (MakeMask(bit) & mask_) != 0; } constexpr void ClearAll() { mask_ = 0; } bool Any() const { return mask_ != 0; } std::optional<Index> Max() const { if (!Any()) { return std::nullopt; } return static_cast<Index>(NumBits() - absl::countl_zero(mask_) - 1); } static constexpr size_t NumBits() { return 8 * sizeof(Mask); } friend bool operator==(const BitMask& lhs, const BitMask& rhs) { return lhs.mask_ == rhs.mask_; } BitMask<Index, Mask> operator&(const BitMask<Index, Mask>& rhs) const { return BitMask<Index, Mask>(mask_ & rhs.mask_); } std::string DebugString() const { return absl::StrCat("0x", absl::Hex(mask_)); } constexpr Mask mask() const { return mask_; } private: explicit constexpr BitMask(Mask mask) : mask_(mask) {} template <typename Bit> static constexpr std::enable_if_t<std::is_enum_v<Bit>, Mask> MakeMask( Bit bit) { using IntType = typename std::underlying_type<Bit>::type; return MakeMask(static_cast<IntType>(bit)); } template <typename Bit> static constexpr std::enable_if_t<!std::is_enum_v<Bit>, Mask> MakeMask( Bit bit) { QUICHE_DCHECK(bit < static_cast<Bit>(NumBits())); if constexpr (std::is_signed_v<Bit>) { QUICHE_DCHECK(bit >= 0); } return Mask(1) << bit; } Mask mask_ = 0; }; static_assert(BitMask<int>({1, 2, 3}).mask() == 0x0e); } #endif #include "quiche/quic/core/quic_utils.h" #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <string> #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "openssl/sha.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { #if defined(__x86_64__) && \ ((defined(__GNUC__) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) || \ defined(__clang__)) #define QUIC_UTIL_HAS_UINT128 1 #endif #ifdef QUIC_UTIL_HAS_UINT128 absl::uint128 IncrementalHashFast(absl::uint128 uhash, absl::string_view data) { static const absl::uint128 kPrime = (static_cast<absl::uint128>(16777216) << 64) + 315; auto hi = absl::Uint128High64(uhash); auto lo = absl::Uint128Low64(uhash); absl::uint128 xhash = (static_cast<absl::uint128>(hi) << 64) + lo; const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); for (size_t i = 0; i < data.length(); ++i) { xhash = (xhash ^ static_cast<uint32_t>(octets[i])) * kPrime; } return absl::MakeUint128(absl::Uint128High64(xhash), absl::Uint128Low64(xhash)); } #endif #ifndef QUIC_UTIL_HAS_UINT128 absl::uint128 IncrementalHashSlow(absl::uint128 hash, absl::string_view data) { static const absl::uint128 kPrime = absl::MakeUint128(16777216, 315); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); for (size_t i = 0; i < data.length(); ++i) { hash = hash ^ absl::MakeUint128(0, octets[i]); hash = hash * kPrime; } return hash; } #endif absl::uint128 IncrementalHash(absl::uint128 hash, absl::string_view data) { #ifdef QUIC_UTIL_HAS_UINT128 return IncrementalHashFast(hash, data); #else return IncrementalHashSlow(hash, data); #endif } } uint64_t QuicUtils::FNV1a_64_Hash(absl::string_view data) { static const uint64_t kOffset = UINT64_C(14695981039346656037); static const uint64_t kPrime = UINT64_C(1099511628211); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); uint64_t hash = kOffset; for (size_t i = 0; i < data.length(); ++i) { hash = hash ^ octets[i]; hash = hash * kPrime; } return hash; } absl::uint128 QuicUtils::FNV1a_128_Hash(absl::string_view data) { return FNV1a_128_Hash_Three(data, absl::string_view(), absl::string_view()); } absl::uint128 QuicUtils::FNV1a_128_Hash_Two(absl::string_view data1, absl::string_view data2) { return FNV1a_128_Hash_Three(data1, data2, absl::string_view()); } absl::uint128 QuicUtils::FNV1a_128_Hash_Three(absl::string_view data1, absl::string_view data2, absl::string_view data3) { const absl::uint128 kOffset = absl::MakeUint128( UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)); absl::uint128 hash = IncrementalHash(kOffset, data1); if (data2.empty()) { return hash; } hash = IncrementalHash(hash, data2); if (data3.empty()) { return hash; } return IncrementalHash(hash, data3); } void QuicUtils::SerializeUint128Short(absl::uint128 v, uint8_t* out) { const uint64_t lo = absl::Uint128Low64(v); const uint64_t hi = absl::Uint128High64(v); memcpy(out, &lo, sizeof(lo)); memcpy(out + sizeof(lo), &hi, sizeof(hi) / 2); } #define RETURN_STRING_LITERAL(x) \ case x: \ return #x; std::string QuicUtils::AddressChangeTypeToString(AddressChangeType type) { switch (type) { RETURN_STRING_LITERAL(NO_CHANGE); RETURN_STRING_LITERAL(PORT_CHANGE); RETURN_STRING_LITERAL(IPV4_SUBNET_CHANGE); RETURN_STRING_LITERAL(IPV4_TO_IPV6_CHANGE); RETURN_STRING_LITERAL(IPV6_TO_IPV4_CHANGE); RETURN_STRING_LITERAL(IPV6_TO_IPV6_CHANGE); RETURN_STRING_LITERAL(IPV4_TO_IPV4_CHANGE); } return "INVALID_ADDRESS_CHANGE_TYPE"; } const char* QuicUtils::SentPacketStateToString(SentPacketState state) { switch (state) { RETURN_STRING_LITERAL(OUTSTANDING); RETURN_STRING_LITERAL(NEVER_SENT); RETURN_STRING_LITERAL(ACKED); RETURN_STRING_LITERAL(UNACKABLE); RETURN_STRING_LITERAL(NEUTERED); RETURN_STRING_LITERAL(HANDSHAKE_RETRANSMITTED); RETURN_STRING_LITERAL(LOST); RETURN_STRING_LITERAL(PTO_RETRANSMITTED); RETURN_STRING_LITERAL(NOT_CONTRIBUTING_RTT); } return "INVALID_SENT_PACKET_STATE"; } const char* QuicUtils::QuicLongHeaderTypetoString(QuicLongHeaderType type) { switch (type) { RETURN_STRING_LITERAL(VERSION_NEGOTIATION); RETURN_STRING_LITERAL(INITIAL); RETURN_STRING_LITERAL(RETRY); RETURN_STRING_LITERAL(HANDSHAKE); RETURN_STRING_LITERAL(ZERO_RTT_PROTECTED); default: return "INVALID_PACKET_TYPE"; } } const char* QuicUtils::AckResultToString(AckResult result) { switch (result) { RETURN_STRING_LITERAL(PACKETS_NEWLY_ACKED); RETURN_STRING_LITERAL(NO_PACKETS_NEWLY_ACKED); RETURN_STRING_LITERAL(UNSENT_PACKETS_ACKED); RETURN_STRING_LITERAL(UNACKABLE_PACKETS_ACKED); RETURN_STRING_LITERAL(PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE); } return "INVALID_ACK_RESULT"; } AddressChangeType QuicUtils::DetermineAddressChangeType( const QuicSocketAddress& old_address, const QuicSocketAddress& new_address) { if (!old_address.IsInitialized() || !new_address.IsInitialized() || old_address == new_address) { return NO_CHANGE; } if (old_address.host() == new_address.host()) { return PORT_CHANGE; } bool old_ip_is_ipv4 = old_address.host().IsIPv4() ? true : false; bool migrating_ip_is_ipv4 = new_address.host().IsIPv4() ? true : false; if (old_ip_is_ipv4 && !migrating_ip_is_ipv4) { return IPV4_TO_IPV6_CHANGE; } if (!old_ip_is_ipv4) { return migrating_ip_is_ipv4 ? IPV6_TO_IPV4_CHANGE : IPV6_TO_IPV6_CHANGE; } const int kSubnetMaskLength = 24; if (old_address.host().InSameSubnet(new_address.host(), kSubnetMaskLength)) { return IPV4_SUBNET_CHANGE; } return IPV4_TO_IPV4_CHANGE; } bool QuicUtils::IsAckable(SentPacketState state) { return state != NEVER_SENT && state != ACKED && state != UNACKABLE; } bool QuicUtils::IsRetransmittableFrame(QuicFrameType type) { switch (type) { case ACK_FRAME: case PADDING_FRAME: case STOP_WAITING_FRAME: case MTU_DISCOVERY_FRAME: case PATH_CHALLENGE_FRAME: case PATH_RESPONSE_FRAME: return false; default: return true; } } bool QuicUtils::IsHandshakeFrame(const QuicFrame& frame, QuicTransportVersion transport_version) { if (!QuicVersionUsesCryptoFrames(transport_version)) { return frame.type == STREAM_FRAME && frame.stream_frame.stream_id == GetCryptoStreamId(transport_version); } else { return frame.type == CRYPTO_FRAME; } } bool QuicUtils::ContainsFrameType(const QuicFrames& frames, QuicFrameType type) { for (const QuicFrame& frame : frames) { if (frame.type == type) { return true; } } return false; } SentPacketState QuicUtils::RetransmissionTypeToPacketState( TransmissionType retransmission_type) { switch (retransmission_type) { case ALL_ZERO_RTT_RETRANSMISSION: return UNACKABLE; case HANDSHAKE_RETRANSMISSION: return HANDSHAKE_RETRANSMITTED; case LOSS_RETRANSMISSION: return LOST; case PTO_RETRANSMISSION: return PTO_RETRANSMITTED; case PATH_RETRANSMISSION: return NOT_CONTRIBUTING_RTT; case ALL_INITIAL_RETRANSMISSION: return UNACKABLE; default: QUIC_BUG(quic_bug_10839_2) << retransmission_type << " is not a retransmission_type"; return UNACKABLE; } } bool QuicUtils::IsIetfPacketHeader(uint8_t first_byte) { return (first_byte & FLAGS_LONG_HEADER) || (first_byte & FLAGS_FIXED_BIT) || !(first_byte & FLAGS_DEMULTIPLEXING_BIT); } bool QuicUtils::IsIetfPacketShortHeader(uint8_t first_byte) { return IsIetfPacketHeader(first_byte) && !(first_byte & FLAGS_LONG_HEADER); } QuicStreamId QuicUtils::GetInvalidStreamId(QuicTransportVersion version) { return VersionHasIetfQuicFrames(version) ? std::numeric_limits<QuicStreamId>::max() : 0; } QuicStreamId QuicUtils::GetCryptoStreamId(QuicTransportVersion version) { QUIC_BUG_IF(quic_bug_12982_1, QuicVersionUsesCryptoFrames(version)) << "CRYPTO data aren't in stream frames; they have no stream ID."; return QuicVersionUsesCryptoFrames(version) ? GetInvalidStreamId(version) : 1; } bool QuicUtils::IsCryptoStreamId(QuicTransportVersion version, QuicStreamId stream_id) { if (QuicVersionUsesCryptoFrames(version)) { return false; } return stream_id == GetCryptoStreamId(version); } QuicStreamId QuicUtils::GetHeadersStreamId(QuicTransportVersion version) { QUICHE_DCHECK(!VersionUsesHttp3(version)); return GetFirstBidirectionalStreamId(version, Perspective::IS_CLIENT); } bool QuicUtils::IsClientInitiatedStreamId(QuicTransportVersion version, QuicStreamId id) { if (id == GetInvalidStreamId(version)) { return false; } return VersionHasIetfQuicFrames(version) ? id % 2 == 0 : id % 2 != 0; } bool QuicUtils::IsServerInitiatedStreamId(QuicTransportVersion version, QuicStreamId id) { if (id == GetInvalidStreamId(version)) { return false; } return VersionHasIetfQuicFrames(version) ? id % 2 != 0 : id % 2 == 0; } bool QuicUtils::IsOutgoingStreamId(ParsedQuicVersion version, QuicStreamId id, Perspective perspective) { const bool perspective_is_server = perspective == Perspective::IS_SERVER; const bool stream_is_server = QuicUtils::IsServerInitiatedStreamId(version.transport_version, id); return perspective_is_server == stream_is_server; } bool QuicUtils::IsBidirectionalStreamId(QuicStreamId id, ParsedQuicVersion version) { QUICHE_DCHECK(version.HasIetfQuicFrames()); return id % 4 < 2; } StreamType QuicUtils::GetStreamType(QuicStreamId id, Perspective perspective, bool peer_initiated, ParsedQuicVersion version) { QUICHE_DCHECK(version.HasIetfQuicFrames()); if (IsBidirectionalStreamId(id, version)) { return BIDIRECTIONAL; } if (peer_initiated) { if (perspective == Perspective::IS_SERVER) { QUICHE_DCHECK_EQ(2u, id % 4); } else { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective); QUICHE_DCHECK_EQ(3u, id % 4); } return READ_UNIDIRECTIONAL; } if (perspective == Perspective::IS_SERVER) { QUICHE_DCHECK_EQ(3u, id % 4); } else { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective); QUICHE_DCHECK_EQ(2u, id % 4); } return WRITE_UNIDIRECTIONAL; } QuicStreamId QuicUtils::StreamIdDelta(QuicTransportVersion version) { return VersionHasIetfQuicFrames(version) ? 4 : 2; } QuicStreamId QuicUtils::GetFirstBidirectionalStreamId( QuicTransportVersion version, Perspective perspective) { if (VersionHasIetfQuicFrames(version)) { return perspective == Perspective::IS_CLIENT ? 0 : 1; } else if (QuicVersionUsesCryptoFrames(version)) { return perspective == Perspective::IS_CLIENT ? 1 : 2; } return perspective == Perspective::IS_CLIENT ? 3 : 2; } QuicStreamId QuicUtils::GetFirstUnidirectionalStreamId( QuicTransportVersion version, Perspective perspective) { if (VersionHasIetfQuicFrames(version)) { return perspective == Perspective::IS_CLIENT ? 2 : 3; } else if (QuicVersionUsesCryptoFrames(version)) { return perspective == Perspective::IS_CLIENT ? 1 : 2; } return perspective == Perspective::IS_CLIENT ? 3 : 2; } QuicStreamId QuicUtils::GetMaxClientInitiatedBidirectionalStreamId( QuicTransportVersion version) { if (VersionHasIetfQuicFrames(version)) { return std::numeric_limits<QuicStreamId>::max() - 3; } return std::numeric_limits<QuicStreamId>::max(); } QuicConnectionId QuicUtils::CreateRandomConnectionId() { return CreateRandomConnectionId(kQuicDefaultConnectionIdLength, QuicRandom::GetInstance()); } QuicConnectionId QuicUtils::CreateRandomConnectionId(QuicRandom* random) { return CreateRandomConnectionId(kQuicDefaultConnectionIdLength, random); } QuicConnectionId QuicUtils::CreateRandomConnectionId( uint8_t connection_id_length) { return CreateRandomConnectionId(connection_id_length, QuicRandom::GetInstance()); } QuicConnectionId QuicUtils::CreateRandomConnectionId( uint8_t connection_id_length, QuicRandom* random) { QuicConnectionId connection_id; connection_id.set_length(connection_id_length); if (connection_id.length() > 0) { random->RandBytes(connection_id.mutable_data(), connection_id.length()); } return connection_id; } QuicConnectionId QuicUtils::CreateZeroConnectionId( QuicTransportVersion version) { if (!VersionAllowsVariableLengthConnectionIds(version)) { char connection_id_bytes[8] = {0, 0, 0, 0, 0, 0, 0, 0}; return QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes)); } return EmptyQuicConnectionId(); } bool QuicUtils::IsConnectionIdLengthValidForVersion( size_t connection_id_length, QuicTransportVersion transport_version) { if (connection_id_length > static_cast<size_t>(std::numeric_limits<uint8_t>::max())) { return false; } if (transport_version == QUIC_VERSION_UNSUPPORTED || transport_version == QUIC_VERSION_RESERVED_FOR_NEGOTIATION) { return true; } const uint8_t connection_id_length8 = static_cast<uint8_t>(connection_id_length); if (!VersionAllowsVariableLengthConnectionIds(transport_version)) { return connection_id_length8 == kQuicDefaultConnectionIdLength; } return connection_id_length8 <= kQuicMaxConnectionIdWithLengthPrefixLength; } bool QuicUtils::IsConnectionIdValidForVersion( QuicConnectionId connection_id, QuicTransportVersion transport_version) { return IsConnectionIdLengthValidForVersion(connection_id.length(), transport_version); } StatelessResetToken QuicUtils::GenerateStatelessResetToken( QuicConnectionId connection_id) { static_assert(sizeof(absl::uint128) == sizeof(StatelessResetToken), "bad size"); static_assert(alignof(absl::uint128) >= alignof(StatelessResetToken), "bad alignment"); absl::uint128 hash = FNV1a_128_Hash( absl::string_view(connection_id.data(), connection_id.length())); return *reinterpret_cast<StatelessResetToken*>(&hash); } QuicStreamCount QuicUtils::GetMaxStreamCount() { return (kMaxQuicStreamCount >> 2) + 1; } PacketNumberSpace QuicUtils::GetPacketNumberSpace( EncryptionLevel encryption_level) { switch (encryption_level) { case ENCRYPTION_INITIAL: return INITIAL_DATA; case ENCRYPTION_HANDSHAKE: return HANDSHAKE_DATA; case ENCRYPTION_ZERO_RTT: case ENCRYPTION_FORWARD_SECURE: return APPLICATION_DATA; default: QUIC_BUG(quic_bug_10839_3) << "Try to get packet number space of encryption level: " << encryption_level; return NUM_PACKET_NUMBER_SPACES; } } EncryptionLevel QuicUtils::GetEncryptionLevelToSendAckofSpace( PacketNumberSpace packet_number_space) { switch (packet_number_space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return ENCRYPTION_FORWARD_SECURE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } bool QuicUtils::IsProbingFrame(QuicFrameType type) { switch (type) { case PATH_CHALLENGE_FRAME: case PATH_RESPONSE_FRAME: case NEW_CONNECTION_ID_FRAME: case PADDING_FRAME: return true; default: return false; } } bool QuicUtils::IsAckElicitingFrame(QuicFrameType type) { switch (type) { case PADDING_FRAME: case STOP_WAITING_FRAME: case ACK_FRAME: case CONNECTION_CLOSE_FRAME: return false; default: return true; } } bool QuicUtils::AreStatelessResetTokensEqual( const StatelessResetToken& token1, const StatelessResetToken& token2) { char byte = 0; for (size_t i = 0; i < kStatelessResetTokenLength; i++) { byte |= (token1[i] ^ token2[i]); } return byte == 0; } bool IsValidWebTransportSessionId(WebTransportSessionId id, ParsedQuicVersion version) { QUICHE_DCHECK(version.UsesHttp3()); return (id <= std::numeric_limits<QuicStreamId>::max()) && QuicUtils::IsBidirectionalStreamId(id, version) && QuicUtils::IsClientInitiatedStreamId(version.transport_version, id); } QuicByteCount MemSliceSpanTotalSize(absl::Span<quiche::QuicheMemSlice> span) { QuicByteCount total = 0; for (const quiche::QuicheMemSlice& slice : span) { total += slice.length(); } return total; } std:
#include "quiche/quic/core/quic_utils.h" #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class QuicUtilsTest : public QuicTest {}; TEST_F(QuicUtilsTest, DetermineAddressChangeType) { const std::string kIPv4String1 = "1.2.3.4"; const std::string kIPv4String2 = "1.2.3.5"; const std::string kIPv4String3 = "1.1.3.5"; const std::string kIPv6String1 = "2001:700:300:1800::f"; const std::string kIPv6String2 = "2001:700:300:1800:1:1:1:f"; QuicSocketAddress old_address; QuicSocketAddress new_address; QuicIpAddress address; EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); new_address = QuicSocketAddress(address, 5678); EXPECT_EQ(PORT_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv6String1)); old_address = QuicSocketAddress(address, 1234); new_address = QuicSocketAddress(address, 5678); EXPECT_EQ(PORT_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv6String1)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_TO_IPV6_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv4String1)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv6String2)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV6_TO_IPV6_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv4String2)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_SUBNET_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String3)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_TO_IPV4_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); } absl::uint128 IncrementalHashReference(const void* data, size_t len) { absl::uint128 hash = absl::MakeUint128(UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)); const absl::uint128 kPrime = absl::MakeUint128(16777216, 315); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data); for (size_t i = 0; i < len; ++i) { hash = hash ^ absl::MakeUint128(0, octets[i]); hash = hash * kPrime; } return hash; } TEST_F(QuicUtilsTest, ReferenceTest) { std::vector<uint8_t> data(32); for (size_t i = 0; i < data.size(); ++i) { data[i] = i % 255; } EXPECT_EQ(IncrementalHashReference(data.data(), data.size()), QuicUtils::FNV1a_128_Hash(absl::string_view( reinterpret_cast<const char*>(data.data()), data.size()))); } TEST_F(QuicUtilsTest, IsUnackable) { for (size_t i = FIRST_PACKET_STATE; i <= LAST_PACKET_STATE; ++i) { if (i == NEVER_SENT || i == ACKED || i == UNACKABLE) { EXPECT_FALSE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); } else { EXPECT_TRUE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); } } } TEST_F(QuicUtilsTest, RetransmissionTypeToPacketState) { for (size_t i = FIRST_TRANSMISSION_TYPE; i <= LAST_TRANSMISSION_TYPE; ++i) { if (i == NOT_RETRANSMISSION) { continue; } SentPacketState state = QuicUtils::RetransmissionTypeToPacketState( static_cast<TransmissionType>(i)); if (i == HANDSHAKE_RETRANSMISSION) { EXPECT_EQ(HANDSHAKE_RETRANSMITTED, state); } else if (i == LOSS_RETRANSMISSION) { EXPECT_EQ(LOST, state); } else if (i == ALL_ZERO_RTT_RETRANSMISSION) { EXPECT_EQ(UNACKABLE, state); } else if (i == PTO_RETRANSMISSION) { EXPECT_EQ(PTO_RETRANSMITTED, state); } else if (i == PATH_RETRANSMISSION) { EXPECT_EQ(NOT_CONTRIBUTING_RTT, state); } else if (i == ALL_INITIAL_RETRANSMISSION) { EXPECT_EQ(UNACKABLE, state); } else { QUICHE_DCHECK(false) << "No corresponding packet state according to transmission type: " << i; } } } TEST_F(QuicUtilsTest, IsIetfPacketHeader) { uint8_t first_byte = 0; EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_TRUE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte |= (FLAGS_LONG_HEADER | FLAGS_DEMULTIPLEXING_BIT); EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte = 0; first_byte |= FLAGS_LONG_HEADER; EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte = 0; first_byte |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID; EXPECT_FALSE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); } TEST_F(QuicUtilsTest, RandomConnectionId) { MockRandom random(33); QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(&random); EXPECT_EQ(connection_id.length(), sizeof(uint64_t)); char connection_id_bytes[sizeof(uint64_t)]; random.RandBytes(connection_id_bytes, ABSL_ARRAYSIZE(connection_id_bytes)); EXPECT_EQ(connection_id, QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes))); EXPECT_NE(connection_id, EmptyQuicConnectionId()); EXPECT_NE(connection_id, TestConnectionId()); EXPECT_NE(connection_id, TestConnectionId(1)); EXPECT_NE(connection_id, TestConnectionIdNineBytesLong(1)); EXPECT_EQ(QuicUtils::CreateRandomConnectionId().length(), kQuicDefaultConnectionIdLength); } TEST_F(QuicUtilsTest, RandomConnectionIdVariableLength) { MockRandom random(1337); const uint8_t connection_id_length = 9; QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(connection_id_length, &random); EXPECT_EQ(connection_id.length(), connection_id_length); char connection_id_bytes[connection_id_length]; random.RandBytes(connection_id_bytes, ABSL_ARRAYSIZE(connection_id_bytes)); EXPECT_EQ(connection_id, QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes))); EXPECT_NE(connection_id, EmptyQuicConnectionId()); EXPECT_NE(connection_id, TestConnectionId()); EXPECT_NE(connection_id, TestConnectionId(1)); EXPECT_NE(connection_id, TestConnectionIdNineBytesLong(1)); EXPECT_EQ(QuicUtils::CreateRandomConnectionId(connection_id_length).length(), connection_id_length); } TEST_F(QuicUtilsTest, VariableLengthConnectionId) { EXPECT_FALSE(VersionAllowsVariableLengthConnectionIds(QUIC_VERSION_46)); EXPECT_TRUE(QuicUtils::IsConnectionIdValidForVersion( QuicUtils::CreateZeroConnectionId(QUIC_VERSION_46), QUIC_VERSION_46)); EXPECT_NE(QuicUtils::CreateZeroConnectionId(QUIC_VERSION_46), EmptyQuicConnectionId()); EXPECT_FALSE(QuicUtils::IsConnectionIdValidForVersion(EmptyQuicConnectionId(), QUIC_VERSION_46)); } TEST_F(QuicUtilsTest, StatelessResetToken) { QuicConnectionId connection_id1a = test::TestConnectionId(1); QuicConnectionId connection_id1b = test::TestConnectionId(1); QuicConnectionId connection_id2 = test::TestConnectionId(2); StatelessResetToken token1a = QuicUtils::GenerateStatelessResetToken(connection_id1a); StatelessResetToken token1b = QuicUtils::GenerateStatelessResetToken(connection_id1b); StatelessResetToken token2 = QuicUtils::GenerateStatelessResetToken(connection_id2); EXPECT_EQ(token1a, token1b); EXPECT_NE(token1a, token2); EXPECT_TRUE(QuicUtils::AreStatelessResetTokensEqual(token1a, token1b)); EXPECT_FALSE(QuicUtils::AreStatelessResetTokensEqual(token1a, token2)); } TEST_F(QuicUtilsTest, EcnCodepointToString) { EXPECT_EQ(EcnCodepointToString(ECN_NOT_ECT), "Not-ECT"); EXPECT_EQ(EcnCodepointToString(ECN_ECT0), "ECT(0)"); EXPECT_EQ(EcnCodepointToString(ECN_ECT1), "ECT(1)"); EXPECT_EQ(EcnCodepointToString(ECN_CE), "CE"); } enum class TestEnumClassBit : uint8_t { BIT_ZERO = 0, BIT_ONE, BIT_TWO, }; enum TestEnumBit { TEST_BIT_0 = 0, TEST_BIT_1, TEST_BIT_2, }; TEST(QuicBitMaskTest, EnumClass) { BitMask<TestEnumClassBit> mask( {TestEnumClassBit::BIT_ZERO, TestEnumClassBit::BIT_TWO}); EXPECT_TRUE(mask.IsSet(TestEnumClassBit::BIT_ZERO)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ONE)); EXPECT_TRUE(mask.IsSet(TestEnumClassBit::BIT_TWO)); mask.ClearAll(); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ZERO)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ONE)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_TWO)); } TEST(QuicBitMaskTest, Enum) { BitMask<TestEnumBit> mask({TEST_BIT_1, TEST_BIT_2}); EXPECT_FALSE(mask.IsSet(TEST_BIT_0)); EXPECT_TRUE(mask.IsSet(TEST_BIT_1)); EXPECT_TRUE(mask.IsSet(TEST_BIT_2)); mask.ClearAll(); EXPECT_FALSE(mask.IsSet(TEST_BIT_0)); EXPECT_FALSE(mask.IsSet(TEST_BIT_1)); EXPECT_FALSE(mask.IsSet(TEST_BIT_2)); } TEST(QuicBitMaskTest, Integer) { BitMask<int> mask({1, 3}); EXPECT_EQ(mask.Max(), 3); mask.Set(3); mask.Set({5, 7, 9}); EXPECT_EQ(mask.Max(), 9); EXPECT_FALSE(mask.IsSet(0)); EXPECT_TRUE(mask.IsSet(1)); EXPECT_FALSE(mask.IsSet(2)); EXPECT_TRUE(mask.IsSet(3)); EXPECT_FALSE(mask.IsSet(4)); EXPECT_TRUE(mask.IsSet(5)); EXPECT_FALSE(mask.IsSet(6)); EXPECT_TRUE(mask.IsSet(7)); EXPECT_FALSE(mask.IsSet(8)); EXPECT_TRUE(mask.IsSet(9)); } TEST(QuicBitMaskTest, NumBits) { EXPECT_EQ(64u, BitMask<int>::NumBits()); EXPECT_EQ(32u, (BitMask<int, uint32_t>::NumBits())); } TEST(QuicBitMaskTest, Constructor) { BitMask<int> empty_mask; for (size_t bit = 0; bit < empty_mask.NumBits(); ++bit) { EXPECT_FALSE(empty_mask.IsSet(bit)); } BitMask<int> mask({1, 3}); BitMask<int> mask2 = mask; BitMask<int> mask3(mask2); for (size_t bit = 0; bit < mask.NumBits(); ++bit) { EXPECT_EQ(mask.IsSet(bit), mask2.IsSet(bit)); EXPECT_EQ(mask.IsSet(bit), mask3.IsSet(bit)); } EXPECT_TRUE(std::is_trivially_copyable<BitMask<int>>::value); } TEST(QuicBitMaskTest, Any) { BitMask<int> mask; EXPECT_FALSE(mask.Any()); mask.Set(3); EXPECT_TRUE(mask.Any()); mask.Set(2); EXPECT_TRUE(mask.Any()); mask.ClearAll(); EXPECT_FALSE(mask.Any()); } TEST(QuicBitMaskTest, And) { using Mask = BitMask<int>; EXPECT_EQ(Mask({1, 3, 6}) & Mask({3, 5, 6}), Mask({3, 6})); EXPECT_EQ(Mask({1, 2, 4}) & Mask({3, 5}), Mask({})); EXPECT_EQ(Mask({1, 2, 3, 4, 5}) & Mask({}), Mask({})); } } } }
261
cpp
google/quiche
quic_stream
quiche/quic/core/quic_stream.cc
quiche/quic/core/quic_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_H_ #include <cstddef> #include <cstdint> #include <list> #include <optional> #include <string> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_flow_controller.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_stream_send_buffer.h" #include "quiche/quic/core/quic_stream_sequencer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/session_notifier_interface.h" #include "quiche/quic/core/stream_delegate_interface.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_reference_counted.h" #include "quiche/spdy/core/spdy_protocol.h" namespace quic { namespace test { class QuicStreamPeer; } class QuicSession; class QuicStream; class QUICHE_EXPORT PendingStream : public QuicStreamSequencer::StreamInterface { public: PendingStream(QuicStreamId id, QuicSession* session); PendingStream(const PendingStream&) = delete; PendingStream(PendingStream&&) = default; ~PendingStream() override = default; void OnDataAvailable() override; void OnFinRead() override; void AddBytesConsumed(QuicByteCount bytes) override; void ResetWithError(QuicResetStreamError error) override; void OnUnrecoverableError(QuicErrorCode error, const std::string& details) override; void OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) override; QuicStreamId id() const override; ParsedQuicVersion version() const override; void OnStreamFrame(const QuicStreamFrame& frame); bool is_bidirectional() const { return is_bidirectional_; } void OnRstStreamFrame(const QuicRstStreamFrame& frame); void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame); void OnStopSending(QuicResetStreamError stop_sending_error_code); const std::optional<QuicResetStreamError>& GetStopSendingErrorCode() const { return stop_sending_error_code_; } uint64_t stream_bytes_read() { return stream_bytes_read_; } const QuicStreamSequencer* sequencer() const { return &sequencer_; } void MarkConsumed(QuicByteCount num_bytes); void StopReading(); QuicTime creation_time() const { return creation_time_; } private: friend class QuicStream; bool MaybeIncreaseHighestReceivedOffset(QuicStreamOffset new_offset); QuicStreamId id_; ParsedQuicVersion version_; StreamDelegateInterface* stream_delegate_; uint64_t stream_bytes_read_; bool fin_received_; bool is_bidirectional_; QuicFlowController* connection_flow_controller_; QuicFlowController flow_controller_; QuicStreamSequencer sequencer_; std::optional<QuicResetStreamError> stop_sending_error_code_; const QuicTime creation_time_; }; class QUICHE_EXPORT QuicStream : public QuicStreamSequencer::StreamInterface { public: QuicStream(QuicStreamId id, QuicSession* session, bool is_static, StreamType type); QuicStream(PendingStream* pending, QuicSession* session, bool is_static); QuicStream(const QuicStream&) = delete; QuicStream& operator=(const QuicStream&) = delete; virtual ~QuicStream(); QuicStreamId id() const override { return id_; } ParsedQuicVersion version() const override; void OnFinRead() override; void ResetWithError(QuicResetStreamError error) override; void Reset(QuicRstStreamErrorCode error); void ResetWriteSide(QuicResetStreamError error); void SendStopSending(QuicResetStreamError error); void OnUnrecoverableError(QuicErrorCode error, const std::string& details) override; void OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) override; virtual void OnStreamFrame(const QuicStreamFrame& frame); virtual void OnCanWrite(); virtual void OnStreamReset(const QuicRstStreamFrame& frame); virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source); const QuicStreamPriority& priority() const; virtual void MaybeSendPriorityUpdateFrame() {} void SetPriority(const QuicStreamPriority& priority); bool IsWaitingForAcks() const; QuicRstStreamErrorCode stream_error() const { return stream_error_.internal_code(); } uint64_t ietf_application_error() const { return stream_error_.ietf_application_code(); } QuicErrorCode connection_error() const { return connection_error_; } bool reading_stopped() const { return sequencer_.ignore_read_data() || read_side_closed_; } bool write_side_closed() const { return write_side_closed_; } bool read_side_closed() const { return read_side_closed_; } bool IsZombie() const { return read_side_closed_ && write_side_closed_ && IsWaitingForAcks(); } bool rst_received() const { return rst_received_; } bool rst_sent() const { return rst_sent_; } bool fin_received() const { return fin_received_; } bool fin_sent() const { return fin_sent_; } bool fin_outstanding() const { return fin_outstanding_; } bool fin_lost() const { return fin_lost_; } uint64_t BufferedDataBytes() const; uint64_t stream_bytes_read() const { return stream_bytes_read_; } uint64_t stream_bytes_written() const; size_t busy_counter() const { return busy_counter_; } void set_busy_counter(size_t busy_counter) { busy_counter_ = busy_counter; } virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame); int num_frames_received() const; int num_duplicate_frames_received() const; bool IsFlowControlBlocked() const; QuicStreamOffset highest_received_byte_offset() const; void UpdateReceiveWindowSize(QuicStreamOffset size); QuicStreamOffset NumBytesConsumed() const { return sequencer()->NumBytesConsumed(); } bool MaybeIncreaseHighestReceivedOffset(QuicStreamOffset new_offset); bool MaybeConfigSendWindowOffset(QuicStreamOffset new_offset, bool was_zero_rtt_rejected); bool HasReceivedFinalOffset() const { return fin_received_ || rst_received_; } bool HasBufferedData() const; QuicTransportVersion transport_version() const; HandshakeProtocol handshake_protocol() const; virtual void StopReading(); void WriteOrBufferData( absl::string_view data, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); void WriteOrBufferDataAtLevel( absl::string_view data, bool fin, EncryptionLevel level, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); void AddRandomPaddingAfterFin(); bool WriteStreamData(QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer); virtual bool OnStreamFrameAcked(QuicStreamOffset offset, QuicByteCount data_length, bool fin_acked, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp, QuicByteCount* newly_acked_length); virtual void OnStreamFrameRetransmitted(QuicStreamOffset offset, QuicByteCount data_length, bool fin_retransmitted); virtual void OnStreamFrameLost(QuicStreamOffset offset, QuicByteCount data_length, bool fin_lost); virtual bool RetransmitStreamData(QuicStreamOffset offset, QuicByteCount data_length, bool fin, TransmissionType type); bool MaybeSetTtl(QuicTime::Delta ttl); QuicConsumedData WriteMemSlices(absl::Span<quiche::QuicheMemSlice> span, bool fin, bool buffer_uncondtionally = false); QuicConsumedData WriteMemSlice(quiche::QuicheMemSlice span, bool fin); virtual bool HasPendingRetransmission() const; bool IsStreamFrameOutstanding(QuicStreamOffset offset, QuicByteCount data_length, bool fin) const; StreamType type() const { return type_; } virtual bool OnStopSending(QuicResetStreamError error); bool is_static() const { return is_static_; } bool was_draining() const { return was_draining_; } QuicTime creation_time() const { return creation_time_; } bool fin_buffered() const { return fin_buffered_; } bool CanWriteNewData() const; void OnStreamCreatedFromPendingStream(); void DisableConnectionFlowControlForThisStream() { stream_contributes_to_connection_flow_control_ = false; } QuicByteCount CalculateSendWindowSize() const; const QuicTime::Delta pending_duration() const { return pending_duration_; } protected: virtual void OnDataBuffered( QuicStreamOffset , QuicByteCount , const quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>& ) {} virtual void OnClose(); bool CanWriteNewDataAfterData(QuicByteCount length) const; virtual void OnCanWriteNewData() {} virtual void OnStreamDataConsumed(QuicByteCount bytes_consumed); void AddBytesConsumed(QuicByteCount bytes) override; virtual void WritePendingRetransmission(); virtual void OnDeadlinePassed(); void SetFinSent(); void MaybeSendStopSending(QuicResetStreamError error); void MaybeSendRstStream(QuicResetStreamError error); void MaybeSendRstStream(QuicRstStreamErrorCode error) { MaybeSendRstStream(QuicResetStreamError::FromInternal(error)); } void MaybeSendStopSending(QuicRstStreamErrorCode error) { MaybeSendStopSending(QuicResetStreamError::FromInternal(error)); } virtual void CloseReadSide(); virtual void CloseWriteSide(); void set_rst_received(bool rst_received) { rst_received_ = rst_received; } void set_stream_error(QuicResetStreamError error) { stream_error_ = error; } StreamDelegateInterface* stream_delegate() { return stream_delegate_; } const QuicSession* session() const { return session_; } QuicSession* session() { return session_; } const QuicStreamSequencer* sequencer() const { return &sequencer_; } QuicStreamSequencer* sequencer() { return &sequencer_; } const QuicIntervalSet<QuicStreamOffset>& bytes_acked() const; const QuicStreamSendBuffer& send_buffer() const { return send_buffer_; } QuicStreamSendBuffer& send_buffer() { return send_buffer_; } virtual void OnWriteSideInDataRecvdState() {} std::optional<QuicByteCount> GetSendWindow() const; std::optional<QuicByteCount> GetReceiveWindow() const; private: friend class test::QuicStreamPeer; friend class QuicStreamUtils; QuicStream(QuicStreamId id, QuicSession* session, QuicStreamSequencer sequencer, bool is_static, StreamType type, uint64_t stream_bytes_read, bool fin_received, std::optional<QuicFlowController> flow_controller, QuicFlowController* connection_flow_controller, QuicTime::Delta pending_duration); void MaybeSendBlocked(); void WriteBufferedData(EncryptionLevel level); void AddBytesSent(QuicByteCount bytes); bool HasDeadlinePassed() const; QuicStreamSequencer sequencer_; QuicStreamId id_; QuicSession* session_; StreamDelegateInterface* stream_delegate_; QuicStreamPriority priority_; uint64_t stream_bytes_read_; QuicResetStreamError stream_error_; QuicErrorCode connection_error_; bool read_side_closed_; bool write_side_closed_; bool write_side_data_recvd_state_notified_; bool fin_buffered_; bool fin_sent_; bool fin_outstanding_; bool fin_lost_; bool fin_received_; bool rst_sent_; bool rst_received_; bool stop_sending_sent_; std::optional<QuicFlowController> flow_controller_; QuicFlowController* connection_flow_controller_; bool stream_contributes_to_connection_flow_control_; size_t busy_counter_; bool add_random_padding_after_fin_; QuicStreamSendBuffer send_buffer_; const QuicByteCount buffered_data_threshold_; const bool is_static_; QuicTime deadline_; bool was_draining_; const StreamType type_; const QuicTime creation_time_; const QuicTime::Delta pending_duration_; Perspective perspective_; }; } #endif #include "quiche/quic/core/quic_stream.h" #include <algorithm> #include <limits> #include <optional> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_flow_controller.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" using spdy::SpdyPriority; namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") namespace { QuicByteCount DefaultFlowControlWindow(ParsedQuicVersion version) { if (!version.AllowsLowFlowControlLimits()) { return kDefaultFlowControlSendWindow; } return 0; } QuicByteCount GetInitialStreamFlowControlWindowToSend(QuicSession* session, QuicStreamId stream_id) { ParsedQuicVersion version = session->connection()->version(); if (version.handshake_protocol != PROTOCOL_TLS1_3) { return session->config()->GetInitialStreamFlowControlWindowToSend(); } if (VersionHasIetfQuicFrames(version.transport_version) && !QuicUtils::IsBidirectionalStreamId(stream_id, version)) { return session->config() ->GetInitialMaxStreamDataBytesUnidirectionalToSend(); } if (QuicUtils::IsOutgoingStreamId(version, stream_id, session->perspective())) { return session->config() ->GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(); } return session->config() ->GetInitialMaxStreamDataBytesIncomingBidirectionalToSend(); } QuicByteCount GetReceivedFlowControlWindow(QuicSession* session, QuicStreamId stream_id) { ParsedQuicVersion version = session->connection()->version(); if (version.handshake_protocol != PROTOCOL_TLS1_3) { if (session->config()->HasReceivedInitialStreamFlowControlWindowBytes()) { return session->config()->ReceivedInitialStreamFlowControlWindowBytes(); } return DefaultFlowControlWindow(version); } if (VersionHasIetfQuicFrames(version.transport_version) && !QuicUtils::IsBidirectionalStreamId(stream_id, version)) { if (session->config() ->HasReceivedInitialMaxStreamDataBytesUnidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesUnidirectional(); } return DefaultFlowControlWindow(version); } if (QuicUtils::IsOutgoingStreamId(version, stream_id, session->perspective())) { if (session->config() ->HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesOutgoingBidirectional(); } return DefaultFlowControlWindow(version); } if (session->config() ->HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesIncomingBidirectional(); } return DefaultFlowControlWindow(version); } } PendingStream::PendingStream(QuicStreamId id, QuicSession* session) : id_(id), version_(session->version()), stream_delegate_(session), stream_bytes_read_(0), fin_received_(false), is_bidirectional_(QuicUtils::GetStreamType(id, session->perspective(), true, session->version()) == BIDIRECTIONAL), connection_flow_controller_(session->flow_controller()), flow_controller_(session, id, false, GetReceivedFlowControlWindow(session, id), GetInitialStreamFlowControlWindowToSend(session, id), kStreamReceiveWindowLimit, session->flow_controller()->auto_tune_receive_window(), session->flow_controller()), sequencer_(this), creation_time_(session->GetClock()->ApproximateNow()) { if (is_bidirectional_) { QUIC_CODE_COUNT_N(quic_pending_stream, 3, 3); } } void PendingStream::OnDataAvailable() { } void PendingStream::OnFinRead() { QUICHE_DCHECK(sequencer_.IsClosed()); } void PendingStream::AddBytesConsumed(QuicByteCount bytes) { flow_controller_.AddBytesConsumed(bytes); connection_flow_controller_->AddBytesConsumed(bytes); } void PendingStream::ResetWithError(QuicResetStreamError ) { QUICHE_NOTREACHED(); } void PendingStream::OnUnrecoverableError(QuicErrorCode error, const std::string& details) { stream_delegate_->OnStreamError(error, details); } void PendingStream::OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { stream_delegate_->OnStreamError(error, ietf_error, details); } QuicStreamId PendingStream::id() const { return id_; } ParsedQuicVersion PendingStream::version() const { return version_; } void PendingStream::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK_EQ(frame.stream_id, id_); bool is_stream_too_long = (frame.offset > kMaxStreamLength) || (kMaxStreamLength - frame.offset < frame.data_length); if (is_stream_too_long) { QUIC_PEER_BUG(quic_peer_bug_12570_1) << "Receive stream frame reaches max stream length. frame offset " << frame.offset << " length " << frame.data_length; OnUnrecoverableError(QUIC_STREAM_LENGTH_OVERFLOW, "Peer sends more data than allowed on this stream."); return; } if (frame.offset + frame.data_length > sequencer_.close_offset()) { OnUnrecoverableError( QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, absl::StrCat( "Stream ", id_, " received data with offset: ", frame.offset + frame.data_length, ", which is beyond close offset: ", sequencer()->close_offset())); return; } if (frame.fin) { fin_received_ = true; } QuicByteCount frame_payload_size = frame.data_length; stream_bytes_read_ += frame_payload_size; if (frame_payload_size
#include "quiche/quic/core/quic_stream.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/quic_write_blocked_list.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_mem_slice_storage.h" using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { const char kData1[] = "FooAndBar"; const char kData2[] = "EepAndBaz"; const QuicByteCount kDataLen = 9; const uint8_t kPacket0ByteConnectionId = 0; const uint8_t kPacket8ByteConnectionId = 8; class TestStream : public QuicStream { public: TestStream(QuicStreamId id, QuicSession* session, StreamType type) : QuicStream(id, session, false, type) { sequencer()->set_level_triggered(true); } TestStream(PendingStream* pending, QuicSession* session, bool is_static) : QuicStream(pending, session, is_static) {} MOCK_METHOD(void, OnDataAvailable, (), (override)); MOCK_METHOD(void, OnCanWriteNewData, (), (override)); MOCK_METHOD(void, OnWriteSideInDataRecvdState, (), (override)); using QuicStream::CanWriteNewData; using QuicStream::CanWriteNewDataAfterData; using QuicStream::CloseWriteSide; using QuicStream::fin_buffered; using QuicStream::MaybeSendStopSending; using QuicStream::OnClose; using QuicStream::WriteMemSlices; using QuicStream::WriteOrBufferData; private: std::string data_; }; class QuicStreamTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicStreamTest() : zero_(QuicTime::Delta::Zero()), supported_versions_(AllSupportedVersions()) {} void Initialize(Perspective perspective = Perspective::IS_SERVER) { ParsedQuicVersionVector version_vector; version_vector.push_back(GetParam()); connection_ = new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, version_vector); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_); session_->Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_->config(), 10); session_->OnConfigNegotiated(); stream_ = new StrictMock<TestStream>(kTestStreamId, session_.get(), BIDIRECTIONAL); EXPECT_NE(nullptr, stream_); EXPECT_CALL(*session_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); session_->ActivateStream(absl::WrapUnique(stream_)); EXPECT_CALL(*session_, MaybeSendStopSendingFrame(kTestStreamId, _)) .Times(AnyNumber()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)) .Times(AnyNumber()); write_blocked_list_ = QuicSessionPeer::GetWriteBlockedStreams(session_.get()); } bool fin_sent() { return stream_->fin_sent(); } bool rst_sent() { return stream_->rst_sent(); } bool HasWriteBlockedStreams() { return write_blocked_list_->HasWriteBlockedSpecialStream() || write_blocked_list_->HasWriteBlockedDataStreams(); } QuicConsumedData CloseStreamOnWriteError( QuicStreamId id, QuicByteCount , QuicStreamOffset , StreamSendingState , TransmissionType , std::optional<EncryptionLevel> ) { session_->ResetStream(id, QUIC_STREAM_CANCELLED); return QuicConsumedData(1, false); } bool ClearResetStreamFrame(const QuicFrame& frame) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } bool ClearStopSendingFrame(const QuicFrame& frame) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<MockQuicSession> session_; StrictMock<TestStream>* stream_; QuicWriteBlockedListInterface* write_blocked_list_; QuicTime::Delta zero_; ParsedQuicVersionVector supported_versions_; QuicStreamId kTestStreamId = GetNthClientInitiatedBidirectionalStreamId( GetParam().transport_version, 1); const QuicStreamId kTestPendingStreamId = GetNthClientInitiatedUnidirectionalStreamId(GetParam().transport_version, 1); }; INSTANTIATE_TEST_SUITE_P(QuicStreamTests, QuicStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); using PendingStreamTest = QuicStreamTest; INSTANTIATE_TEST_SUITE_P(PendingStreamTests, PendingStreamTest, ::testing::ValuesIn(CurrentSupportedHttp3Versions()), ::testing::PrintToStringParamName()); TEST_P(PendingStreamTest, PendingStreamStaticness) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_FALSE(stream.is_static()); PendingStream pending2(kTestPendingStreamId + 4, session_.get()); TestStream stream2(&pending2, session_.get(), true); EXPECT_TRUE(stream2.is_static()); } TEST_P(PendingStreamTest, PendingStreamType) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(stream.type(), READ_UNIDIRECTIONAL); } TEST_P(PendingStreamTest, PendingStreamTypeOnClient) { Initialize(Perspective::IS_CLIENT); QuicStreamId server_initiated_pending_stream_id = GetNthServerInitiatedUnidirectionalStreamId(session_->transport_version(), 1); PendingStream pending(server_initiated_pending_stream_id, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(stream.type(), READ_UNIDIRECTIONAL); } TEST_P(PendingStreamTest, PendingStreamTooMuchData) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, kInitialSessionFlowControlWindowForTest + 1, "."); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending.OnStreamFrame(frame); } TEST_P(PendingStreamTest, PendingStreamTooMuchDataInRstStream) { Initialize(); PendingStream pending1(kTestPendingStreamId, session_.get()); QuicRstStreamFrame frame1(kInvalidControlFrameId, kTestPendingStreamId, QUIC_STREAM_CANCELLED, kInitialSessionFlowControlWindowForTest + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending1.OnRstStreamFrame(frame1); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending2(bidirection_stream_id, session_.get()); QuicRstStreamFrame frame2(kInvalidControlFrameId, bidirection_stream_id, QUIC_STREAM_CANCELLED, kInitialSessionFlowControlWindowForTest + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending2.OnRstStreamFrame(frame2); } TEST_P(PendingStreamTest, PendingStreamRstStream) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamOffset final_byte_offset = 7; QuicRstStreamFrame frame(kInvalidControlFrameId, kTestPendingStreamId, QUIC_STREAM_CANCELLED, final_byte_offset); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); pending.OnRstStreamFrame(frame); } TEST_P(PendingStreamTest, PendingStreamWindowUpdate) { Initialize(); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending(bidirection_stream_id, session_.get()); QuicWindowUpdateFrame frame(kInvalidControlFrameId, bidirection_stream_id, kDefaultFlowControlSendWindow * 2); pending.OnWindowUpdateFrame(frame); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(QuicStreamPeer::SendWindowSize(&stream), kDefaultFlowControlSendWindow * 2); } TEST_P(PendingStreamTest, PendingStreamStopSending) { Initialize(); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending(bidirection_stream_id, session_.get()); QuicResetStreamError error = QuicResetStreamError::FromInternal(QUIC_STREAM_INTERNAL_ERROR); pending.OnStopSending(error); EXPECT_TRUE(pending.GetStopSendingErrorCode()); auto actual_error = *pending.GetStopSendingErrorCode(); EXPECT_EQ(actual_error, error); } TEST_P(PendingStreamTest, FromPendingStream) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, 2, "."); pending.OnStreamFrame(frame); pending.OnStreamFrame(frame); QuicStreamFrame frame2(kTestPendingStreamId, true, 3, "."); pending.OnStreamFrame(frame2); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(3, stream.num_frames_received()); EXPECT_EQ(3u, stream.stream_bytes_read()); EXPECT_EQ(1, stream.num_duplicate_frames_received()); EXPECT_EQ(true, stream.fin_received()); EXPECT_EQ(frame2.offset + 1, stream.highest_received_byte_offset()); EXPECT_EQ(frame2.offset + 1, session_->flow_controller()->highest_received_byte_offset()); } TEST_P(PendingStreamTest, FromPendingStreamThenData) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, 2, "."); pending.OnStreamFrame(frame); auto stream = new TestStream(&pending, session_.get(), false); session_->ActivateStream(absl::WrapUnique(stream)); QuicStreamFrame frame2(kTestPendingStreamId, true, 3, "."); stream->OnStreamFrame(frame2); EXPECT_EQ(2, stream->num_frames_received()); EXPECT_EQ(2u, stream->stream_bytes_read()); EXPECT_EQ(true, stream->fin_received()); EXPECT_EQ(frame2.offset + 1, stream->highest_received_byte_offset()); EXPECT_EQ(frame2.offset + 1, session_->flow_controller()->highest_received_byte_offset()); } TEST_P(QuicStreamTest, WriteAllData) { Initialize(); QuicByteCount length = 1 + QuicPacketCreator::StreamFramePacketOverhead( connection_->transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0u); connection_->SetMaxPacketLength(length); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_FALSE(HasWriteBlockedStreams()); } TEST_P(QuicStreamTest, NoBlockingIfNoDataOrFin) { Initialize(); EXPECT_QUIC_BUG( stream_->WriteOrBufferData(absl::string_view(), false, nullptr), ""); EXPECT_FALSE(HasWriteBlockedStreams()); } TEST_P(QuicStreamTest, BlockIfOnlySomeDataConsumed) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); EXPECT_EQ(1u, stream_->BufferedDataBytes()); } TEST_P(QuicStreamTest, BlockIfFinNotConsumedWithData) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), true, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, BlockIfSoloFinNotConsumed) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(absl::string_view(), true, nullptr); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, CloseOnPartialWrite) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Invoke(this, &QuicStreamTest::CloseStreamOnWriteError)); stream_->WriteOrBufferData(absl::string_view(kData1, 2), false, nullptr); ASSERT_EQ(0u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, WriteOrBufferData) { Initialize(); EXPECT_FALSE(HasWriteBlockedStreams()); QuicByteCount length = 1 + QuicPacketCreator::StreamFramePacketOverhead( connection_->transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0u); connection_->SetMaxPacketLength(length); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), kDataLen - 1, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, stream_->BufferedDataBytes()); EXPECT_TRUE(HasWriteBlockedStreams()); stream_->WriteOrBufferData(kData2, false, nullptr); EXPECT_EQ(10u, stream_->BufferedDataBytes()); InSequence s; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), kDataLen - 1, kDataLen - 1, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()); stream_->OnCanWrite(); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 2 * kDataLen - 2, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()); stream_->OnCanWrite(); EXPECT_TRUE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, WriteOrBufferDataReachStreamLimit) { Initialize(); std::string data("aaaaa"); QuicStreamPeer::SetStreamBytesWritten(kMaxStreamLength - data.length(), stream_); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_QUIC_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->WriteOrBufferData("a", false, nullptr); }, "Write too many data via stream"); } TEST_P(QuicStreamTest, ConnectionCloseAfterStreamClose) { Initialize(); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(session_->transport_version())) { QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED); session_->OnStopSendingFrame(stop_sending); } EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_CANCELLED)); EXPECT_THAT(stream_->connection_error(), IsQuicNoError()); QuicConnectionCloseFrame frame; frame.quic_error_code = QUIC_INTERNAL_ERROR; stream_->OnConnectionClosed(frame, ConnectionCloseSource::FROM_SELF); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_CANCELLED)); EXPECT_THAT(stream_->connection_error(), IsQuicNoError()); } TEST_P(QuicStreamTest, RstAlwaysSentIfNoFinSent) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 1), false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(session_->transport_version())) { QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED); session_->OnStopSendingFrame(stop_sending); } EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); } TEST_P(QuicStreamTest, RstNotSentIfFinSent) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 1), true, nullptr); EXPECT_TRUE(fin_sent()); EXPECT_FALSE(rst_sent()); QuicStreamPeer::CloseReadSide(stream_); stream_->CloseWriteSide(); EXPECT_TRUE(fin_sent()); EXPECT_FALSE(rst_sent()); } TEST_P(QuicStreamTest, OnlySendOneRst) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)).Times(1); stream_->Reset(QUIC_STREAM_CANCELLED); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); QuicStreamPeer::CloseReadSide(stream_); stream_->CloseWriteSide(); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); } TEST_P(QuicStreamTest, StreamFlowControlMultipleWindowUpdates) { Initialize(); EXPECT_EQ(kMinimumFlowControlSendWindow, QuicStreamPeer::SendWindowOffset(stream_)); QuicWindowUpdateFrame window_update_1(kInvalidControlFrameId, stream_->id(), kMinimumFlowControlSendWindow + 5); stream_->OnWindowUpdateFrame(window_update_1); EXPECT_EQ(window_update_1.max_data, QuicStreamPeer::SendWindowOffset(stream_)); QuicWindowUpdateFrame window_update_2(kInvalidControlFrameId, stream_->id(), 1); QuicWindowUpdateFrame window_update_3(kInvalidControlFrameId, stream_->id(), kMinimumFlowControlSendWindow + 10); QuicWindowUpdateFrame window_update_4(kInvalidControlFrameId, stream_->id(), 5678); stream_->OnWindowUpdateFrame(window_update_2); stream_->OnWindowUpdateFrame(window_update_3); stream_->OnWindowUpdateFrame(window_update_4); EXPECT_EQ(window_update_3.max_data, QuicStreamPeer::SendWindowOffset(stream_)); } TEST_P(QuicStreamTest, FrameStats) { Initialize(); EXPECT_EQ(0, stream_->num_frames_received()); EXPECT_EQ(0, stream_->num_duplicate_frames_received()); QuicStreamFrame frame(stream_->id(), false, 0, "."); EXPECT_CALL(*stream_, OnDataAvailable()).Times(2); stream_->OnStreamFrame(frame); EXPECT_EQ(1, stream_->num_frames_received()); EXPECT_EQ(0, stream_->num_duplicate_frames_received()); stream_->OnStreamFrame(frame); EXPECT_EQ(2, stream_->num_frames_received()); EXPECT_EQ(1, stream_->num_duplicate_frames_received()); QuicStreamFrame frame2(stream_->id(), false, 1, "abc"); stream_->OnStreamFrame(frame2); } TEST_P(QuicStreamTest, StreamSequencerNeverSeesPacketsViolatingFlowControl) { Initialize(); QuicStreamFrame frame(stream_->id(), false, kInitialSessionFlowControlWindowForTest + 1, "."); EXPECT_GT(frame.offset, QuicStreamPeer::ReceiveWindowOffset(stream_)); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); stream_->OnStreamFrame(frame); } TEST_P(QuicStreamTest, StopReadingSendsFlowControl) { Initialize(); stream_->StopReading(); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)) .Times(0); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); std::string data(1000, 'x'); for (QuicStreamOffset offset = 0; offset < 2 * kInitialStreamFlowControlWindowForTest; offset += data.length()) { QuicStreamFrame frame(stream_->id(), false, offset, data); stream_->OnStreamFrame(frame); } EXPECT_LT(kInitialStreamFlowControlWindowForTest, QuicStreamPeer::ReceiveWindowOffset(stream_)); } TEST_P(QuicStreamTest, FinalByteOffsetFromFin) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicStreamFrame stream_frame_no_fin(stream_->id(), false, 1234, "."); stream_->OnStreamFrame(stream_frame_no_fin); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicStreamFrame stream_frame_with_fin(stream_->id(), true, 1234, "."); stream_->OnStreamFrame(stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, FinalByteOffsetFromRst) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, InvalidFinalByteOffsetFromRst) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 0xFFFFFFFFFFFF); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); stream_->OnStreamReset(rst_frame); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, FinalByteOffsetFromZeroLengthStreamFrame) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); const QuicStreamOffset kByteOffsetExceedingFlowControlWindow = kInitialSessionFlowControlWindowForTest + 1; const QuicStreamOffset current_stream_flow_control_offset = QuicStreamPeer::ReceiveWindowOffset(stream_); const QuicStreamOffset current_connection_flow_control_offset = QuicFlowControllerPeer::ReceiveWindowOffset(session_->flow_controller()); ASSERT_GT(kByteOffsetExceedingFlowControlWindow, current_stream_flow_control_offset); ASSERT_GT(kByteOffsetExceedingFlowControlWindow, current_connection_flow_control_offset); QuicStreamFrame zero_length_stream_frame_with_fin( stream_->id(), true, kByteOffsetExceedingFlowControlWindow, absl::string_view()); EXPECT_EQ(0, zero_length_stream_frame_with_fin.data_length); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); stream_->OnStreamFrame(zero_length_stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); EXPECT_EQ(current_stream_flow_control_offset, QuicStreamPeer::ReceiveWindowOffset(stream_)); EXPECT_EQ( current_connection_flow_control_offset, QuicFlowControllerPeer::ReceiveWindowOffset(session_->flow_controller())); } TEST_P(QuicStreamTest, OnStreamResetOffsetOverflow) { Initialize(); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, kMaxStreamLength + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->OnStreamReset(rst_frame); } TEST_P(QuicStreamTest, OnStreamFrameUpperLimit) { Initialize(); QuicStreamPeer::SetReceiveWindowOffset(stream_, kMaxStreamLength + 5u); QuicFlowControllerPeer::SetReceiveWindowOffset(session_->flow_controller(), kMaxStreamLength + 5u); QuicStreamSequencerPeer::SetFrameBufferTotalBytesRead( QuicStreamPeer::sequencer(stream_), kMaxStreamLength - 10u); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)) .Times(0); QuicStreamFrame stream_frame(stream_->id(), false, kMaxStreamLength - 1, "."); stream_->OnStreamFrame(stream_frame); QuicStreamFrame stream_frame2(stream_->id(), true, kMaxStreamLength, ""); stream_->OnStreamFrame(stream_frame2); } TEST_P(QuicStreamTest, StreamTooLong) { Initialize(); QuicStreamFrame stream_frame(stream_->id(), false, kMaxStreamLength, "."); EXPECT_QUIC_PEER_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)) .Times(1); stream_->OnStreamFrame(stream_frame); }, absl::StrCat("Receive stream frame on stream ", stream_->id(), " reaches max stream length")); } TEST_P(QuicStreamTest, SetDrainingIncomingOutgoing) {
262
cpp
google/quiche
quic_packets
quiche/quic/core/quic_packets.cc
quiche/quic/core/quic_packets_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_PACKETS_H_ #define QUICHE_QUIC_CORE_QUIC_PACKETS_H_ #include <sys/types.h> #include <cstddef> #include <cstdint> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/quic_ack_listener_interface.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { class QuicPacket; struct QuicPacketHeader; QUICHE_EXPORT QuicConnectionId GetServerConnectionIdAsRecipient( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT QuicConnectionId GetClientConnectionIdAsRecipient( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT QuicConnectionId GetServerConnectionIdAsSender( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT QuicConnectionIdIncluded GetServerConnectionIdIncludedAsSender( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT QuicConnectionId GetClientConnectionIdAsSender( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT QuicConnectionIdIncluded GetClientConnectionIdIncludedAsSender( const QuicPacketHeader& header, Perspective perspective); QUICHE_EXPORT uint8_t GetIncludedConnectionIdLength(QuicConnectionId connection_id, QuicConnectionIdIncluded connection_id_included); QUICHE_EXPORT uint8_t GetIncludedDestinationConnectionIdLength(const QuicPacketHeader& header); QUICHE_EXPORT uint8_t GetIncludedSourceConnectionIdLength(const QuicPacketHeader& header); QUICHE_EXPORT size_t GetPacketHeaderSize(QuicTransportVersion version, const QuicPacketHeader& header); QUICHE_EXPORT size_t GetPacketHeaderSize( QuicTransportVersion version, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool include_version, bool include_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length); QUICHE_EXPORT size_t GetStartOfEncryptedData(QuicTransportVersion version, const QuicPacketHeader& header); QUICHE_EXPORT size_t GetStartOfEncryptedData( QuicTransportVersion version, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool include_version, bool include_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length); struct QUICHE_EXPORT QuicPacketHeader { QuicPacketHeader(); QuicPacketHeader(const QuicPacketHeader& other); ~QuicPacketHeader(); QuicPacketHeader& operator=(const QuicPacketHeader& other); QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os, const QuicPacketHeader& header); QuicConnectionId destination_connection_id; QuicConnectionIdIncluded destination_connection_id_included; QuicConnectionId source_connection_id; QuicConnectionIdIncluded source_connection_id_included; bool reset_flag; bool version_flag; bool has_possible_stateless_reset_token; QuicPacketNumberLength packet_number_length; uint8_t type_byte; ParsedQuicVersion version; DiversificationNonce* nonce; QuicPacketNumber packet_number; PacketHeaderFormat form; QuicLongHeaderType long_packet_type; StatelessResetToken possible_stateless_reset_token; quiche::QuicheVariableLengthIntegerLength retry_token_length_length; absl::string_view retry_token; quiche::QuicheVariableLengthIntegerLength length_length; QuicByteCount remaining_packet_length; bool operator==(const QuicPacketHeader& other) const; bool operator!=(const QuicPacketHeader& other) const; }; struct QUICHE_EXPORT QuicPublicResetPacket { QuicPublicResetPacket(); explicit QuicPublicResetPacket(QuicConnectionId connection_id); QuicConnectionId connection_id; QuicPublicResetNonceProof nonce_proof; QuicSocketAddress client_address; std::string endpoint_id; }; struct QUICHE_EXPORT QuicVersionNegotiationPacket { QuicVersionNegotiationPacket(); explicit QuicVersionNegotiationPacket(QuicConnectionId connection_id); QuicVersionNegotiationPacket(const QuicVersionNegotiationPacket& other); ~QuicVersionNegotiationPacket(); QuicConnectionId connection_id; ParsedQuicVersionVector versions; }; struct QUICHE_EXPORT QuicIetfStatelessResetPacket { QuicIetfStatelessResetPacket(); QuicIetfStatelessResetPacket(const QuicPacketHeader& header, StatelessResetToken token); QuicIetfStatelessResetPacket(const QuicIetfStatelessResetPacket& other); ~QuicIetfStatelessResetPacket(); QuicPacketHeader header; StatelessResetToken stateless_reset_token; }; class QUICHE_EXPORT QuicData { public: QuicData(const char* buffer, size_t length); QuicData(const char* buffer, size_t length, bool owns_buffer); QuicData(absl::string_view data); QuicData(const QuicData&) = delete; QuicData& operator=(const QuicData&) = delete; virtual ~QuicData(); absl::string_view AsStringPiece() const { return absl::string_view(data(), length()); } const char* data() const { return buffer_; } size_t length() const { return length_; } private: const char* buffer_; size_t length_; bool owns_buffer_; }; class QUICHE_EXPORT QuicPacket : public QuicData { public: QuicPacket( char* buffer, size_t length, bool owns_buffer, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool includes_version, bool includes_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length); QuicPacket(QuicTransportVersion version, char* buffer, size_t length, bool owns_buffer, const QuicPacketHeader& header); QuicPacket(const QuicPacket&) = delete; QuicPacket& operator=(const QuicPacket&) = delete; absl::string_view AssociatedData(QuicTransportVersion version) const; absl::string_view Plaintext(QuicTransportVersion version) const; char* mutable_data() { return buffer_; } private: char* buffer_; const uint8_t destination_connection_id_length_; const uint8_t source_connection_id_length_; const bool includes_version_; const bool includes_diversification_nonce_; const QuicPacketNumberLength packet_number_length_; const quiche::QuicheVariableLengthIntegerLength retry_token_length_length_; const QuicByteCount retry_token_length_; const quiche::QuicheVariableLengthIntegerLength length_length_; }; class QUICHE_EXPORT QuicEncryptedPacket : public QuicData { public: QuicEncryptedPacket(const char* buffer, size_t length); QuicEncryptedPacket(const char* buffer, size_t length, bool owns_buffer); QuicEncryptedPacket(absl::string_view data); QuicEncryptedPacket(const QuicEncryptedPacket&) = delete; QuicEncryptedPacket& operator=(const QuicEncryptedPacket&) = delete; std::unique_ptr<QuicEncryptedPacket> Clone() const; QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os, const QuicEncryptedPacket& s); }; namespace test { class QuicReceivedPacketPeer; } class QUICHE_EXPORT QuicReceivedPacket : public QuicEncryptedPacket { public: QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time); QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer); QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer, int ttl, bool ttl_valid); QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer, int ttl, bool ttl_valid, char* packet_headers, size_t headers_length, bool owns_header_buffer); QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer, int ttl, bool ttl_valid, char* packet_headers, size_t headers_length, bool owns_header_buffer, QuicEcnCodepoint ecn_codepoint); ~QuicReceivedPacket(); QuicReceivedPacket(const QuicReceivedPacket&) = delete; QuicReceivedPacket& operator=(const QuicReceivedPacket&) = delete; std::unique_ptr<QuicReceivedPacket> Clone() const; QuicTime receipt_time() const { return receipt_time_; } int ttl() const { return ttl_; } char* packet_headers() const { return packet_headers_; } int headers_length() const { return headers_length_; } QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os, const QuicReceivedPacket& s); QuicEcnCodepoint ecn_codepoint() const { return ecn_codepoint_; } private: friend class test::QuicReceivedPacketPeer; const QuicTime receipt_time_; int ttl_; char* packet_headers_; int headers_length_; bool owns_header_buffer_; QuicEcnCodepoint ecn_codepoint_; }; struct QUICHE_EXPORT SerializedPacket { SerializedPacket(QuicPacketNumber packet_number, QuicPacketNumberLength packet_number_length, const char* encrypted_buffer, QuicPacketLength encrypted_length, bool has_ack, bool has_stop_waiting); SerializedPacket(const SerializedPacket& other) = delete; SerializedPacket& operator=(const SerializedPacket& other) = delete; SerializedPacket(SerializedPacket&& other); ~SerializedPacket(); const char* encrypted_buffer; QuicPacketLength encrypted_length; std::function<void(const char*)> release_encrypted_buffer; QuicFrames retransmittable_frames; QuicFrames nonretransmittable_frames; IsHandshake has_crypto_handshake; QuicPacketNumber packet_number; QuicPacketNumberLength packet_number_length; EncryptionLevel encryption_level; bool has_ack; bool has_stop_waiting; bool has_ack_ecn = false; TransmissionType transmission_type; QuicPacketNumber largest_acked; bool has_ack_frame_copy; bool has_ack_frequency; bool has_message; SerializedPacketFate fate; QuicSocketAddress peer_address; std::optional<QuicByteCount> bytes_not_retransmitted; std::optional<QuicPacketHeader> initial_header; }; QUICHE_EXPORT SerializedPacket* CopySerializedPacket( const SerializedPacket& serialized, quiche::QuicheBufferAllocator* allocator, bool copy_buffer); QUICHE_EXPORT char* CopyBuffer(const SerializedPacket& packet); QUICHE_EXPORT char* CopyBuffer(const char* encrypted_buffer, QuicPacketLength encrypted_length); struct QUICHE_EXPORT QuicPerPacketContext { virtual ~QuicPerPacketContext() {} }; struct QUICHE_EXPORT ReceivedPacketInfo { ReceivedPacketInfo(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet); ReceivedPacketInfo(const ReceivedPacketInfo& other) = default; ~ReceivedPacketInfo(); std::string ToString() const; QUICHE_EXPORT friend std::ostream& operator<<( std::ostream& os, const ReceivedPacketInfo& packet_info); const QuicSocketAddress& self_address; const QuicSocketAddress& peer_address; const QuicReceivedPacket& packet; PacketHeaderFormat form; QuicLongHeaderType long_packet_type; bool version_flag; bool use_length_prefix; QuicVersionLabel version_label; ParsedQuicVersion version; QuicConnectionId destination_connection_id; QuicConnectionId source_connection_id; std::optional<absl::string_view> retry_token; }; } #endif #include "quiche/quic/core/quic_packets.h" #include <algorithm> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicConnectionId GetServerConnectionIdAsRecipient( const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_SERVER) { return header.destination_connection_id; } return header.source_connection_id; } QuicConnectionId GetClientConnectionIdAsRecipient( const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_CLIENT) { return header.destination_connection_id; } return header.source_connection_id; } QuicConnectionId GetServerConnectionIdAsSender(const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_CLIENT) { return header.destination_connection_id; } return header.source_connection_id; } QuicConnectionIdIncluded GetServerConnectionIdIncludedAsSender( const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_CLIENT) { return header.destination_connection_id_included; } return header.source_connection_id_included; } QuicConnectionId GetClientConnectionIdAsSender(const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_CLIENT) { return header.source_connection_id; } return header.destination_connection_id; } QuicConnectionIdIncluded GetClientConnectionIdIncludedAsSender( const QuicPacketHeader& header, Perspective perspective) { if (perspective == Perspective::IS_CLIENT) { return header.source_connection_id_included; } return header.destination_connection_id_included; } uint8_t GetIncludedConnectionIdLength( QuicConnectionId connection_id, QuicConnectionIdIncluded connection_id_included) { QUICHE_DCHECK(connection_id_included == CONNECTION_ID_PRESENT || connection_id_included == CONNECTION_ID_ABSENT); return connection_id_included == CONNECTION_ID_PRESENT ? connection_id.length() : 0; } uint8_t GetIncludedDestinationConnectionIdLength( const QuicPacketHeader& header) { return GetIncludedConnectionIdLength( header.destination_connection_id, header.destination_connection_id_included); } uint8_t GetIncludedSourceConnectionIdLength(const QuicPacketHeader& header) { return GetIncludedConnectionIdLength(header.source_connection_id, header.source_connection_id_included); } size_t GetPacketHeaderSize(QuicTransportVersion version, const QuicPacketHeader& header) { return GetPacketHeaderSize( version, GetIncludedDestinationConnectionIdLength(header), GetIncludedSourceConnectionIdLength(header), header.version_flag, header.nonce != nullptr, header.packet_number_length, header.retry_token_length_length, header.retry_token.length(), header.length_length); } size_t GetPacketHeaderSize( QuicTransportVersion version, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool include_version, bool include_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) { if (include_version) { size_t size = kPacketHeaderTypeSize + kConnectionIdLengthSize + destination_connection_id_length + source_connection_id_length + packet_number_length + kQuicVersionSize; if (include_diversification_nonce) { size += kDiversificationNonceSize; } if (VersionHasLengthPrefixedConnectionIds(version)) { size += kConnectionIdLengthSize; } QUICHE_DCHECK( QuicVersionHasLongHeaderLengths(version) || retry_token_length_length + retry_token_length + length_length == 0); if (QuicVersionHasLongHeaderLengths(version)) { size += retry_token_length_length + retry_token_length + length_length; } return size; } return kPacketHeaderTypeSize + destination_connection_id_length + packet_number_length; } size_t GetStartOfEncryptedData(QuicTransportVersion version, const QuicPacketHeader& header) { return GetPacketHeaderSize(version, header); } size_t GetStartOfEncryptedData( QuicTransportVersion version, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool include_version, bool include_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) { return GetPacketHeaderSize( version, destination_connection_id_length, source_connection_id_length, include_version, include_diversification_nonce, packet_number_length, retry_token_length_length, retry_token_length, length_length); } QuicPacketHeader::QuicPacketHeader() : destination_connection_id(EmptyQuicConnectionId()), destination_connection_id_included(CONNECTION_ID_PRESENT), source_connection_id(EmptyQuicConnectionId()), source_connection_id_included(CONNECTION_ID_ABSENT), reset_flag(false), version_flag(false), has_possible_stateless_reset_token(false), packet_number_length(PACKET_4BYTE_PACKET_NUMBER), type_byte(0), version(UnsupportedQuicVersion()), nonce(nullptr), form(GOOGLE_QUIC_PACKET), long_packet_type(INITIAL), possible_stateless_reset_token({}), retry_token_length_length(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0), retry_token(absl::string_view()), length_length(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0), remaining_packet_length(0) {} QuicPacketHeader::QuicPacketHeader(const QuicPacketHeader& other) = default; QuicPacketHeader::~QuicPacketHeader() {} QuicPacketHeader& QuicPacketHeader::operator=(const QuicPacketHeader& other) = default; QuicPublicResetPacket::QuicPublicResetPacket() : connection_id(EmptyQuicConnectionId()), nonce_proof(0) {} QuicPublicResetPacket::QuicPublicResetPacket(QuicConnectionId connection_id) : connection_id(connection_id), nonce_proof(0) {} QuicVersionNegotiationPacket::QuicVersionNegotiationPacket() : connection_id(EmptyQuicConnectionId()) {} QuicVersionNegotiationPacket::QuicVersionNegotiationPacket( QuicConnectionId connection_id) : connection_id(connection_id) {} QuicVersionNegotiationPacket::QuicVersionNegotiationPacket( const QuicVersionNegotiationPacket& other) = default; QuicVersionNegotiationPacket::~QuicVersionNegotiationPacket() {} QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket() : stateless_reset_token({}) {} QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket( const QuicPacketHeader& header, StatelessResetToken token) : header(header), stateless_reset_token(token) {} QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& other) = default; QuicIetfStatelessResetPacket::~QuicIetfStatelessResetPacket() {} std::ostream& operator<<(std::ostream& os, const QuicPacketHeader& header) { os << "{ destination_connection_id: " << header.destination_connection_id << " (" << (header.destination_connection_id_included == CONNECTION_ID_PRESENT ? "present" : "absent") << "), source_connection_id: " << header.source_connection_id << " (" << (header.source_connection_id_included == CONNECTION_ID_PRESENT ? "present" : "absent") << "), packet_number_length: " << static_cast<int>(header.packet_number_length) << ", reset_flag: " << header.reset_flag << ", version_flag: " << header.version_flag; if (header.version_flag) { os << ", version: " << ParsedQuicVersionToString(header.version); if (header.long_packet_type != INVALID_PACKET_TYPE) { os << ", long_packet_type: " << QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type); } if (header.retry_token_length_length != quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) { os << ", retry_token_length_length: " << static_cast<int>(header.retry_token_length_length); } if (header.retry_token.length() != 0) { os << ", retry_token_length: " << header.retry_token.length(); } if (header.length_length != quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) { os << ", length_length: " << static_cast<int>(header.length_length); } if (header.remaining_packet_length != 0) { os << ", remaining_packet_length: " << header.remaining_packet_length; } } if (header.nonce != nullptr) { os << ", diversification_nonce: " << absl::BytesToHexString( absl::string_view(header.nonce->data(), header.nonce->size())); } os << ", packet_number: " << header.packet_number << " }\n"; return os; } QuicData::QuicData(const char* buffer, size_t length) : buffer_(buffer), length_(length), owns_buffer_(false) {} QuicData::QuicData(const char* buffer, size_t length, bool owns_buffer) : buffer_(buffer), length_(length), owns_buffer_(owns_buffer) {} QuicData::QuicData(absl::string_view packet_data) : buffer_(packet_data.data()), length_(packet_data.length()), owns_buffer_(false) {} QuicData::~QuicData() { if (owns_buffer_) { delete[] const_cast<char*>(buffer_); } } QuicPacket::QuicPacket( char* buffer, size_t length, bool owns_buffer, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool includes_version, bool includes_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, QuicByteCount retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) : QuicData(buffer, length, owns_buffer), buffer_(buffer), destination_connection_id_length_(destination_connection_id_length), source_connection_id_length_(source_connection_id_length), includes_version_(includes_version), includes_diversification_nonce_(includes_diversification_nonce), packet_number_length_(packet_number_length), retry_token_length_length_(retry_token_length_length), retry_token_length_(retry_token_length), length_length_(length_length) {} QuicPacket::QuicPacket(QuicTransportVersion , char* buffer, size_t length, bool owns_buffer, const QuicPacketHeader& header) : QuicPacket(buffer, length, owns_buffer, GetIncludedDestinationConnectionIdLength(header), GetIncludedSourceConnectionIdLength(header), header.version_flag, header.nonce != nullptr, header.packet_number_length, header.retry_token_length_length, header.retry_token.length(), header.length_length) {} QuicEncryptedPacket::QuicEncryptedPacket(const char* buffer, size_t length) : QuicData(buffer, length) {} QuicEncryptedPacket::QuicEncryptedPacket(const char* buffer, size_t length, bool owns_buffer) : QuicData(buffer, length, owns_buffer) {} QuicEncryptedPacket::QuicEncryptedPacket(absl::string_view data) : QuicData(data) {} std::unique_ptr<QuicEncryptedPacket> QuicEncryptedPacket::Clone() const { char* buffer = new char[this->length()]; std::copy(this->data(), this->data() + this->length(), buffer); return std::make_unique<QuicEncryptedPacket>(buffer, this->length(), true); } std::ostream& operator<<(std::ostream& os, const QuicEncryptedPacket& s) { os << s.length() << "-byte data"; return os; } QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time) : QuicReceivedPacket(buffer, length, receipt_time, false ) {} QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer) : QuicReceivedPacket(buffer, length, receipt_time, owns_buffer, 0 , true ) {} QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer, int ttl, bool ttl_valid) : quic::QuicReceivedPacket(buffer, length, receipt_time, owns_buffer, ttl, ttl_valid, nullptr , 0 , false , ECN_NOT_ECT) {} QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer, int ttl, bool ttl_valid, char* packet_heade
#include "quiche/quic/core/quic_packets.h" #include <memory> #include <string> #include "absl/memory/memory.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { QuicPacketHeader CreateFakePacketHeader() { QuicPacketHeader header; header.destination_connection_id = TestConnectionId(1); header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.source_connection_id = TestConnectionId(2); header.source_connection_id_included = CONNECTION_ID_ABSENT; return header; } class QuicPacketsTest : public QuicTest {}; TEST_F(QuicPacketsTest, GetServerConnectionIdAsRecipient) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(TestConnectionId(1), GetServerConnectionIdAsRecipient(header, Perspective::IS_SERVER)); EXPECT_EQ(TestConnectionId(2), GetServerConnectionIdAsRecipient(header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, GetServerConnectionIdAsSender) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(TestConnectionId(2), GetServerConnectionIdAsSender(header, Perspective::IS_SERVER)); EXPECT_EQ(TestConnectionId(1), GetServerConnectionIdAsSender(header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, GetServerConnectionIdIncludedAsSender) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(CONNECTION_ID_ABSENT, GetServerConnectionIdIncludedAsSender( header, Perspective::IS_SERVER)); EXPECT_EQ(CONNECTION_ID_PRESENT, GetServerConnectionIdIncludedAsSender( header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, GetClientConnectionIdIncludedAsSender) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(CONNECTION_ID_PRESENT, GetClientConnectionIdIncludedAsSender( header, Perspective::IS_SERVER)); EXPECT_EQ(CONNECTION_ID_ABSENT, GetClientConnectionIdIncludedAsSender( header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, GetClientConnectionIdAsRecipient) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(TestConnectionId(2), GetClientConnectionIdAsRecipient(header, Perspective::IS_SERVER)); EXPECT_EQ(TestConnectionId(1), GetClientConnectionIdAsRecipient(header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, GetClientConnectionIdAsSender) { QuicPacketHeader header = CreateFakePacketHeader(); EXPECT_EQ(TestConnectionId(1), GetClientConnectionIdAsSender(header, Perspective::IS_SERVER)); EXPECT_EQ(TestConnectionId(2), GetClientConnectionIdAsSender(header, Perspective::IS_CLIENT)); } TEST_F(QuicPacketsTest, CopyQuicPacketHeader) { QuicPacketHeader header; QuicPacketHeader header2 = CreateFakePacketHeader(); EXPECT_NE(header, header2); QuicPacketHeader header3(header2); EXPECT_EQ(header2, header3); } TEST_F(QuicPacketsTest, CopySerializedPacket) { std::string buffer(1000, 'a'); quiche::SimpleBufferAllocator allocator; SerializedPacket packet(QuicPacketNumber(1), PACKET_1BYTE_PACKET_NUMBER, buffer.data(), buffer.length(), false, false); packet.retransmittable_frames.push_back(QuicFrame(QuicWindowUpdateFrame())); packet.retransmittable_frames.push_back(QuicFrame(QuicStreamFrame())); QuicAckFrame ack_frame(InitAckFrame(1)); packet.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(-1))); std::unique_ptr<SerializedPacket> copy = absl::WrapUnique<SerializedPacket>( CopySerializedPacket(packet, &allocator, true)); EXPECT_EQ(quic::QuicPacketNumber(1), copy->packet_number); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, copy->packet_number_length); ASSERT_EQ(2u, copy->retransmittable_frames.size()); EXPECT_EQ(WINDOW_UPDATE_FRAME, copy->retransmittable_frames[0].type); EXPECT_EQ(STREAM_FRAME, copy->retransmittable_frames[1].type); ASSERT_EQ(2u, copy->nonretransmittable_frames.size()); EXPECT_EQ(ACK_FRAME, copy->nonretransmittable_frames[0].type); EXPECT_EQ(PADDING_FRAME, copy->nonretransmittable_frames[1].type); EXPECT_EQ(1000u, copy->encrypted_length); quiche::test::CompareCharArraysWithHexError( "encrypted_buffer", copy->encrypted_buffer, copy->encrypted_length, packet.encrypted_buffer, packet.encrypted_length); std::unique_ptr<SerializedPacket> copy2 = absl::WrapUnique<SerializedPacket>( CopySerializedPacket(packet, &allocator, false)); EXPECT_EQ(packet.encrypted_buffer, copy2->encrypted_buffer); EXPECT_EQ(1000u, copy2->encrypted_length); } TEST_F(QuicPacketsTest, CloneReceivedPacket) { char header[4] = "bar"; QuicReceivedPacket packet("foo", 3, QuicTime::Zero(), false, 0, true, header, sizeof(header) - 1, false, QuicEcnCodepoint::ECN_ECT1); std::unique_ptr<QuicReceivedPacket> copy = packet.Clone(); EXPECT_EQ(packet.ecn_codepoint(), copy->ecn_codepoint()); } } } }
263
cpp
google/quiche
uber_received_packet_manager
quiche/quic/core/uber_received_packet_manager.cc
quiche/quic/core/uber_received_packet_manager_test.cc
#ifndef QUICHE_QUIC_CORE_UBER_RECEIVED_PACKET_MANAGER_H_ #define QUICHE_QUIC_CORE_UBER_RECEIVED_PACKET_MANAGER_H_ #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/quic_received_packet_manager.h" namespace quic { class QUICHE_EXPORT UberReceivedPacketManager { public: explicit UberReceivedPacketManager(QuicConnectionStats* stats); UberReceivedPacketManager(const UberReceivedPacketManager&) = delete; UberReceivedPacketManager& operator=(const UberReceivedPacketManager&) = delete; virtual ~UberReceivedPacketManager(); void SetFromConfig(const QuicConfig& config, Perspective perspective); bool IsAwaitingPacket(EncryptionLevel decrypted_packet_level, QuicPacketNumber packet_number) const; void RecordPacketReceived(EncryptionLevel decrypted_packet_level, const QuicPacketHeader& header, QuicTime receipt_time, QuicEcnCodepoint ecn_codepoint); const QuicFrame GetUpdatedAckFrame(PacketNumberSpace packet_number_space, QuicTime approximate_now); void DontWaitForPacketsBefore(EncryptionLevel decrypted_packet_level, QuicPacketNumber least_unacked); void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, EncryptionLevel decrypted_packet_level, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats); void ResetAckStates(EncryptionLevel encryption_level); void EnableMultiplePacketNumberSpacesSupport(Perspective perspective); bool IsAckFrameUpdated() const; QuicPacketNumber GetLargestObserved( EncryptionLevel decrypted_packet_level) const; QuicTime GetAckTimeout(PacketNumberSpace packet_number_space) const; QuicTime GetEarliestAckTimeout() const; bool IsAckFrameEmpty(PacketNumberSpace packet_number_space) const; size_t min_received_before_ack_decimation() const; void set_min_received_before_ack_decimation(size_t new_value); void set_ack_frequency(size_t new_value); bool supports_multiple_packet_number_spaces() const { return supports_multiple_packet_number_spaces_; } const QuicAckFrame& ack_frame() const; const QuicAckFrame& GetAckFrame(PacketNumberSpace packet_number_space) const; void set_max_ack_ranges(size_t max_ack_ranges); void OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame); void set_save_timestamps(bool save_timestamps); private: friend class test::QuicConnectionPeer; friend class test::UberReceivedPacketManagerPeer; QuicReceivedPacketManager received_packet_managers_[NUM_PACKET_NUMBER_SPACES]; bool supports_multiple_packet_number_spaces_; }; } #endif #include "quiche/quic/core/uber_received_packet_manager.h" #include <algorithm> #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { UberReceivedPacketManager::UberReceivedPacketManager(QuicConnectionStats* stats) : supports_multiple_packet_number_spaces_(false) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_connection_stats(stats); } } UberReceivedPacketManager::~UberReceivedPacketManager() {} void UberReceivedPacketManager::SetFromConfig(const QuicConfig& config, Perspective perspective) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.SetFromConfig(config, perspective); } } bool UberReceivedPacketManager::IsAwaitingPacket( EncryptionLevel decrypted_packet_level, QuicPacketNumber packet_number) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].IsAwaitingPacket(packet_number); } return received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .IsAwaitingPacket(packet_number); } const QuicFrame UberReceivedPacketManager::GetUpdatedAckFrame( PacketNumberSpace packet_number_space, QuicTime approximate_now) { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].GetUpdatedAckFrame(approximate_now); } return received_packet_managers_[packet_number_space].GetUpdatedAckFrame( approximate_now); } void UberReceivedPacketManager::RecordPacketReceived( EncryptionLevel decrypted_packet_level, const QuicPacketHeader& header, QuicTime receipt_time, QuicEcnCodepoint ecn_codepoint) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].RecordPacketReceived(header, receipt_time, ecn_codepoint); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .RecordPacketReceived(header, receipt_time, ecn_codepoint); } void UberReceivedPacketManager::DontWaitForPacketsBefore( EncryptionLevel decrypted_packet_level, QuicPacketNumber least_unacked) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].DontWaitForPacketsBefore(least_unacked); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .DontWaitForPacketsBefore(least_unacked); } void UberReceivedPacketManager::MaybeUpdateAckTimeout( bool should_last_packet_instigate_acks, EncryptionLevel decrypted_packet_level, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].MaybeUpdateAckTimeout( should_last_packet_instigate_acks, last_received_packet_number, last_packet_receipt_time, now, rtt_stats); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .MaybeUpdateAckTimeout(should_last_packet_instigate_acks, last_received_packet_number, last_packet_receipt_time, now, rtt_stats); } void UberReceivedPacketManager::ResetAckStates( EncryptionLevel encryption_level) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].ResetAckStates(); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace(encryption_level)] .ResetAckStates(); if (encryption_level == ENCRYPTION_INITIAL) { received_packet_managers_[INITIAL_DATA].set_local_max_ack_delay( kAlarmGranularity); } } void UberReceivedPacketManager::EnableMultiplePacketNumberSpacesSupport( Perspective perspective) { if (supports_multiple_packet_number_spaces_) { QUIC_BUG(quic_bug_10495_1) << "Multiple packet number spaces has already been enabled"; return; } if (received_packet_managers_[0].GetLargestObserved().IsInitialized()) { QUIC_BUG(quic_bug_10495_2) << "Try to enable multiple packet number spaces support after any " "packet has been received."; return; } if (perspective == Perspective::IS_CLIENT) { received_packet_managers_[INITIAL_DATA].set_local_max_ack_delay( kAlarmGranularity); } received_packet_managers_[HANDSHAKE_DATA].set_local_max_ack_delay( kAlarmGranularity); supports_multiple_packet_number_spaces_ = true; } bool UberReceivedPacketManager::IsAckFrameUpdated() const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].ack_frame_updated(); } for (const auto& received_packet_manager : received_packet_managers_) { if (received_packet_manager.ack_frame_updated()) { return true; } } return false; } QuicPacketNumber UberReceivedPacketManager::GetLargestObserved( EncryptionLevel decrypted_packet_level) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].GetLargestObserved(); } return received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .GetLargestObserved(); } QuicTime UberReceivedPacketManager::GetAckTimeout( PacketNumberSpace packet_number_space) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].ack_timeout(); } return received_packet_managers_[packet_number_space].ack_timeout(); } QuicTime UberReceivedPacketManager::GetEarliestAckTimeout() const { QuicTime ack_timeout = QuicTime::Zero(); for (const auto& received_packet_manager : received_packet_managers_) { const QuicTime timeout = received_packet_manager.ack_timeout(); if (!ack_timeout.IsInitialized()) { ack_timeout = timeout; continue; } if (timeout.IsInitialized()) { ack_timeout = std::min(ack_timeout, timeout); } } return ack_timeout; } bool UberReceivedPacketManager::IsAckFrameEmpty( PacketNumberSpace packet_number_space) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].IsAckFrameEmpty(); } return received_packet_managers_[packet_number_space].IsAckFrameEmpty(); } size_t UberReceivedPacketManager::min_received_before_ack_decimation() const { return received_packet_managers_[0].min_received_before_ack_decimation(); } void UberReceivedPacketManager::set_min_received_before_ack_decimation( size_t new_value) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_min_received_before_ack_decimation(new_value); } } void UberReceivedPacketManager::set_ack_frequency(size_t new_value) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_ack_frequency(new_value); } } const QuicAckFrame& UberReceivedPacketManager::ack_frame() const { QUICHE_DCHECK(!supports_multiple_packet_number_spaces_); return received_packet_managers_[0].ack_frame(); } const QuicAckFrame& UberReceivedPacketManager::GetAckFrame( PacketNumberSpace packet_number_space) const { QUICHE_DCHECK(supports_multiple_packet_number_spaces_); return received_packet_managers_[packet_number_space].ack_frame(); } void UberReceivedPacketManager::set_max_ack_ranges(size_t max_ack_ranges) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_max_ack_ranges(max_ack_ranges); } } void UberReceivedPacketManager::set_save_timestamps(bool save_timestamps) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_save_timestamps( save_timestamps, supports_multiple_packet_number_spaces_); } } void UberReceivedPacketManager::OnAckFrequencyFrame( const QuicAckFrequencyFrame& frame) { if (!supports_multiple_packet_number_spaces_) { QUIC_BUG(quic_bug_10495_3) << "Received AckFrequencyFrame when multiple packet number spaces " "is not supported"; return; } received_packet_managers_[APPLICATION_DATA].OnAckFrequencyFrame(frame); } }
#include "quiche/quic/core/uber_received_packet_manager.h" #include <algorithm> #include <memory> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class UberReceivedPacketManagerPeer { public: static void SetAckDecimationDelay(UberReceivedPacketManager* manager, float ack_decimation_delay) { for (auto& received_packet_manager : manager->received_packet_managers_) { received_packet_manager.ack_decimation_delay_ = ack_decimation_delay; } } }; namespace { const bool kInstigateAck = true; const QuicTime::Delta kMinRttMs = QuicTime::Delta::FromMilliseconds(40); const QuicTime::Delta kDelayedAckTime = QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); EncryptionLevel GetEncryptionLevel(PacketNumberSpace packet_number_space) { switch (packet_number_space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return ENCRYPTION_FORWARD_SECURE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } class UberReceivedPacketManagerTest : public QuicTest { protected: UberReceivedPacketManagerTest() { manager_ = std::make_unique<UberReceivedPacketManager>(&stats_); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); rtt_stats_.UpdateRtt(kMinRttMs, QuicTime::Delta::Zero(), QuicTime::Zero()); manager_->set_save_timestamps(true); } void RecordPacketReceipt(uint64_t packet_number) { RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, packet_number); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time) { RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, packet_number, receipt_time); } void RecordPacketReceipt(EncryptionLevel decrypted_packet_level, uint64_t packet_number) { RecordPacketReceipt(decrypted_packet_level, packet_number, QuicTime::Zero()); } void RecordPacketReceipt(EncryptionLevel decrypted_packet_level, uint64_t packet_number, QuicTime receipt_time) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(packet_number); manager_->RecordPacketReceived(decrypted_packet_level, header, receipt_time, ECN_NOT_ECT); } bool HasPendingAck() { if (!manager_->supports_multiple_packet_number_spaces()) { return manager_->GetAckTimeout(APPLICATION_DATA).IsInitialized(); } return manager_->GetEarliestAckTimeout().IsInitialized(); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, uint64_t last_received_packet_number) { MaybeUpdateAckTimeout(should_last_packet_instigate_acks, ENCRYPTION_FORWARD_SECURE, last_received_packet_number); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, EncryptionLevel decrypted_packet_level, uint64_t last_received_packet_number) { manager_->MaybeUpdateAckTimeout( should_last_packet_instigate_acks, decrypted_packet_level, QuicPacketNumber(last_received_packet_number), clock_.ApproximateNow(), clock_.ApproximateNow(), &rtt_stats_); } void CheckAckTimeout(QuicTime time) { QUICHE_DCHECK(HasPendingAck()); if (!manager_->supports_multiple_packet_number_spaces()) { QUICHE_DCHECK(manager_->GetAckTimeout(APPLICATION_DATA) == time); if (time <= clock_.ApproximateNow()) { manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); QUICHE_DCHECK(!HasPendingAck()); } return; } QUICHE_DCHECK(manager_->GetEarliestAckTimeout() == time); for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicTime ack_timeout = manager_->GetAckTimeout(static_cast<PacketNumberSpace>(i)); if (!ack_timeout.IsInitialized() || ack_timeout > clock_.ApproximateNow()) { continue; } manager_->ResetAckStates( GetEncryptionLevel(static_cast<PacketNumberSpace>(i))); } } MockClock clock_; RttStats rtt_stats_; QuicConnectionStats stats_; std::unique_ptr<UberReceivedPacketManager> manager_; }; TEST_F(UberReceivedPacketManagerTest, DontWaitForPacketsBefore) { EXPECT_TRUE(manager_->IsAckFrameEmpty(APPLICATION_DATA)); RecordPacketReceipt(2); EXPECT_FALSE(manager_->IsAckFrameEmpty(APPLICATION_DATA)); RecordPacketReceipt(7); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3u))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(6u))); manager_->DontWaitForPacketsBefore(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4)); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3u))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(6u))); } TEST_F(UberReceivedPacketManagerTest, GetUpdatedAckFrame) { QuicTime two_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(2, two_ms); EXPECT_TRUE(manager_->IsAckFrameUpdated()); QuicFrame ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, QuicTime::Zero()); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(QuicTime::Delta::Zero(), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); QuicTime four_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(4); ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, four_ms); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); RecordPacketReceipt(999, two_ms); RecordPacketReceipt(4, two_ms); RecordPacketReceipt(1000, two_ms); EXPECT_TRUE(manager_->IsAckFrameUpdated()); ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, two_ms); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(2u, ack.ack_frame->received_packet_times.size()); } TEST_F(UberReceivedPacketManagerTest, UpdateReceivedConnectionStats) { EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(1); EXPECT_TRUE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(6); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(4u, stats_.max_sequence_reordering); EXPECT_EQ(1000, stats_.max_time_reordering_us); EXPECT_EQ(1u, stats_.packets_reordered); } TEST_F(UberReceivedPacketManagerTest, LimitAckRanges) { manager_->set_max_ack_ranges(10); EXPECT_FALSE(manager_->IsAckFrameUpdated()); for (int i = 0; i < 100; ++i) { RecordPacketReceipt(1 + 2 * i); EXPECT_TRUE(manager_->IsAckFrameUpdated()); manager_->GetUpdatedAckFrame(APPLICATION_DATA, QuicTime::Zero()); EXPECT_GE(10u, manager_->ack_frame().packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(1u + 2 * i), manager_->ack_frame().packets.Max()); for (int j = 0; j < std::min(10, i + 1); ++j) { ASSERT_GE(i, j); EXPECT_TRUE(manager_->ack_frame().packets.Contains( QuicPacketNumber(1 + (i - j) * 2))); if (i > j) { EXPECT_FALSE(manager_->ack_frame().packets.Contains( QuicPacketNumber((i - j) * 2))); } } } } TEST_F(UberReceivedPacketManagerTest, IgnoreOutOfOrderTimestamps) { EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(manager_->IsAckFrameUpdated()); EXPECT_EQ(1u, manager_->ack_frame().received_packet_times.size()); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, manager_->ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_EQ(2u, manager_->ack_frame().received_packet_times.size()); } TEST_F(UberReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(UberReceivedPacketManagerTest, OutOfOrderAckReceiptCausesNoAck) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckReceiptCausesAckSend) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); clock_.AdvanceTime(kDelayedAckTime); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 4); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 5); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckSentEveryNthPacket) { EXPECT_FALSE(HasPendingAck()); manager_->set_ack_frequency(3); for (size_t i = 1; i <= 39; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(UberReceivedPacketManagerTest, AckDecimationReducesAcks) { EXPECT_FALSE(HasPendingAck()); manager_->set_min_received_before_ack_decimation(10); for (size_t i = 1; i <= 29; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i <= 10) { if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } continue; } if (i == 20) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kMinRttMs * 0.25); } } RecordPacketReceipt(30, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 30); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimation) { EXPECT_FALSE(HasPendingAck()); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimationUnlimitedAggregation) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kAKDU); config.SetConnectionOptionsToSend(connection_options); manager_->SetFromConfig(config, Perspective::IS_CLIENT); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (int i = 1; i <= 18; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(ack_time); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimationEighthRtt) { EXPECT_FALSE(HasPendingAck()); UberReceivedPacketManagerPeer::SetAckDecimationDelay(manager_.get(), 0.125); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.125; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, DontWaitForPacketsBeforeMultiplePacketNumberSpaces) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_CLIENT); EXPECT_FALSE( manager_->GetLargestObserved(ENCRYPTION_HANDSHAKE).IsInitialized()); EXPECT_FALSE( manager_->GetLargestObserved(ENCRYPTION_FORWARD_SECURE).IsInitialized()); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 2); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 4); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 3); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 7); EXPECT_EQ(QuicPacketNumber(4), manager_->GetLargestObserved(ENCRYPTION_HANDSHAKE)); EXPECT_EQ(QuicPacketNumber(7), manager_->GetLargestObserved(ENCRYPTION_FORWARD_SECURE)); EXPECT_TRUE( manager_->IsAwaitingPacket(ENCRYPTION_HANDSHAKE, QuicPacketNumber(3))); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4))); manager_->DontWaitForPacketsBefore(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(5)); EXPECT_TRUE( manager_->IsAwaitingPacket(ENCRYPTION_HANDSHAKE, QuicPacketNumber(3))); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4))); } TEST_F(UberReceivedPacketManagerTest, AckSendingDifferentPacketNumberSpaces) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_SERVER); EXPECT_FALSE(HasPendingAck()); EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(ENCRYPTION_INITIAL, 3); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_INITIAL, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(25)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(25)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_INITIAL, 4); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_INITIAL, 4); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 3); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_HANDSHAKE, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 3); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 2); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, 2); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckTimeoutForPreviouslyUndecryptablePackets) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_SERVER); EXPECT_FALSE(HasPendingAck()); EXPECT_FALSE(manager_->IsAckFrameUpdated()); const QuicTime packet_receipt_time4 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 5); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_HANDSHAKE, 5); EXPECT_TRUE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 4); manager_->MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4), packet_receipt_time4, clock_.ApproximateNow(), &rtt_stats_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() - QuicTime::Delta::FromMilliseconds(11) + kDelayedAckTime); } } } }
264
cpp
google/quiche
quic_linux_socket_utils
quiche/quic/core/quic_linux_socket_utils.cc
quiche/quic/core/quic_linux_socket_utils_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_LINUX_SOCKET_UTILS_H_ #define QUICHE_QUIC_CORE_QUIC_LINUX_SOCKET_UTILS_H_ #include <errno.h> #include <stddef.h> #include <string.h> #include <sys/socket.h> #include <sys/uio.h> #include <deque> #include <functional> #include <iterator> #include <memory> #include <type_traits> #include <utility> #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_callbacks.h" #ifndef SOL_UDP #define SOL_UDP 17 #endif #ifndef UDP_SEGMENT #define UDP_SEGMENT 103 #endif #ifndef UDP_MAX_SEGMENTS #define UDP_MAX_SEGMENTS (1 << 6UL) #endif #ifndef SO_TXTIME #define SO_TXTIME 61 #endif namespace quic { inline constexpr int kCmsgSpaceForIpv4 = CMSG_SPACE(sizeof(in_pktinfo)); inline constexpr int kCmsgSpaceForIpv6 = CMSG_SPACE(sizeof(in6_pktinfo)); inline constexpr int kCmsgSpaceForIp = (kCmsgSpaceForIpv4 < kCmsgSpaceForIpv6) ? kCmsgSpaceForIpv6 : kCmsgSpaceForIpv4; inline constexpr int kCmsgSpaceForSegmentSize = CMSG_SPACE(sizeof(uint16_t)); inline constexpr int kCmsgSpaceForTxTime = CMSG_SPACE(sizeof(uint64_t)); inline constexpr int kCmsgSpaceForTTL = CMSG_SPACE(sizeof(int)); inline constexpr int kCmsgSpaceForTOS = CMSG_SPACE(sizeof(int)); class QUICHE_EXPORT QuicMsgHdr { public: QuicMsgHdr(iovec* iov, size_t iov_len, char* cbuf, size_t cbuf_size); void SetPeerAddress(const QuicSocketAddress& peer_address); void SetIpInNextCmsg(const QuicIpAddress& self_address); template <typename DataType> DataType* GetNextCmsgData(int cmsg_level, int cmsg_type) { return reinterpret_cast<DataType*>( GetNextCmsgDataInternal(cmsg_level, cmsg_type, sizeof(DataType))); } const msghdr* hdr() const { return &hdr_; } protected: void* GetNextCmsgDataInternal(int cmsg_level, int cmsg_type, size_t data_size); msghdr hdr_; sockaddr_storage raw_peer_address_; char* cbuf_; const size_t cbuf_size_; cmsghdr* cmsg_; }; struct QUICHE_EXPORT BufferedWrite { BufferedWrite(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address) : BufferedWrite(buffer, buf_len, self_address, peer_address, std::unique_ptr<PerPacketOptions>(), QuicPacketWriterParams(), 0) {} BufferedWrite(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, std::unique_ptr<PerPacketOptions> options, const QuicPacketWriterParams& params, uint64_t release_time) : buffer(buffer), buf_len(buf_len), self_address(self_address), peer_address(peer_address), options(std::move(options)), params(params), release_time(release_time) {} const char* buffer; size_t buf_len; QuicIpAddress self_address; QuicSocketAddress peer_address; std::unique_ptr<PerPacketOptions> options; QuicPacketWriterParams params; uint64_t release_time; }; class QUICHE_EXPORT QuicMMsgHdr { public: using ControlBufferInitializer = quiche::UnretainedCallback<void( QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write)>; template <typename IteratorT> QuicMMsgHdr( const IteratorT& first, const IteratorT& last, size_t cbuf_size, ControlBufferInitializer cbuf_initializer = +[](quic::QuicMMsgHdr*, int, const quic::BufferedWrite&) {}) : num_msgs_(std::distance(first, last)), cbuf_size_(cbuf_size) { static_assert( std::is_same<typename std::iterator_traits<IteratorT>::value_type, BufferedWrite>::value, "Must iterate over a collection of BufferedWrite."); QUICHE_DCHECK_LE(0, num_msgs_); if (num_msgs_ == 0) { return; } storage_.reset(new char[StorageSize()]); memset(&storage_[0], 0, StorageSize()); int i = -1; for (auto it = first; it != last; ++it) { ++i; InitOneHeader(i, *it); cbuf_initializer(this, i, *it); } } void SetIpInNextCmsg(int i, const QuicIpAddress& self_address); template <typename DataType> DataType* GetNextCmsgData(int i, int cmsg_level, int cmsg_type) { return reinterpret_cast<DataType*>( GetNextCmsgDataInternal(i, cmsg_level, cmsg_type, sizeof(DataType))); } mmsghdr* mhdr() { return GetMMsgHdr(0); } int num_msgs() const { return num_msgs_; } int num_bytes_sent(int num_packets_sent); protected: void InitOneHeader(int i, const BufferedWrite& buffered_write); void* GetNextCmsgDataInternal(int i, int cmsg_level, int cmsg_type, size_t data_size); size_t StorageSize() const { return num_msgs_ * (sizeof(mmsghdr) + sizeof(iovec) + sizeof(sockaddr_storage) + sizeof(cmsghdr*) + cbuf_size_); } mmsghdr* GetMMsgHdr(int i) { auto* first = reinterpret_cast<mmsghdr*>(&storage_[0]); return &first[i]; } iovec* GetIov(int i) { auto* first = reinterpret_cast<iovec*>(GetMMsgHdr(num_msgs_)); return &first[i]; } sockaddr_storage* GetPeerAddressStorage(int i) { auto* first = reinterpret_cast<sockaddr_storage*>(GetIov(num_msgs_)); return &first[i]; } cmsghdr** GetCmsgHdr(int i) { auto* first = reinterpret_cast<cmsghdr**>(GetPeerAddressStorage(num_msgs_)); return &first[i]; } char* GetCbuf(int i) { auto* first = reinterpret_cast<char*>(GetCmsgHdr(num_msgs_)); return &first[i * cbuf_size_]; } const int num_msgs_; const size_t cbuf_size_; std::unique_ptr<char[]> storage_; }; class QUICHE_EXPORT QuicLinuxSocketUtils { public: static int GetUDPSegmentSize(int fd); static bool EnableReleaseTime(int fd, clockid_t clockid); static bool GetTtlFromMsghdr(struct msghdr* hdr, int* ttl); static void SetIpInfoInCmsgData(const QuicIpAddress& self_address, void* cmsg_data); static size_t SetIpInfoInCmsg(const QuicIpAddress& self_address, cmsghdr* cmsg); static WriteResult WritePacket(int fd, const QuicMsgHdr& hdr); static WriteResult WriteMultiplePackets(int fd, QuicMMsgHdr* mhdr, int* num_packets_sent); }; } #endif #include "quiche/quic/core/quic_linux_socket_utils.h" #include <linux/net_tstamp.h> #include <netinet/in.h> #include <cstddef> #include <cstdint> #include <string> #include "quiche/quic/core/quic_syscall_wrapper.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QuicMsgHdr::QuicMsgHdr(iovec* iov, size_t iov_len, char* cbuf, size_t cbuf_size) : cbuf_(cbuf), cbuf_size_(cbuf_size), cmsg_(nullptr) { hdr_.msg_name = nullptr; hdr_.msg_namelen = 0; hdr_.msg_iov = iov; hdr_.msg_iovlen = iov_len; hdr_.msg_flags = 0; hdr_.msg_control = nullptr; hdr_.msg_controllen = 0; } void QuicMsgHdr::SetPeerAddress(const QuicSocketAddress& peer_address) { QUICHE_DCHECK(peer_address.IsInitialized()); raw_peer_address_ = peer_address.generic_address(); hdr_.msg_name = &raw_peer_address_; hdr_.msg_namelen = raw_peer_address_.ss_family == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6); } void QuicMsgHdr::SetIpInNextCmsg(const QuicIpAddress& self_address) { if (!self_address.IsInitialized()) { return; } if (self_address.IsIPv4()) { QuicLinuxSocketUtils::SetIpInfoInCmsgData( self_address, GetNextCmsgData<in_pktinfo>(IPPROTO_IP, IP_PKTINFO)); } else { QuicLinuxSocketUtils::SetIpInfoInCmsgData( self_address, GetNextCmsgData<in6_pktinfo>(IPPROTO_IPV6, IPV6_PKTINFO)); } } void* QuicMsgHdr::GetNextCmsgDataInternal(int cmsg_level, int cmsg_type, size_t data_size) { hdr_.msg_controllen += CMSG_SPACE(data_size); QUICHE_DCHECK_LE(hdr_.msg_controllen, cbuf_size_); if (cmsg_ == nullptr) { QUICHE_DCHECK_EQ(nullptr, hdr_.msg_control); memset(cbuf_, 0, cbuf_size_); hdr_.msg_control = cbuf_; cmsg_ = CMSG_FIRSTHDR(&hdr_); } else { QUICHE_DCHECK_NE(nullptr, hdr_.msg_control); cmsg_ = CMSG_NXTHDR(&hdr_, cmsg_); } QUICHE_DCHECK_NE(nullptr, cmsg_) << "Insufficient control buffer space"; cmsg_->cmsg_len = CMSG_LEN(data_size); cmsg_->cmsg_level = cmsg_level; cmsg_->cmsg_type = cmsg_type; return CMSG_DATA(cmsg_); } void QuicMMsgHdr::InitOneHeader(int i, const BufferedWrite& buffered_write) { mmsghdr* mhdr = GetMMsgHdr(i); msghdr* hdr = &mhdr->msg_hdr; iovec* iov = GetIov(i); iov->iov_base = const_cast<char*>(buffered_write.buffer); iov->iov_len = buffered_write.buf_len; hdr->msg_iov = iov; hdr->msg_iovlen = 1; hdr->msg_control = nullptr; hdr->msg_controllen = 0; QUICHE_DCHECK(buffered_write.peer_address.IsInitialized()); sockaddr_storage* peer_address_storage = GetPeerAddressStorage(i); *peer_address_storage = buffered_write.peer_address.generic_address(); hdr->msg_name = peer_address_storage; hdr->msg_namelen = peer_address_storage->ss_family == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6); } void QuicMMsgHdr::SetIpInNextCmsg(int i, const QuicIpAddress& self_address) { if (!self_address.IsInitialized()) { return; } if (self_address.IsIPv4()) { QuicLinuxSocketUtils::SetIpInfoInCmsgData( self_address, GetNextCmsgData<in_pktinfo>(i, IPPROTO_IP, IP_PKTINFO)); } else { QuicLinuxSocketUtils::SetIpInfoInCmsgData( self_address, GetNextCmsgData<in6_pktinfo>(i, IPPROTO_IPV6, IPV6_PKTINFO)); } } void* QuicMMsgHdr::GetNextCmsgDataInternal(int i, int cmsg_level, int cmsg_type, size_t data_size) { mmsghdr* mhdr = GetMMsgHdr(i); msghdr* hdr = &mhdr->msg_hdr; cmsghdr*& cmsg = *GetCmsgHdr(i); hdr->msg_controllen += CMSG_SPACE(data_size); QUICHE_DCHECK_LE(hdr->msg_controllen, cbuf_size_); if (cmsg == nullptr) { QUICHE_DCHECK_EQ(nullptr, hdr->msg_control); hdr->msg_control = GetCbuf(i); cmsg = CMSG_FIRSTHDR(hdr); } else { QUICHE_DCHECK_NE(nullptr, hdr->msg_control); cmsg = CMSG_NXTHDR(hdr, cmsg); } QUICHE_DCHECK_NE(nullptr, cmsg) << "Insufficient control buffer space"; cmsg->cmsg_len = CMSG_LEN(data_size); cmsg->cmsg_level = cmsg_level; cmsg->cmsg_type = cmsg_type; return CMSG_DATA(cmsg); } int QuicMMsgHdr::num_bytes_sent(int num_packets_sent) { QUICHE_DCHECK_LE(0, num_packets_sent); QUICHE_DCHECK_LE(num_packets_sent, num_msgs_); int bytes_sent = 0; iovec* iov = GetIov(0); for (int i = 0; i < num_packets_sent; ++i) { bytes_sent += iov[i].iov_len; } return bytes_sent; } int QuicLinuxSocketUtils::GetUDPSegmentSize(int fd) { int optval; socklen_t optlen = sizeof(optval); int rc = getsockopt(fd, SOL_UDP, UDP_SEGMENT, &optval, &optlen); if (rc < 0) { QUIC_LOG_EVERY_N_SEC(INFO, 10) << "getsockopt(UDP_SEGMENT) failed: " << strerror(errno); return -1; } QUIC_LOG_EVERY_N_SEC(INFO, 10) << "getsockopt(UDP_SEGMENT) returned segment size: " << optval; return optval; } bool QuicLinuxSocketUtils::EnableReleaseTime(int fd, clockid_t clockid) { struct LinuxSockTxTime { clockid_t clockid; uint32_t flags; }; LinuxSockTxTime so_txtime_val{clockid, 0}; if (setsockopt(fd, SOL_SOCKET, SO_TXTIME, &so_txtime_val, sizeof(so_txtime_val)) != 0) { QUIC_LOG_EVERY_N_SEC(INFO, 10) << "setsockopt(SOL_SOCKET,SO_TXTIME) failed: " << strerror(errno); return false; } return true; } bool QuicLinuxSocketUtils::GetTtlFromMsghdr(struct msghdr* hdr, int* ttl) { if (hdr->msg_controllen > 0) { struct cmsghdr* cmsg; for (cmsg = CMSG_FIRSTHDR(hdr); cmsg != nullptr; cmsg = CMSG_NXTHDR(hdr, cmsg)) { if ((cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_TTL) || (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_HOPLIMIT)) { *ttl = *(reinterpret_cast<int*>(CMSG_DATA(cmsg))); return true; } } } return false; } void QuicLinuxSocketUtils::SetIpInfoInCmsgData( const QuicIpAddress& self_address, void* cmsg_data) { QUICHE_DCHECK(self_address.IsInitialized()); const std::string& address_str = self_address.ToPackedString(); if (self_address.IsIPv4()) { in_pktinfo* pktinfo = static_cast<in_pktinfo*>(cmsg_data); pktinfo->ipi_ifindex = 0; memcpy(&pktinfo->ipi_spec_dst, address_str.c_str(), address_str.length()); } else if (self_address.IsIPv6()) { in6_pktinfo* pktinfo = static_cast<in6_pktinfo*>(cmsg_data); memcpy(&pktinfo->ipi6_addr, address_str.c_str(), address_str.length()); } else { QUIC_BUG(quic_bug_10598_1) << "Unrecognized IPAddress"; } } size_t QuicLinuxSocketUtils::SetIpInfoInCmsg(const QuicIpAddress& self_address, cmsghdr* cmsg) { std::string address_string; if (self_address.IsIPv4()) { cmsg->cmsg_len = CMSG_LEN(sizeof(in_pktinfo)); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(in_pktinfo)); pktinfo->ipi_ifindex = 0; address_string = self_address.ToPackedString(); memcpy(&pktinfo->ipi_spec_dst, address_string.c_str(), address_string.length()); return sizeof(in_pktinfo); } else if (self_address.IsIPv6()) { cmsg->cmsg_len = CMSG_LEN(sizeof(in6_pktinfo)); cmsg->cmsg_level = IPPROTO_IPV6; cmsg->cmsg_type = IPV6_PKTINFO; in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg)); memset(pktinfo, 0, sizeof(in6_pktinfo)); address_string = self_address.ToPackedString(); memcpy(&pktinfo->ipi6_addr, address_string.c_str(), address_string.length()); return sizeof(in6_pktinfo); } else { QUIC_BUG(quic_bug_10598_2) << "Unrecognized IPAddress"; return 0; } } WriteResult QuicLinuxSocketUtils::WritePacket(int fd, const QuicMsgHdr& hdr) { int rc; do { rc = GetGlobalSyscallWrapper()->Sendmsg(fd, hdr.hdr(), 0); } while (rc < 0 && errno == EINTR); if (rc >= 0) { return WriteResult(WRITE_STATUS_OK, rc); } return WriteResult((errno == EAGAIN || errno == EWOULDBLOCK) ? WRITE_STATUS_BLOCKED : WRITE_STATUS_ERROR, errno); } WriteResult QuicLinuxSocketUtils::WriteMultiplePackets(int fd, QuicMMsgHdr* mhdr, int* num_packets_sent) { *num_packets_sent = 0; if (mhdr->num_msgs() <= 0) { return WriteResult(WRITE_STATUS_ERROR, EINVAL); } int rc; do { rc = GetGlobalSyscallWrapper()->Sendmmsg(fd, mhdr->mhdr(), mhdr->num_msgs(), 0); } while (rc < 0 && errno == EINTR); if (rc > 0) { *num_packets_sent = rc; return WriteResult(WRITE_STATUS_OK, mhdr->num_bytes_sent(rc)); } else if (rc == 0) { QUIC_BUG(quic_bug_10598_3) << "sendmmsg returned 0, returning WRITE_STATUS_ERROR. errno: " << errno; errno = EIO; } return WriteResult((errno == EAGAIN || errno == EWOULDBLOCK) ? WRITE_STATUS_BLOCKED : WRITE_STATUS_ERROR, errno); } }
#include "quiche/quic/core/quic_linux_socket_utils.h" #include <netinet/in.h> #include <stdint.h> #include <cstddef> #include <sstream> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_mock_syscall_wrapper.h" #include "quiche/common/quiche_circular_deque.h" using testing::_; using testing::InSequence; using testing::Invoke; namespace quic { namespace test { namespace { class QuicLinuxSocketUtilsTest : public QuicTest { protected: WriteResult TestWriteMultiplePackets( int fd, const quiche::QuicheCircularDeque<BufferedWrite>::const_iterator& first, const quiche::QuicheCircularDeque<BufferedWrite>::const_iterator& last, int* num_packets_sent) { QuicMMsgHdr mhdr( first, last, kCmsgSpaceForIp, [](QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write) { mhdr->SetIpInNextCmsg(i, buffered_write.self_address); }); WriteResult res = QuicLinuxSocketUtils::WriteMultiplePackets(fd, &mhdr, num_packets_sent); return res; } MockQuicSyscallWrapper mock_syscalls_; ScopedGlobalSyscallWrapperOverride syscall_override_{&mock_syscalls_}; }; void CheckIpAndTtlInCbuf(msghdr* hdr, const void* cbuf, const QuicIpAddress& self_addr, int ttl) { const bool is_ipv4 = self_addr.IsIPv4(); const size_t ip_cmsg_space = is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6; EXPECT_EQ(cbuf, hdr->msg_control); EXPECT_EQ(ip_cmsg_space + CMSG_SPACE(sizeof(uint16_t)), hdr->msg_controllen); cmsghdr* cmsg = CMSG_FIRSTHDR(hdr); EXPECT_EQ(cmsg->cmsg_len, is_ipv4 ? CMSG_LEN(sizeof(in_pktinfo)) : CMSG_LEN(sizeof(in6_pktinfo))); EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6); EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_PKTINFO : IPV6_PKTINFO); const std::string& self_addr_str = self_addr.ToPackedString(); if (is_ipv4) { in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg)); EXPECT_EQ(0, memcmp(&pktinfo->ipi_spec_dst, self_addr_str.c_str(), self_addr_str.length())); } else { in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg)); EXPECT_EQ(0, memcmp(&pktinfo->ipi6_addr, self_addr_str.c_str(), self_addr_str.length())); } cmsg = CMSG_NXTHDR(hdr, cmsg); EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(int))); EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6); EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_TTL : IPV6_HOPLIMIT); EXPECT_EQ(ttl, *reinterpret_cast<int*>(CMSG_DATA(cmsg))); EXPECT_EQ(nullptr, CMSG_NXTHDR(hdr, cmsg)); } void CheckMsghdrWithoutCbuf(const msghdr* hdr, const void* buffer, size_t buf_len, const QuicSocketAddress& peer_addr) { EXPECT_EQ( peer_addr.host().IsIPv4() ? sizeof(sockaddr_in) : sizeof(sockaddr_in6), hdr->msg_namelen); sockaddr_storage peer_generic_addr = peer_addr.generic_address(); EXPECT_EQ(0, memcmp(hdr->msg_name, &peer_generic_addr, hdr->msg_namelen)); EXPECT_EQ(1u, hdr->msg_iovlen); EXPECT_EQ(buffer, hdr->msg_iov->iov_base); EXPECT_EQ(buf_len, hdr->msg_iov->iov_len); EXPECT_EQ(0, hdr->msg_flags); EXPECT_EQ(nullptr, hdr->msg_control); EXPECT_EQ(0u, hdr->msg_controllen); } void CheckIpAndGsoSizeInCbuf(msghdr* hdr, const void* cbuf, const QuicIpAddress& self_addr, uint16_t gso_size) { const bool is_ipv4 = self_addr.IsIPv4(); const size_t ip_cmsg_space = is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6; EXPECT_EQ(cbuf, hdr->msg_control); EXPECT_EQ(ip_cmsg_space + CMSG_SPACE(sizeof(uint16_t)), hdr->msg_controllen); cmsghdr* cmsg = CMSG_FIRSTHDR(hdr); EXPECT_EQ(cmsg->cmsg_len, is_ipv4 ? CMSG_LEN(sizeof(in_pktinfo)) : CMSG_LEN(sizeof(in6_pktinfo))); EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6); EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_PKTINFO : IPV6_PKTINFO); const std::string& self_addr_str = self_addr.ToPackedString(); if (is_ipv4) { in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg)); EXPECT_EQ(0, memcmp(&pktinfo->ipi_spec_dst, self_addr_str.c_str(), self_addr_str.length())); } else { in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg)); EXPECT_EQ(0, memcmp(&pktinfo->ipi6_addr, self_addr_str.c_str(), self_addr_str.length())); } cmsg = CMSG_NXTHDR(hdr, cmsg); EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(uint16_t))); EXPECT_EQ(cmsg->cmsg_level, SOL_UDP); EXPECT_EQ(cmsg->cmsg_type, UDP_SEGMENT); EXPECT_EQ(gso_size, *reinterpret_cast<uint16_t*>(CMSG_DATA(cmsg))); EXPECT_EQ(nullptr, CMSG_NXTHDR(hdr, cmsg)); } TEST_F(QuicLinuxSocketUtilsTest, QuicMsgHdr) { QuicSocketAddress peer_addr(QuicIpAddress::Loopback4(), 1234); char packet_buf[1024]; iovec iov{packet_buf, sizeof(packet_buf)}; { QuicMsgHdr quic_hdr(&iov, 1, nullptr, 0); quic_hdr.SetPeerAddress(peer_addr); CheckMsghdrWithoutCbuf(quic_hdr.hdr(), packet_buf, sizeof(packet_buf), peer_addr); } for (bool is_ipv4 : {true, false}) { QuicIpAddress self_addr = is_ipv4 ? QuicIpAddress::Loopback4() : QuicIpAddress::Loopback6(); alignas(cmsghdr) char cbuf[kCmsgSpaceForIp + kCmsgSpaceForTTL]; QuicMsgHdr quic_hdr(&iov, 1, cbuf, sizeof(cbuf)); quic_hdr.SetPeerAddress(peer_addr); msghdr* hdr = const_cast<msghdr*>(quic_hdr.hdr()); EXPECT_EQ(nullptr, hdr->msg_control); EXPECT_EQ(0u, hdr->msg_controllen); quic_hdr.SetIpInNextCmsg(self_addr); EXPECT_EQ(cbuf, hdr->msg_control); const size_t ip_cmsg_space = is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6; EXPECT_EQ(ip_cmsg_space, hdr->msg_controllen); if (is_ipv4) { *quic_hdr.GetNextCmsgData<int>(IPPROTO_IP, IP_TTL) = 32; } else { *quic_hdr.GetNextCmsgData<int>(IPPROTO_IPV6, IPV6_HOPLIMIT) = 32; } CheckIpAndTtlInCbuf(hdr, cbuf, self_addr, 32); } } TEST_F(QuicLinuxSocketUtilsTest, QuicMMsgHdr) { quiche::QuicheCircularDeque<BufferedWrite> buffered_writes; char packet_buf1[1024]; char packet_buf2[512]; buffered_writes.emplace_back( packet_buf1, sizeof(packet_buf1), QuicIpAddress::Loopback4(), QuicSocketAddress(QuicIpAddress::Loopback4(), 4)); buffered_writes.emplace_back( packet_buf2, sizeof(packet_buf2), QuicIpAddress::Loopback6(), QuicSocketAddress(QuicIpAddress::Loopback6(), 6)); QuicMMsgHdr quic_mhdr_without_cbuf(buffered_writes.begin(), buffered_writes.end(), 0); for (size_t i = 0; i < buffered_writes.size(); ++i) { const BufferedWrite& bw = buffered_writes[i]; CheckMsghdrWithoutCbuf(&quic_mhdr_without_cbuf.mhdr()[i].msg_hdr, bw.buffer, bw.buf_len, bw.peer_address); } QuicMMsgHdr quic_mhdr_with_cbuf( buffered_writes.begin(), buffered_writes.end(), kCmsgSpaceForIp + kCmsgSpaceForSegmentSize, [](QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write) { mhdr->SetIpInNextCmsg(i, buffered_write.self_address); *mhdr->GetNextCmsgData<uint16_t>(i, SOL_UDP, UDP_SEGMENT) = 1300; }); for (size_t i = 0; i < buffered_writes.size(); ++i) { const BufferedWrite& bw = buffered_writes[i]; msghdr* hdr = &quic_mhdr_with_cbuf.mhdr()[i].msg_hdr; CheckIpAndGsoSizeInCbuf(hdr, hdr->msg_control, bw.self_address, 1300); } } TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_NoPacketsToSend) { int num_packets_sent; quiche::QuicheCircularDeque<BufferedWrite> buffered_writes; EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _)).Times(0); EXPECT_EQ(WriteResult(WRITE_STATUS_ERROR, EINVAL), TestWriteMultiplePackets(1, buffered_writes.begin(), buffered_writes.end(), &num_packets_sent)); } TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteBlocked) { int num_packets_sent; quiche::QuicheCircularDeque<BufferedWrite> buffered_writes; buffered_writes.emplace_back(nullptr, 0, QuicIpAddress(), QuicSocketAddress(QuicIpAddress::Any4(), 0)); EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _)) .WillOnce(Invoke([](int , mmsghdr* , unsigned int , int ) { errno = EWOULDBLOCK; return -1; })); EXPECT_EQ(WriteResult(WRITE_STATUS_BLOCKED, EWOULDBLOCK), TestWriteMultiplePackets(1, buffered_writes.begin(), buffered_writes.end(), &num_packets_sent)); EXPECT_EQ(0, num_packets_sent); } TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteError) { int num_packets_sent; quiche::QuicheCircularDeque<BufferedWrite> buffered_writes; buffered_writes.emplace_back(nullptr, 0, QuicIpAddress(), QuicSocketAddress(QuicIpAddress::Any4(), 0)); EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _)) .WillOnce(Invoke([](int , mmsghdr* , unsigned int , int ) { errno = EPERM; return -1; })); EXPECT_EQ(WriteResult(WRITE_STATUS_ERROR, EPERM), TestWriteMultiplePackets(1, buffered_writes.begin(), buffered_writes.end(), &num_packets_sent)); EXPECT_EQ(0, num_packets_sent); } TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteSuccess) { int num_packets_sent; quiche::QuicheCircularDeque<BufferedWrite> buffered_writes; const int kNumBufferedWrites = 10; static_assert(kNumBufferedWrites < 256, "Must be less than 256"); std::vector<std::string> buffer_holder; for (int i = 0; i < kNumBufferedWrites; ++i) { size_t buf_len = (i + 1) * 2; std::ostringstream buffer_ostream; while (buffer_ostream.str().length() < buf_len) { buffer_ostream << i; } buffer_holder.push_back(buffer_ostream.str().substr(0, buf_len - 1) + '$'); buffered_writes.emplace_back(buffer_holder.back().data(), buf_len, QuicIpAddress(), QuicSocketAddress(QuicIpAddress::Any4(), 0)); if (i != 0) { ASSERT_TRUE(buffered_writes.back().self_address.FromString("127.0.0.1")); } std::ostringstream peer_ip_ostream; QuicIpAddress peer_ip_address; peer_ip_ostream << "127.0.1." << i + 1; ASSERT_TRUE(peer_ip_address.FromString(peer_ip_ostream.str())); buffered_writes.back().peer_address = QuicSocketAddress(peer_ip_address, i + 1); } InSequence s; for (int expected_num_packets_sent : {1, 2, 3, 10}) { SCOPED_TRACE(testing::Message() << "expected_num_packets_sent=" << expected_num_packets_sent); EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _)) .WillOnce(Invoke([&](int , mmsghdr* msgvec, unsigned int vlen, int ) { EXPECT_LE(static_cast<unsigned int>(expected_num_packets_sent), vlen); for (unsigned int i = 0; i < vlen; ++i) { const BufferedWrite& buffered_write = buffered_writes[i]; const msghdr& hdr = msgvec[i].msg_hdr; EXPECT_EQ(1u, hdr.msg_iovlen); EXPECT_EQ(buffered_write.buffer, hdr.msg_iov->iov_base); EXPECT_EQ(buffered_write.buf_len, hdr.msg_iov->iov_len); sockaddr_storage expected_peer_address = buffered_write.peer_address.generic_address(); EXPECT_EQ(0, memcmp(&expected_peer_address, hdr.msg_name, sizeof(sockaddr_storage))); EXPECT_EQ(buffered_write.self_address.IsInitialized(), hdr.msg_control != nullptr); } return expected_num_packets_sent; })) .RetiresOnSaturation(); int expected_bytes_written = 0; for (auto it = buffered_writes.cbegin(); it != buffered_writes.cbegin() + expected_num_packets_sent; ++it) { expected_bytes_written += it->buf_len; } EXPECT_EQ( WriteResult(WRITE_STATUS_OK, expected_bytes_written), TestWriteMultiplePackets(1, buffered_writes.cbegin(), buffered_writes.cend(), &num_packets_sent)); EXPECT_EQ(expected_num_packets_sent, num_packets_sent); } } } } }
265
cpp
google/quiche
tls_client_handshaker
quiche/quic/core/tls_client_handshaker.cc
quiche/quic/core/tls_client_handshaker_test.cc
#ifndef QUICHE_QUIC_CORE_TLS_CLIENT_HANDSHAKER_H_ #define QUICHE_QUIC_CORE_TLS_CLIENT_HANDSHAKER_H_ #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/tls_client_connection.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/tls_handshaker.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT TlsClientHandshaker : public TlsHandshaker, public QuicCryptoClientStream::HandshakerInterface, public TlsClientConnection::Delegate { public: TlsClientHandshaker(const QuicServerId& server_id, QuicCryptoStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler, bool has_application_state); TlsClientHandshaker(const TlsClientHandshaker&) = delete; TlsClientHandshaker& operator=(const TlsClientHandshaker&) = delete; ~TlsClientHandshaker() override; bool CryptoConnect() override; int num_sent_client_hellos() const override; bool ResumptionAttempted() const override; bool IsResumption() const override; bool EarlyDataAccepted() const override; ssl_early_data_reason_t EarlyDataReason() const override; bool ReceivedInchoateReject() const override; int num_scup_messages_received() const override; std::string chlo_hash() const override; bool ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) override; bool encryption_established() const override; bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override; EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override; bool one_rtt_keys_available() const override; const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override; CryptoMessageParser* crypto_message_parser() override; HandshakeState GetHandshakeState() const override; size_t BufferSizeLimitForLevel(EncryptionLevel level) const override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void OnOneRttPacketAcknowledged() override; void OnHandshakePacketSent() override; void OnConnectionClosed(QuicErrorCode error, ConnectionCloseSource source) override; void OnHandshakeDoneReceived() override; void OnNewTokenReceived(absl::string_view token) override; void SetWriteSecret(EncryptionLevel level, const SSL_CIPHER* cipher, absl::Span<const uint8_t> write_secret) override; void WriteMessage(EncryptionLevel level, absl::string_view data) override; void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) override; void AllowEmptyAlpnForTests() { allow_empty_alpn_for_tests_ = true; } void AllowInvalidSNIForTests() { allow_invalid_sni_for_tests_ = true; } using TlsHandshaker::ssl; protected: const TlsConnection* tls_connection() const override { return &tls_connection_; } void FinishHandshake() override; void OnEnterEarlyData() override; void FillNegotiatedParams(); void ProcessPostHandshakeMessage() override; bool ShouldCloseConnectionOnUnexpectedError(int ssl_error) override; QuicAsyncStatus VerifyCertChain( const std::vector<std::string>& certs, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) override; void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) override; TlsConnection::Delegate* ConnectionDelegate() override { return this; } private: bool SetAlpn(); bool SetTransportParameters(); bool ProcessTransportParameters(std::string* error_details); void HandleZeroRttReject(); void OnHandshakeConfirmed(); void InsertSession(bssl::UniquePtr<SSL_SESSION> session) override; bool PrepareZeroRttConfig(QuicResumptionState* cached_state); QuicSession* session() { return session_; } QuicSession* session_; QuicServerId server_id_; ProofVerifier* proof_verifier_; std::unique_ptr<ProofVerifyContext> verify_context_; QuicCryptoClientStream::ProofHandler* proof_handler_; SessionCache* session_cache_; std::string user_agent_id_; std::string pre_shared_key_; HandshakeState state_ = HANDSHAKE_START; bool encryption_established_ = false; bool initial_keys_dropped_ = false; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> crypto_negotiated_params_; bool allow_empty_alpn_for_tests_ = false; bool allow_invalid_sni_for_tests_ = false; const bool has_application_state_; std::unique_ptr<QuicResumptionState> cached_state_; TlsClientConnection tls_connection_; bssl::UniquePtr<SSL_SESSION> cached_tls_sessions_[2] = {}; std::unique_ptr<TransportParameters> received_transport_params_ = nullptr; std::unique_ptr<ApplicationState> received_application_state_ = nullptr; }; } #endif #include "quiche/quic/core/tls_client_handshaker.h" #include <algorithm> #include <cstring> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_hostname_utils.h" #include "quiche/common/quiche_text_utils.h" namespace quic { TlsClientHandshaker::TlsClientHandshaker( const QuicServerId& server_id, QuicCryptoStream* stream, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, QuicCryptoClientStream::ProofHandler* proof_handler, bool has_application_state) : TlsHandshaker(stream, session), session_(session), server_id_(server_id), proof_verifier_(crypto_config->proof_verifier()), verify_context_(std::move(verify_context)), proof_handler_(proof_handler), session_cache_(crypto_config->session_cache()), user_agent_id_(crypto_config->user_agent_id()), pre_shared_key_(crypto_config->pre_shared_key()), crypto_negotiated_params_(new QuicCryptoNegotiatedParameters), has_application_state_(has_application_state), tls_connection_(crypto_config->ssl_ctx(), this, session->GetSSLConfig()) { if (crypto_config->tls_signature_algorithms().has_value()) { SSL_set1_sigalgs_list(ssl(), crypto_config->tls_signature_algorithms()->c_str()); } if (crypto_config->proof_source() != nullptr) { std::shared_ptr<const ClientProofSource::CertAndKey> cert_and_key = crypto_config->proof_source()->GetCertAndKey(server_id.host()); if (cert_and_key != nullptr) { QUIC_DVLOG(1) << "Setting client cert and key for " << server_id.host(); tls_connection_.SetCertChain(cert_and_key->chain->ToCryptoBuffers().value, cert_and_key->private_key.private_key()); } } #if BORINGSSL_API_VERSION >= 22 if (!crypto_config->preferred_groups().empty()) { SSL_set1_group_ids(ssl(), crypto_config->preferred_groups().data(), crypto_config->preferred_groups().size()); } #endif #if BORINGSSL_API_VERSION >= 27 SSL_set_alps_use_new_codepoint(ssl(), crypto_config->alps_use_new_codepoint()); #endif } TlsClientHandshaker::~TlsClientHandshaker() {} bool TlsClientHandshaker::CryptoConnect() { if (!pre_shared_key_.empty()) { std::string error_details = "QUIC client pre-shared keys not yet supported with TLS"; QUIC_BUG(quic_bug_10576_1) << error_details; CloseConnection(QUIC_HANDSHAKE_FAILED, error_details); return false; } int use_legacy_extension = 0; if (session()->version().UsesLegacyTlsExtension()) { use_legacy_extension = 1; } SSL_set_quic_use_legacy_codepoint(ssl(), use_legacy_extension); #if BORINGSSL_API_VERSION >= 16 SSL_set_permute_extensions(ssl(), true); #endif SSL_set_connect_state(ssl()); if (QUIC_DLOG_INFO_IS_ON() && !QuicHostnameUtils::IsValidSNI(server_id_.host())) { QUIC_DLOG(INFO) << "Client configured with invalid hostname \"" << server_id_.host() << "\", not sending as SNI"; } if (!server_id_.host().empty() && (QuicHostnameUtils::IsValidSNI(server_id_.host()) || allow_invalid_sni_for_tests_) && SSL_set_tlsext_host_name(ssl(), server_id_.host().c_str()) != 1) { return false; } if (!SetAlpn()) { CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to set ALPN"); return false; } if (!SetTransportParameters()) { CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to set Transport Parameters"); return false; } if (session_cache_) { cached_state_ = session_cache_->Lookup( server_id_, session()->GetClock()->WallNow(), SSL_get_SSL_CTX(ssl())); } if (cached_state_) { SSL_set_session(ssl(), cached_state_->tls_session.get()); if (!cached_state_->token.empty()) { session()->SetSourceAddressTokenToSend(cached_state_->token); } } SSL_set_enable_ech_grease(ssl(), tls_connection_.ssl_config().ech_grease_enabled); if (!tls_connection_.ssl_config().ech_config_list.empty() && !SSL_set1_ech_config_list( ssl(), reinterpret_cast<const uint8_t*>( tls_connection_.ssl_config().ech_config_list.data()), tls_connection_.ssl_config().ech_config_list.size())) { CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to set ECHConfigList"); return false; } AdvanceHandshake(); return session()->connection()->connected(); } bool TlsClientHandshaker::PrepareZeroRttConfig( QuicResumptionState* cached_state) { std::string error_details; if (!cached_state->transport_params || handshaker_delegate()->ProcessTransportParameters( *(cached_state->transport_params), true, &error_details) != QUIC_NO_ERROR) { QUIC_BUG(quic_bug_10576_2) << "Unable to parse cached transport parameters."; CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to parse cached Transport Parameters."); return false; } session()->connection()->OnTransportParametersResumed( *(cached_state->transport_params)); session()->OnConfigNegotiated(); if (has_application_state_) { if (!cached_state->application_state || !session()->ResumeApplicationState( cached_state->application_state.get())) { QUIC_BUG(quic_bug_10576_3) << "Unable to parse cached application state."; CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to parse cached application state."); return false; } } return true; } static bool IsValidAlpn(const std::string& alpn_string) { return alpn_string.length() <= std::numeric_limits<uint8_t>::max(); } bool TlsClientHandshaker::SetAlpn() { std::vector<std::string> alpns = session()->GetAlpnsToOffer(); if (alpns.empty()) { if (allow_empty_alpn_for_tests_) { return true; } QUIC_BUG(quic_bug_10576_4) << "ALPN missing"; return false; } if (!std::all_of(alpns.begin(), alpns.end(), IsValidAlpn)) { QUIC_BUG(quic_bug_10576_5) << "ALPN too long"; return false; } uint8_t alpn[1024]; QuicDataWriter alpn_writer(sizeof(alpn), reinterpret_cast<char*>(alpn)); bool success = true; for (const std::string& alpn_string : alpns) { success = success && alpn_writer.WriteUInt8(alpn_string.size()) && alpn_writer.WriteStringPiece(alpn_string); } success = success && (SSL_set_alpn_protos(ssl(), alpn, alpn_writer.length()) == 0); if (!success) { QUIC_BUG(quic_bug_10576_6) << "Failed to set ALPN: " << quiche::QuicheTextUtils::HexDump( absl::string_view(alpn_writer.data(), alpn_writer.length())); return false; } for (const std::string& alpn_string : alpns) { for (const ParsedQuicVersion& version : session()->supported_versions()) { if (!version.UsesHttp3() || AlpnForVersion(version) != alpn_string) { continue; } if (SSL_add_application_settings( ssl(), reinterpret_cast<const uint8_t*>(alpn_string.data()), alpn_string.size(), nullptr, 0) != 1) { QUIC_BUG(quic_bug_10576_7) << "Failed to enable ALPS."; return false; } break; } } QUIC_DLOG(INFO) << "Client using ALPN: '" << alpns[0] << "'"; return true; } bool TlsClientHandshaker::SetTransportParameters() { TransportParameters params; params.perspective = Perspective::IS_CLIENT; params.legacy_version_information = TransportParameters::LegacyVersionInformation(); params.legacy_version_information->version = CreateQuicVersionLabel(session()->supported_versions().front()); params.version_information = TransportParameters::VersionInformation(); const QuicVersionLabel version = CreateQuicVersionLabel(session()->version()); params.version_information->chosen_version = version; params.version_information->other_versions.push_back(version); if (!handshaker_delegate()->FillTransportParameters(&params)) { return false; } session()->connection()->OnTransportParametersSent(params); std::vector<uint8_t> param_bytes; return SerializeTransportParameters(params, &param_bytes) && SSL_set_quic_transport_params(ssl(), param_bytes.data(), param_bytes.size()) == 1; } bool TlsClientHandshaker::ProcessTransportParameters( std::string* error_details) { received_transport_params_ = std::make_unique<TransportParameters>(); const uint8_t* param_bytes; size_t param_bytes_len; SSL_get_peer_quic_transport_params(ssl(), &param_bytes, &param_bytes_len); if (param_bytes_len == 0) { *error_details = "Server's transport parameters are missing"; return false; } std::string parse_error_details; if (!ParseTransportParameters( session()->connection()->version(), Perspective::IS_SERVER, param_bytes, param_bytes_len, received_transport_params_.get(), &parse_error_details)) { QUICHE_DCHECK(!parse_error_details.empty()); *error_details = "Unable to parse server's transport parameters: " + parse_error_details; return false; } session()->connection()->OnTransportParametersReceived( *received_transport_params_); if (received_transport_params_->legacy_version_information.has_value()) { if (received_transport_params_->legacy_version_information->version != CreateQuicVersionLabel(session()->connection()->version())) { *error_details = "Version mismatch detected"; return false; } if (CryptoUtils::ValidateServerHelloVersions( received_transport_params_->legacy_version_information ->supported_versions, session()->connection()->server_supported_versions(), error_details) != QUIC_NO_ERROR) { QUICHE_DCHECK(!error_details->empty()); return false; } } if (received_transport_params_->version_information.has_value()) { if (!CryptoUtils::ValidateChosenVersion( received_transport_params_->version_information->chosen_version, session()->version(), error_details)) { QUICHE_DCHECK(!error_details->empty()); return false; } if (!CryptoUtils::CryptoUtils::ValidateServerVersions( received_transport_params_->version_information->other_versions, session()->version(), session()->client_original_supported_versions(), error_details)) { QUICHE_DCHECK(!error_details->empty()); return false; } } if (handshaker_delegate()->ProcessTransportParameters( *received_transport_params_, false, error_details) != QUIC_NO_ERROR) { QUICHE_DCHECK(!error_details->empty()); return false; } session()->OnConfigNegotiated(); if (is_connection_closed()) { *error_details = "Session closed the connection when parsing negotiated config."; return false; } return true; } int TlsClientHandshaker::num_sent_client_hellos() const { return 0; } bool TlsClientHandshaker::ResumptionAttempted() const { QUIC_BUG_IF(quic_tls_client_resumption_attempted, !encryption_established_); return cached_state_ != nullptr; } bool TlsClientHandshaker::IsResumption() const { QUIC_BUG_IF(quic_bug_12736_1, !one_rtt_keys_available()); return SSL_session_reused(ssl()) == 1; } bool TlsClientHandshaker::EarlyDataAccepted() const { QUIC_BUG_IF(quic_bug_12736_2, !one_rtt_keys_available()); return SSL_early_data_accepted(ssl()) == 1; } ssl_early_data_reason_t TlsClientHandshaker::EarlyDataReason() const { return TlsHandshaker::EarlyDataReason(); } bool TlsClientHandshaker::ReceivedInchoateReject() const { QUIC_BUG_IF(quic_bug_12736_3, !one_rtt_keys_available()); return false; } int TlsClientHandshaker::num_scup_messages_received() const { return 0; } std::string TlsClientHandshaker::chlo_hash() const { return ""; } bool TlsClientHandshaker::ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) { return ExportKeyingMaterialForLabel(label, context, result_len, result); } bool TlsClientHandshaker::encryption_established() const { return encryption_established_; } bool TlsClientHandshaker::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel TlsClientHandshaker::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } bool TlsClientHandshaker::one_rtt_keys_available() const { return state_ >= HANDSHAKE_COMPLETE; } const QuicCryptoNegotiatedParameters& TlsClientHandshaker::crypto_negotiated_params() const { return *crypto_negotiated_params_; } CryptoMessageParser* TlsClientHandshaker::crypto_message_parser() { return TlsHandshaker::crypto_message_parser(); } HandshakeState TlsClientHandshaker::GetHandshakeState() const { return state_; } size_t TlsClientHandshaker::BufferSizeLimitForLevel( EncryptionLevel level) const { return TlsHandshaker::BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> TlsClientHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return TlsHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> TlsClientHandshaker::CreateCurrentOneRttEncrypter() { return TlsHandshaker::CreateCurrentOneRttEncrypter(); } void TlsClientHandshaker::OnOneRttPacketAcknowledged() { OnHandshakeConfirmed(); } void TlsClientHandshaker::OnHandshakePacketSent() { if (initial_keys_dropped_) { return; } initial_keys_dropped_ = true; handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_INITIAL); } void TlsClientHandshaker::OnConnectionClosed(QuicErrorCode error, ConnectionCloseSource source) { TlsHandshaker::OnConnectionClosed(error, source); } void TlsClientHandshaker::OnHandshakeDoneReceived() { if (!one_rtt_keys_available()) { CloseConnection(QUIC_HANDSHAKE_FAILED, "Unexpected handshake done received"); return; } OnHandshakeConfirmed(); } void TlsClientHandshaker::OnNewTokenReceived(absl::string_view token) { if (token.empty()) { return; } if (session_cache_ != nullptr) { session_cache_->OnNewTokenReceived(server_id_, token); } } void TlsClientHandshaker::SetWriteSecret( EncryptionLevel level, const SSL_CIPHER* cipher, absl::Span<const uint8_t> write_secret) { if (is_connection_closed()) { return; } if (level == ENCRYPTION_FORWARD_SECURE || level == ENCRYPTION_ZERO_RTT) { encryption_established_ = true; } TlsHandshaker::SetWriteSecret(level, cipher, write_secret); if (level == ENCRYPTION_FORWARD_SECURE) { handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_ZERO_RTT); } } void TlsClientHandshaker::OnHandshakeConfirmed() { QUICHE_DCHECK(one_rtt_keys_available()); if (state_ >= HANDSHAKE_CONFIRMED) { return; } state_ = HANDSHAKE_CONFIRMED; handshaker_delegate()->OnTlsHandshakeConfirmed(); handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_HANDSHAKE); handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_HANDSHAKE); } QuicAsyncStatus TlsClientHandshaker::VerifyCertChain( const std::vector<std::string>& certs, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) { const uint8_t* ocsp_response_raw; size_t ocsp_response_len; SSL_get0_ocsp_response(ssl(), &ocsp_response_raw, &ocsp_response_len); std::string ocsp_response(reinterpret_cast<const char*>(ocsp_response_raw), ocsp_response_len); const uint8_t* sct_list_raw; size_t sct_list_len; SSL_get0_signed_cert_timestamp_list(ssl(), &sct_list_raw, &sct_list_len); std::string sct_list(reinterpret_cast<const char*>(sct_list_raw), sct_list_len); return proof_verifier_->VerifyCertChain( server_id_.host(), server_id_.port(), certs, ocsp_response, sct_list, verify_context_.get(), error_details, details, out_alert, std::move(callback)); } void TlsClientHandshaker::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) { proof_handler_->OnProofVerifyDetailsAvailable(verify_details); } void TlsClientHandshaker::FinishHandshake() { FillNegotiatedParams(); QUICHE_CHECK(!SSL_in_early_data(ssl())); QUIC_LOG(INFO) << "Client: handshake finished"; std::string error_details; if (!ProcessTransportParameters(&error_details)) { QUICHE_DCHECK(!error_details.empty()); CloseConnection(QUIC_HANDSHAKE_FAILED, error_details); return; } const uint8_t* alpn_data = nullptr; unsigned alpn_length = 0; SSL_get0_alpn_selected(ssl(), &alpn_data, &alpn_length); if (alpn_length == 0) { QUIC_DLOG(ERROR) << "Client: server did not select ALPN"; CloseConnection(QUIC_HANDSHAKE_FAILED, "Server did not select ALPN"); return; } std::string received_alpn_string(reinterpret_cast<const char*>(alpn_data), alpn_length); std::vector<std::string> offered_alpns = session()->GetAlpnsToOffer(); if (std::find(offered_alpns.begin(), offered_alpns.end(), received_alpn_string) == offered_alpns.end()) { QUIC_LOG(ERROR) << "Client: received mismatched ALPN '" << received_alpn_string; CloseConnection(QUIC_HANDSHAKE_FAILED, "Client received mismatched ALPN"); return; } session()->OnAlpnSelected(received_alpn_string); QUIC_DLOG(INFO) << "Client: server selected ALPN: '" << received_alpn_string << "'"; const uint8_t* alps_data; size_t alps_length; SSL_get0_peer_application_settings(ssl(), &alps_data, &alps_length); if (alps_length > 0) { auto error = session()->OnAlpsData(alps_data, alps_length); if (error.has_value()) { CloseConnection(QUIC_HANDSHAKE_FAILED, absl::StrCat("Error processing ALPS data: ", *error)); return; } } state_ = HANDSHAKE_COMPLETE; handshaker_delegate()->OnTlsHandshakeComplete(); } void TlsClientHandshaker::OnEnterEarlyData() { QUICHE_DCHECK(SSL_in_early_data(ssl())); FillNegotiatedParams(); PrepareZeroRttConfig(cached_state_.get()); } void TlsClientHandshaker::FillNegotiatedParams() { const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl()); if (cipher) { crypto_negotiated_params_->cipher_suite = SSL_CIPHER_get_protocol_id(cipher); } crypto_negotiated_params_->key_exchange_group = SSL_get_curve_id(ssl()); crypto_negotiated_params_->peer_signature_algorithm = SSL_get_peer_signature_algorithm(ssl()); crypto_negotiated_params_->encrypted_client_hello = SSL_ech_accepted(ssl()); } void TlsClientHandshaker::ProcessPostHandshakeMessage() { int rv = SSL_process_quic_post_handshake(ssl()); if (rv != 1) { CloseConnection(QUIC_HANDSHAKE_FAILED, "Unexpected post-handshake data"); } } bool TlsClientHandshaker::ShouldCloseConnectionOnUnexpectedError( int ssl_error) { if (ssl_error != SSL_ERROR_EARLY_DATA_REJECTED) { return true; } HandleZeroRttReject(); return false; } void TlsClientHandshaker::HandleZeroRttReject() { QUIC_LOG(INFO) << "0-RTT handshake attempted but was rejected by the server"; QUICHE_DCHECK(session_cache_); encryption_established_ = false; handshaker_delegate()->OnZeroRttRejected(EarlyDataReason()); SSL_reset_early_data_reject(ssl()); session_cache_->ClearEarlyData(server_id_); AdvanceHandshake(); } void TlsClientHandshaker::InsertSession(bssl::UniquePtr<SSL_SESSION> session) { if (!received_transport_params_) { QUIC_BUG(quic_bug_10576_8) << "Transport parameters isn't received"; return; } if (session_cache_ == nullptr) { QUIC_DVLOG(1) << "No session cache, not inserting a session"; return; } if (has_application_state_ && !received_application_state_) { if (cached_tls_sessions_[0] != nullptr) { cached_tls_sessions_[1] = std::move(cached_tls_sessions_[0]); } cached_tls_sessions_[0] = std::move(session); return; } session_cache_->Insert(server_id_, std::move(session), *received_transport_params_, received_application_state_.get()); } void TlsClientHandshaker::WriteMessage(EncryptionLevel level, absl::string_view data) { if (level == ENCRYPTION_HANDSHAKE && state_ < HANDSHAKE_PROCESSED) { state_ = HANDSHAKE_PROCESSED; } TlsHandshaker::WriteMessage(level, data); } void TlsClientHandshaker::SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) { QUICHE_DCHECK(one_rtt_keys_available()); received_application_state_ = std::move(application_state); if (session_cache_ != nullptr && cached_tls_sessions_[0] != nullptr) { if (cached_tls_sessions_[1] != nullptr) { session_cache_->Insert(server_id_, std::move(cached_tls_sessions_[1]), *received_transport_params_, received_application_state_.get()); } session_cache_->Insert(server_id_, std::move(cached_tls_sessions_[0]), *received_transport_params_, received_application_state_.get()); } } }
#include <algorithm> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "openssl/hpke.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/quic/tools/fake_proof_verifier.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; namespace quic { namespace test { namespace { constexpr char kServerHostname[] = "test.example.com"; constexpr uint16_t kServerPort = 443; class TestProofVerifier : public ProofVerifier { public: TestProofVerifier() : verifier_(crypto_test_utils::ProofVerifierForTesting()) {} QuicAsyncStatus VerifyProof( const std::string& hostname, const uint16_t port, const std::string& server_config, QuicTransportVersion quic_version, absl::string_view chlo_hash, const std::vector<std::string>& certs, const std::string& cert_sct, const std::string& signature, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, std::unique_ptr<ProofVerifierCallback> callback) override { return verifier_->VerifyProof( hostname, port, server_config, quic_version, chlo_hash, certs, cert_sct, signature, context, error_details, details, std::move(callback)); } QuicAsyncStatus VerifyCertChain( const std::string& hostname, const uint16_t port, const std::vector<std::string>& certs, const std::string& ocsp_response, const std::string& cert_sct, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) override { if (!active_) { return verifier_->VerifyCertChain( hostname, port, certs, ocsp_response, cert_sct, context, error_details, details, out_alert, std::move(callback)); } pending_ops_.push_back(std::make_unique<VerifyChainPendingOp>( hostname, port, certs, ocsp_response, cert_sct, context, error_details, details, out_alert, std::move(callback), verifier_.get())); return QUIC_PENDING; } std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override { return nullptr; } void Activate() { active_ = true; } size_t NumPendingCallbacks() const { return pending_ops_.size(); } void InvokePendingCallback(size_t n) { ASSERT_GT(NumPendingCallbacks(), n); pending_ops_[n]->Run(); auto it = pending_ops_.begin() + n; pending_ops_.erase(it); } private: class FailingProofVerifierCallback : public ProofVerifierCallback { public: void Run(bool , const std::string& , std::unique_ptr<ProofVerifyDetails>* ) override { FAIL(); } }; class VerifyChainPendingOp { public: VerifyChainPendingOp(const std::string& hostname, const uint16_t port, const std::vector<std::string>& certs, const std::string& ocsp_response, const std::string& cert_sct, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback, ProofVerifier* delegate) : hostname_(hostname), port_(port), certs_(certs), ocsp_response_(ocsp_response), cert_sct_(cert_sct), context_(context), error_details_(error_details), details_(details), out_alert_(out_alert), callback_(std::move(callback)), delegate_(delegate) {} void Run() { QuicAsyncStatus status = delegate_->VerifyCertChain( hostname_, port_, certs_, ocsp_response_, cert_sct_, context_, error_details_, details_, out_alert_, std::make_unique<FailingProofVerifierCallback>()); ASSERT_NE(status, QUIC_PENDING); callback_->Run(status == QUIC_SUCCESS, *error_details_, details_); } private: std::string hostname_; const uint16_t port_; std::vector<std::string> certs_; std::string ocsp_response_; std::string cert_sct_; const ProofVerifyContext* context_; std::string* error_details_; std::unique_ptr<ProofVerifyDetails>* details_; uint8_t* out_alert_; std::unique_ptr<ProofVerifierCallback> callback_; ProofVerifier* delegate_; }; std::unique_ptr<ProofVerifier> verifier_; bool active_ = false; std::vector<std::unique_ptr<VerifyChainPendingOp>> pending_ops_; }; class TlsClientHandshakerTest : public QuicTestWithParam<ParsedQuicVersion> { public: TlsClientHandshakerTest() : supported_versions_({GetParam()}), server_id_(kServerHostname, kServerPort, false), server_compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) { crypto_config_ = std::make_unique<QuicCryptoClientConfig>( std::make_unique<TestProofVerifier>(), std::make_unique<test::SimpleSessionCache>()); server_crypto_config_ = crypto_test_utils::CryptoServerConfigForTesting(); CreateConnection(); } void CreateSession() { session_ = std::make_unique<TestQuicSpdyClientSession>( connection_, DefaultQuicConfig(), supported_versions_, server_id_, crypto_config_.get(), ssl_config_); EXPECT_CALL(*session_, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>( {AlpnForVersion(connection_->version())}))); } void CreateConnection() { connection_ = new PacketSavingConnection(&client_helper_, &alarm_factory_, Perspective::IS_CLIENT, supported_versions_); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); CreateSession(); } void CompleteCryptoHandshake() { CompleteCryptoHandshakeWithServerALPN( AlpnForVersion(connection_->version())); } void CompleteCryptoHandshakeWithServerALPN(const std::string& alpn) { EXPECT_CALL(*connection_, SendCryptoData(_, _, _)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); QuicConfig config; crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), alpn); } QuicCryptoClientStream* stream() { return session_->GetMutableCryptoStream(); } QuicCryptoServerStreamBase* server_stream() { return server_session_->GetMutableCryptoStream(); } void InitializeFakeServer() { TestQuicSpdyServerSession* server_session = nullptr; CreateServerSessionForTest( server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_, &server_helper_, &alarm_factory_, server_crypto_config_.get(), &server_compressed_certs_cache_, &server_connection_, &server_session); server_session_.reset(server_session); std::string alpn = AlpnForVersion(connection_->version()); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillRepeatedly([alpn](const std::vector<absl::string_view>& alpns) { return std::find(alpns.cbegin(), alpns.cend(), alpn); }); } static bssl::UniquePtr<SSL_ECH_KEYS> MakeTestEchKeys( const char* public_name, size_t max_name_len, std::string* ech_config_list) { bssl::ScopedEVP_HPKE_KEY key; if (!EVP_HPKE_KEY_generate(key.get(), EVP_hpke_x25519_hkdf_sha256())) { return nullptr; } uint8_t* ech_config; size_t ech_config_len; if (!SSL_marshal_ech_config(&ech_config, &ech_config_len, 1, key.get(), public_name, max_name_len)) { return nullptr; } bssl::UniquePtr<uint8_t> scoped_ech_config(ech_config); uint8_t* ech_config_list_raw; size_t ech_config_list_len; bssl::UniquePtr<SSL_ECH_KEYS> keys(SSL_ECH_KEYS_new()); if (!keys || !SSL_ECH_KEYS_add(keys.get(), 1, ech_config, ech_config_len, key.get()) || !SSL_ECH_KEYS_marshal_retry_configs(keys.get(), &ech_config_list_raw, &ech_config_list_len)) { return nullptr; } bssl::UniquePtr<uint8_t> scoped_ech_config_list(ech_config_list_raw); ech_config_list->assign(ech_config_list_raw, ech_config_list_raw + ech_config_list_len); return keys; } MockQuicConnectionHelper server_helper_; MockQuicConnectionHelper client_helper_; MockAlarmFactory alarm_factory_; PacketSavingConnection* connection_; ParsedQuicVersionVector supported_versions_; std::unique_ptr<TestQuicSpdyClientSession> session_; QuicServerId server_id_; CryptoHandshakeMessage message_; std::unique_ptr<QuicCryptoClientConfig> crypto_config_; std::optional<QuicSSLConfig> ssl_config_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; PacketSavingConnection* server_connection_; std::unique_ptr<TestQuicSpdyServerSession> server_session_; QuicCompressedCertsCache server_compressed_certs_cache_; }; INSTANTIATE_TEST_SUITE_P(TlsHandshakerTests, TlsClientHandshakerTest, ::testing::ValuesIn(AllSupportedVersionsWithTls()), ::testing::PrintToStringParamName()); TEST_P(TlsClientHandshakerTest, NotInitiallyConnected) { EXPECT_FALSE(stream()->encryption_established()); EXPECT_FALSE(stream()->one_rtt_keys_available()); } TEST_P(TlsClientHandshakerTest, ConnectedAfterHandshake) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); } TEST_P(TlsClientHandshakerTest, ConnectionClosedOnTlsError) { stream()->CryptoConnect(); EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _)); char bogus_handshake_message[] = { 2, 0, 0, 0, }; stream()->crypto_message_parser()->ProcessInput( absl::string_view(bogus_handshake_message, ABSL_ARRAYSIZE(bogus_handshake_message)), ENCRYPTION_INITIAL); EXPECT_FALSE(stream()->one_rtt_keys_available()); } TEST_P(TlsClientHandshakerTest, ProofVerifyDetailsAvailableAfterHandshake) { EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)); stream()->CryptoConnect(); QuicConfig config; crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), AlpnForVersion(connection_->version())); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); } TEST_P(TlsClientHandshakerTest, HandshakeWithAsyncProofVerifier) { InitializeFakeServer(); TestProofVerifier* proof_verifier = static_cast<TestProofVerifier*>(crypto_config_->proof_verifier()); proof_verifier->Activate(); stream()->CryptoConnect(); std::pair<size_t, size_t> moved_message_counts = crypto_test_utils::AdvanceHandshake( connection_, stream(), 0, server_connection_, server_stream(), 0); ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u); proof_verifier->InvokePendingCallback(0); crypto_test_utils::AdvanceHandshake( connection_, stream(), moved_message_counts.first, server_connection_, server_stream(), moved_message_counts.second); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); } TEST_P(TlsClientHandshakerTest, Resumption) { SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->ResumptionAttempted()); EXPECT_FALSE(stream()->IsResumption()); CreateConnection(); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->ResumptionAttempted()); EXPECT_TRUE(stream()->IsResumption()); } TEST_P(TlsClientHandshakerTest, ResumptionRejection) { SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->ResumptionAttempted()); EXPECT_FALSE(stream()->IsResumption()); SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET); CreateConnection(); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->ResumptionAttempted()); EXPECT_FALSE(stream()->IsResumption()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_unsupported_for_session); } TEST_P(TlsClientHandshakerTest, ZeroRttResumption) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); CreateConnection(); EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); EXPECT_TRUE(stream()->encryption_established()); EXPECT_NE(stream()->crypto_negotiated_params().cipher_suite, 0); EXPECT_NE(stream()->crypto_negotiated_params().key_exchange_group, 0); EXPECT_NE(stream()->crypto_negotiated_params().peer_signature_algorithm, 0); QuicConfig config; crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), AlpnForVersion(connection_->version())); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->IsResumption()); EXPECT_TRUE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_accepted); } TEST_P(TlsClientHandshakerTest, ZeroRttResumptionWithAyncProofVerifier) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); CreateConnection(); InitializeFakeServer(); EXPECT_CALL(*session_, OnConfigNegotiated()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)) .Times(testing::AnyNumber()); TestProofVerifier* proof_verifier = static_cast<TestProofVerifier*>(crypto_config_->proof_verifier()); proof_verifier->Activate(); stream()->CryptoConnect(); ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u); crypto_test_utils::AdvanceHandshake(connection_, stream(), 0, server_connection_, server_stream(), 0); EXPECT_FALSE(stream()->one_rtt_keys_available()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); proof_verifier->InvokePendingCallback(0); QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_); EXPECT_NE(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_HANDSHAKE)); } TEST_P(TlsClientHandshakerTest, ZeroRttRejection) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false); CreateConnection(); EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION)); if (VersionUsesHttp3(session_->transport_version())) { EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION)); } EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION)); if (VersionUsesHttp3(session_->transport_version())) { EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION)); } CompleteCryptoHandshake(); QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_); EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT)); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->IsResumption()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_peer_declined); } TEST_P(TlsClientHandshakerTest, ZeroRttAndResumptionRejection) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET); CreateConnection(); EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION)); if (VersionUsesHttp3(session_->transport_version())) { EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION)); } EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION)); if (VersionUsesHttp3(session_->transport_version())) { EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION)); } CompleteCryptoHandshake(); QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_); EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT)); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_session_not_resumed); } TEST_P(TlsClientHandshakerTest, ClientSendsNoSNI) { server_id_ = QuicServerId("", 443); crypto_config_.reset(new QuicCryptoClientConfig( std::make_unique<FakeProofVerifier>(), nullptr)); CreateConnection(); InitializeFakeServer(); stream()->CryptoConnect(); crypto_test_utils::CommunicateHandshakeMessages( connection_, stream(), server_connection_, server_stream()); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, ""); } TEST_P(TlsClientHandshakerTest, ClientSendingTooManyALPNs) { std::string long_alpn(250, 'A'); EXPECT_QUIC_BUG( { EXPECT_CALL(*session_, GetAlpnsToOffer()) .WillOnce(testing::Return(std::vector<std::string>({ long_alpn + "1", long_alpn + "2", long_alpn + "3", long_alpn + "4", long_alpn + "5", long_alpn + "6", long_alpn + "7", long_alpn + "8", }))); stream()->CryptoConnect(); }, "Failed to set ALPN"); } TEST_P(TlsClientHandshakerTest, ServerRequiresCustomALPN) { InitializeFakeServer(); const std::string kTestAlpn = "An ALPN That Client Did Not Offer"; EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillOnce([kTestAlpn](const std::vector<absl::string_view>& alpns) { return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn); }); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, static_cast<QuicIetfTransportErrorCodes>( CRYPTO_ERROR_FIRST + 120), "TLS handshake failure (ENCRYPTION_INITIAL) 120: " "no application protocol", _)); stream()->CryptoConnect(); crypto_test_utils::AdvanceHandshake(connection_, stream(), 0, server_connection_, server_stream(), 0); EXPECT_FALSE(stream()->one_rtt_keys_available()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->encryption_established()); EXPECT_FALSE(server_stream()->encryption_established()); } TEST_P(TlsClientHandshakerTest, ZeroRTTNotAttemptedOnALPNChange) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); CreateConnection(); const std::string kTestAlpn = "Test ALPN"; EXPECT_CALL(*session_, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>({kTestAlpn}))); EXPECT_CALL(*session_, OnConfigNegotiated()).Times(1); CompleteCryptoHandshakeWithServerALPN(kTestAlpn); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_alpn_mismatch); } TEST_P(TlsClientHandshakerTest, InvalidSNI) { server_id_ = QuicServerId("invalid!.example.com", 443); crypto_config_.reset(new QuicCryptoClientConfig( std::make_unique<FakeProofVerifier>(), nullptr)); CreateConnection(); InitializeFakeServer(); stream()->CryptoConnect(); crypto_test_utils::CommunicateHandshakeMessages( connection_, stream(), server_connection_, server_stream()); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, ""); } TEST_P(TlsClientHandshakerTest, BadTransportParams) { if (!connection_->version().UsesHttp3()) { return; } CompleteCryptoHandshake(); CreateConnection(); stream()->CryptoConnect(); auto* id_manager = QuicSessionPeer::ietf_streamid_manager(session_.get()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, id_manager->max_outgoing_bidirectional_streams()); QuicConfig config; config.SetMaxBidirectionalStreamsToSend( config.GetMaxBidirectionalStreamsToSend() - 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED, _, _)) .WillOnce(testing::Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _)); crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), AlpnForVersion(connection_->version())); } TEST_P(TlsClientHandshakerTest, ECH) { ssl_config_.emplace(); bssl::UniquePtr<SSL_ECH_KEYS> ech_keys = MakeTestEchKeys("public-name.example", 64, &ssl_config_->ech_config_list); ASSERT_TRUE(ech_keys); ASSERT_TRUE( SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get())); CreateConnection(); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello); } TEST_P(TlsClientHandshakerTest, ECHWithConfigAndGREASE) { ssl_config_.emplace(); bssl::UniquePtr<SSL_ECH_KEYS> ech_keys = MakeTestEchKeys("public-name.example", 64, &ssl_config_->ech_config_list); ASSERT_TRUE(ech_keys); ssl_config_->ech_grease_enabled = true; ASSERT_TRUE( SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get())); CreateConnection(); CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol()); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello); } TEST_P(TlsClientHandshakerTest, ECHInvalidConfig) { ssl_config_.emplace(); ssl_config_->ech_config_list = "invalid config"; CreateConnection(); EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _)); stream()->CryptoConnect(); } TEST_P(TlsClientHandshakerTest, ECHWrongKeys) { ssl_config_.emplace(); bssl::UniquePtr<SSL_ECH_KEYS> ech_keys1 = MakeTestEchKeys("public-name.example", 64, &ssl_config_->ech_config_list); ASSERT_TRUE(ech_keys1); std::string ech_config_list2; bssl::UniquePtr<SSL_ECH_KEYS> ech_keys2 = MakeTestEchKeys( "public-name.example", 64, &ech_config_list2); ASSERT_TRUE(ech_keys2); ASSERT_TRUE( SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys2.get())); CreateConnection(); EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_
266
cpp
google/quiche
quic_stream_sequencer
quiche/quic/core/quic_stream_sequencer.cc
quiche/quic/core/quic_stream_sequencer_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_SEQUENCER_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_SEQUENCER_H_ #include <cstddef> #include <map> #include <string> #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicStreamSequencerPeer; } class QUICHE_EXPORT QuicStreamSequencer final { public: class QUICHE_EXPORT StreamInterface { public: virtual ~StreamInterface() = default; virtual void OnDataAvailable() = 0; virtual void OnFinRead() = 0; virtual void AddBytesConsumed(QuicByteCount bytes) = 0; virtual void ResetWithError(QuicResetStreamError error) = 0; virtual void OnUnrecoverableError(QuicErrorCode error, const std::string& details) = 0; virtual void OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) = 0; virtual QuicStreamId id() const = 0; virtual ParsedQuicVersion version() const = 0; }; explicit QuicStreamSequencer(StreamInterface* quic_stream); QuicStreamSequencer(const QuicStreamSequencer&) = delete; QuicStreamSequencer(QuicStreamSequencer&&) = default; QuicStreamSequencer& operator=(const QuicStreamSequencer&) = delete; QuicStreamSequencer& operator=(QuicStreamSequencer&&) = default; ~QuicStreamSequencer(); void OnStreamFrame(const QuicStreamFrame& frame); void OnCryptoFrame(const QuicCryptoFrame& frame); int GetReadableRegions(iovec* iov, size_t iov_len) const; bool GetReadableRegion(iovec* iov) const; bool PeekRegion(QuicStreamOffset offset, iovec* iov) const; size_t Readv(const struct iovec* iov, size_t iov_len); void MarkConsumed(size_t num_bytes); void Read(std::string* buffer); bool HasBytesToRead() const; size_t ReadableBytes() const; bool IsClosed() const; void SetUnblocked(); void SetBlockedUntilFlush(); void StopReading(); void ReleaseBuffer(); void ReleaseBufferIfEmpty(); size_t NumBytesBuffered() const; QuicStreamOffset NumBytesConsumed() const; bool IsAllDataAvailable() const; QuicStreamOffset close_offset() const { return close_offset_; } int num_frames_received() const { return num_frames_received_; } int num_duplicate_frames_received() const { return num_duplicate_frames_received_; } bool ignore_read_data() const { return ignore_read_data_; } void set_level_triggered(bool level_triggered) { level_triggered_ = level_triggered; } bool level_triggered() const { return level_triggered_; } void set_stream(StreamInterface* stream) { stream_ = stream; } std::string DebugString() const; private: friend class test::QuicStreamSequencerPeer; void FlushBufferedFrames(); bool CloseStreamAtOffset(QuicStreamOffset offset); void MaybeCloseStream(); void OnFrameData(QuicStreamOffset byte_offset, size_t data_len, const char* data_buffer); StreamInterface* stream_; QuicStreamSequencerBuffer buffered_frames_; QuicStreamOffset highest_offset_; QuicStreamOffset close_offset_; bool blocked_; int num_frames_received_; int num_duplicate_frames_received_; bool ignore_read_data_; bool level_triggered_; }; } #endif #include "quiche/quic/core/quic_stream_sequencer.h" #include <algorithm> #include <cstddef> #include <limits> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_stack_trace.h" namespace quic { QuicStreamSequencer::QuicStreamSequencer(StreamInterface* quic_stream) : stream_(quic_stream), buffered_frames_(kStreamReceiveWindowLimit), highest_offset_(0), close_offset_(std::numeric_limits<QuicStreamOffset>::max()), blocked_(false), num_frames_received_(0), num_duplicate_frames_received_(0), ignore_read_data_(false), level_triggered_(false) {} QuicStreamSequencer::~QuicStreamSequencer() { if (stream_ == nullptr) { QUIC_BUG(quic_bug_10858_1) << "Double free'ing QuicStreamSequencer at " << this << ". " << QuicStackTrace(); } stream_ = nullptr; } void QuicStreamSequencer::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK_LE(frame.offset + frame.data_length, close_offset_); ++num_frames_received_; const QuicStreamOffset byte_offset = frame.offset; const size_t data_len = frame.data_length; if (frame.fin && (!CloseStreamAtOffset(frame.offset + data_len) || data_len == 0)) { return; } if (stream_->version().HasIetfQuicFrames() && data_len == 0) { QUICHE_DCHECK(!frame.fin); return; } OnFrameData(byte_offset, data_len, frame.data_buffer); } void QuicStreamSequencer::OnCryptoFrame(const QuicCryptoFrame& frame) { ++num_frames_received_; if (frame.data_length == 0) { return; } OnFrameData(frame.offset, frame.data_length, frame.data_buffer); } void QuicStreamSequencer::OnFrameData(QuicStreamOffset byte_offset, size_t data_len, const char* data_buffer) { highest_offset_ = std::max(highest_offset_, byte_offset + data_len); const size_t previous_readable_bytes = buffered_frames_.ReadableBytes(); size_t bytes_written; std::string error_details; QuicErrorCode result = buffered_frames_.OnStreamData( byte_offset, absl::string_view(data_buffer, data_len), &bytes_written, &error_details); if (result != QUIC_NO_ERROR) { std::string details = absl::StrCat("Stream ", stream_->id(), ": ", QuicErrorCodeToString(result), ": ", error_details); QUIC_LOG_FIRST_N(WARNING, 50) << QuicErrorCodeToString(result); QUIC_LOG_FIRST_N(WARNING, 50) << details; stream_->OnUnrecoverableError(result, details); return; } if (bytes_written == 0) { ++num_duplicate_frames_received_; return; } if (blocked_) { return; } if (level_triggered_) { if (buffered_frames_.ReadableBytes() > previous_readable_bytes) { if (ignore_read_data_) { FlushBufferedFrames(); } else { stream_->OnDataAvailable(); } } return; } const bool stream_unblocked = previous_readable_bytes == 0 && buffered_frames_.ReadableBytes() > 0; if (stream_unblocked) { if (ignore_read_data_) { FlushBufferedFrames(); } else { stream_->OnDataAvailable(); } } } bool QuicStreamSequencer::CloseStreamAtOffset(QuicStreamOffset offset) { const QuicStreamOffset kMaxOffset = std::numeric_limits<QuicStreamOffset>::max(); if (close_offset_ != kMaxOffset && offset != close_offset_) { stream_->OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, absl::StrCat( "Stream ", stream_->id(), " received new final offset: ", offset, ", which is different from close offset: ", close_offset_)); return false; } if (offset < highest_offset_) { stream_->OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, absl::StrCat( "Stream ", stream_->id(), " received fin with offset: ", offset, ", which reduces current highest offset: ", highest_offset_)); return false; } close_offset_ = offset; MaybeCloseStream(); return true; } void QuicStreamSequencer::MaybeCloseStream() { if (blocked_ || !IsClosed()) { return; } QUIC_DVLOG(1) << "Passing up termination, as we've processed " << buffered_frames_.BytesConsumed() << " of " << close_offset_ << " bytes."; if (ignore_read_data_) { stream_->OnFinRead(); } else { stream_->OnDataAvailable(); } buffered_frames_.Clear(); } int QuicStreamSequencer::GetReadableRegions(iovec* iov, size_t iov_len) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.GetReadableRegions(iov, iov_len); } bool QuicStreamSequencer::GetReadableRegion(iovec* iov) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.GetReadableRegion(iov); } bool QuicStreamSequencer::PeekRegion(QuicStreamOffset offset, iovec* iov) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.PeekRegion(offset, iov); } void QuicStreamSequencer::Read(std::string* buffer) { QUICHE_DCHECK(!blocked_); buffer->resize(buffer->size() + ReadableBytes()); iovec iov; iov.iov_len = ReadableBytes(); iov.iov_base = &(*buffer)[buffer->size() - iov.iov_len]; Readv(&iov, 1); } size_t QuicStreamSequencer::Readv(const struct iovec* iov, size_t iov_len) { QUICHE_DCHECK(!blocked_); std::string error_details; size_t bytes_read; QuicErrorCode read_error = buffered_frames_.Readv(iov, iov_len, &bytes_read, &error_details); if (read_error != QUIC_NO_ERROR) { std::string details = absl::StrCat("Stream ", stream_->id(), ": ", error_details); stream_->OnUnrecoverableError(read_error, details); return bytes_read; } stream_->AddBytesConsumed(bytes_read); return bytes_read; } bool QuicStreamSequencer::HasBytesToRead() const { return buffered_frames_.HasBytesToRead(); } size_t QuicStreamSequencer::ReadableBytes() const { return buffered_frames_.ReadableBytes(); } bool QuicStreamSequencer::IsClosed() const { return buffered_frames_.BytesConsumed() >= close_offset_; } void QuicStreamSequencer::MarkConsumed(size_t num_bytes_consumed) { QUICHE_DCHECK(!blocked_); bool result = buffered_frames_.MarkConsumed(num_bytes_consumed); if (!result) { QUIC_BUG(quic_bug_10858_2) << "Invalid argument to MarkConsumed." << " expect to consume: " << num_bytes_consumed << ", but not enough bytes available. " << DebugString(); stream_->ResetWithError( QuicResetStreamError::FromInternal(QUIC_ERROR_PROCESSING_STREAM)); return; } stream_->AddBytesConsumed(num_bytes_consumed); } void QuicStreamSequencer::SetBlockedUntilFlush() { blocked_ = true; } void QuicStreamSequencer::SetUnblocked() { blocked_ = false; if (IsClosed() || HasBytesToRead()) { stream_->OnDataAvailable(); } } void QuicStreamSequencer::StopReading() { if (ignore_read_data_) { return; } ignore_read_data_ = true; FlushBufferedFrames(); } void QuicStreamSequencer::ReleaseBuffer() { buffered_frames_.ReleaseWholeBuffer(); } void QuicStreamSequencer::ReleaseBufferIfEmpty() { if (buffered_frames_.Empty()) { buffered_frames_.ReleaseWholeBuffer(); } } void QuicStreamSequencer::FlushBufferedFrames() { QUICHE_DCHECK(ignore_read_data_); size_t bytes_flushed = buffered_frames_.FlushBufferedFrames(); QUIC_DVLOG(1) << "Flushing buffered data at offset " << buffered_frames_.BytesConsumed() << " length " << bytes_flushed << " for stream " << stream_->id(); stream_->AddBytesConsumed(bytes_flushed); MaybeCloseStream(); } size_t QuicStreamSequencer::NumBytesBuffered() const { return buffered_frames_.BytesBuffered(); } QuicStreamOffset QuicStreamSequencer::NumBytesConsumed() const { return buffered_frames_.BytesConsumed(); } bool QuicStreamSequencer::IsAllDataAvailable() const { QUICHE_DCHECK_LE(NumBytesConsumed() + NumBytesBuffered(), close_offset_); return NumBytesConsumed() + NumBytesBuffered() >= close_offset_; } std::string QuicStreamSequencer::DebugString() const { return absl::StrCat( "QuicStreamSequencer: bytes buffered: ", NumBytesBuffered(), "\n bytes consumed: ", NumBytesConsumed(), "\n first missing byte: ", buffered_frames_.FirstMissingByte(), "\n next expected byte: ", buffered_frames_.NextExpectedByte(), "\n received frames: ", buffered_frames_.ReceivedFramesDebugString(), "\n has bytes to read: ", HasBytesToRead() ? "true" : "false", "\n frames received: ", num_frames_received(), "\n close offset bytes: ", close_offset_, "\n is closed: ", IsClosed() ? "true" : "false"); } }
#include "quiche/quic/core/quic_stream_sequencer.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::AnyNumber; using testing::InSequence; namespace quic { namespace test { class MockStream : public QuicStreamSequencer::StreamInterface { public: MOCK_METHOD(void, OnFinRead, (), (override)); MOCK_METHOD(void, OnDataAvailable, (), (override)); MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode error, const std::string& details), (override)); MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details), (override)); MOCK_METHOD(void, ResetWithError, (QuicResetStreamError error), (override)); MOCK_METHOD(void, AddBytesConsumed, (QuicByteCount bytes), (override)); QuicStreamId id() const override { return 1; } ParsedQuicVersion version() const override { return CurrentSupportedVersions()[0]; } }; namespace { static const char kPayload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; class QuicStreamSequencerTest : public QuicTest { public: void ConsumeData(size_t num_bytes) { char buffer[1024]; ASSERT_GT(ABSL_ARRAYSIZE(buffer), num_bytes); struct iovec iov; iov.iov_base = buffer; iov.iov_len = num_bytes; ASSERT_EQ(num_bytes, sequencer_->Readv(&iov, 1)); } protected: QuicStreamSequencerTest() : stream_(), sequencer_(new QuicStreamSequencer(&stream_)) {} bool VerifyReadableRegion(const std::vector<std::string>& expected) { return VerifyReadableRegion(*sequencer_, expected); } bool VerifyReadableRegions(const std::vector<std::string>& expected) { return VerifyReadableRegions(*sequencer_, expected); } bool VerifyIovecs(iovec* iovecs, size_t num_iovecs, const std::vector<std::string>& expected) { return VerifyIovecs(*sequencer_, iovecs, num_iovecs, expected); } bool VerifyReadableRegion(const QuicStreamSequencer& sequencer, const std::vector<std::string>& expected) { iovec iovecs[1]; if (sequencer.GetReadableRegions(iovecs, 1)) { return (VerifyIovecs(sequencer, iovecs, 1, std::vector<std::string>{expected[0]})); } return false; } bool VerifyReadableRegions(const QuicStreamSequencer& sequencer, const std::vector<std::string>& expected) { iovec iovecs[5]; size_t num_iovecs = sequencer.GetReadableRegions(iovecs, ABSL_ARRAYSIZE(iovecs)); return VerifyReadableRegion(sequencer, expected) && VerifyIovecs(sequencer, iovecs, num_iovecs, expected); } bool VerifyIovecs(const QuicStreamSequencer& , iovec* iovecs, size_t num_iovecs, const std::vector<std::string>& expected) { int start_position = 0; for (size_t i = 0; i < num_iovecs; ++i) { if (!VerifyIovec(iovecs[i], expected[0].substr(start_position, iovecs[i].iov_len))) { return false; } start_position += iovecs[i].iov_len; } return true; } bool VerifyIovec(const iovec& iovec, absl::string_view expected) { if (iovec.iov_len != expected.length()) { QUIC_LOG(ERROR) << "Invalid length: " << iovec.iov_len << " vs " << expected.length(); return false; } if (memcmp(iovec.iov_base, expected.data(), expected.length()) != 0) { QUIC_LOG(ERROR) << "Invalid data: " << static_cast<char*>(iovec.iov_base) << " vs " << expected; return false; } return true; } void OnFinFrame(QuicStreamOffset byte_offset, const char* data) { QuicStreamFrame frame; frame.stream_id = 1; frame.offset = byte_offset; frame.data_buffer = data; frame.data_length = strlen(data); frame.fin = true; sequencer_->OnStreamFrame(frame); } void OnFrame(QuicStreamOffset byte_offset, const char* data) { QuicStreamFrame frame; frame.stream_id = 1; frame.offset = byte_offset; frame.data_buffer = data; frame.data_length = strlen(data); frame.fin = false; sequencer_->OnStreamFrame(frame); } size_t NumBufferedBytes() { return QuicStreamSequencerPeer::GetNumBufferedBytes(sequencer_.get()); } testing::StrictMock<MockStream> stream_; std::unique_ptr<QuicStreamSequencer> sequencer_; }; TEST_F(QuicStreamSequencerTest, RejectOldFrame) { EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); OnFrame(0, "abc"); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); OnFrame(0, "def"); EXPECT_EQ(0u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, RejectBufferedFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); OnFrame(0, "def"); EXPECT_EQ(3u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, FullFrameConsumed) { EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); OnFrame(0, "abc"); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) { sequencer_->SetBlockedUntilFlush(); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); sequencer_->SetUnblocked(); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_FALSE(sequencer_->IsAllDataAvailable()); OnFinFrame(3, "def"); EXPECT_TRUE(sequencer_->IsClosed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); } TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) { sequencer_->SetBlockedUntilFlush(); OnFinFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); sequencer_->SetUnblocked(); EXPECT_TRUE(sequencer_->IsClosed()); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, EmptyFrame) { if (!stream_.version().HasIetfQuicFrames()) { EXPECT_CALL(stream_, OnUnrecoverableError(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _)); } OnFrame(0, ""); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, EmptyFinFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFinFrame(0, ""); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); } TEST_F(QuicStreamSequencerTest, PartialFrameConsumed) { EXPECT_CALL(stream_, AddBytesConsumed(2)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(2); })); OnFrame(0, "abc"); EXPECT_EQ(1u, NumBufferedBytes()); EXPECT_EQ(2u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, NextxFrameNotConsumed) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, FutureFrameNotProcessed) { OnFrame(3, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, OutOfOrderFrameProcessed) { OnFrame(6, "ghi"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_EQ(3u, sequencer_->NumBytesBuffered()); OnFrame(3, "def"); EXPECT_EQ(6u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_EQ(6u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(9)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(9); })); OnFrame(0, "abc"); EXPECT_EQ(9u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); EXPECT_EQ(0u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, BasicHalfCloseOrdered) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFinFrame(0, "abc"); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); } TEST_F(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) { OnFinFrame(6, ""); EXPECT_EQ(6u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); OnFrame(3, "def"); EXPECT_CALL(stream_, AddBytesConsumed(6)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(6); })); EXPECT_FALSE(sequencer_->IsClosed()); OnFrame(0, "abc"); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, BasicHalfUnordered) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); OnFrame(0, "abc"); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, TerminateWithReadv) { char buffer[3]; OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_CALL(stream_, AddBytesConsumed(3)); iovec iov = {&buffer[0], 3}; int bytes_read = sequencer_->Readv(&iov, 1); EXPECT_EQ(3, bytes_read); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, MultipleOffsets) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received new final offset: 1, which is " "different from close offset: 3")); OnFinFrame(1, ""); } class QuicSequencerRandomTest : public QuicStreamSequencerTest { public: using Frame = std::pair<int, std::string>; using FrameList = std::vector<Frame>; void CreateFrames() { int payload_size = ABSL_ARRAYSIZE(kPayload) - 1; int remaining_payload = payload_size; while (remaining_payload != 0) { int size = std::min(OneToN(6), remaining_payload); int index = payload_size - remaining_payload; list_.push_back( std::make_pair(index, std::string(kPayload + index, size))); remaining_payload -= size; } } QuicSequencerRandomTest() { uint64_t seed = QuicRandom::GetInstance()->RandUint64(); QUIC_LOG(INFO) << "**** The current seed is " << seed << " ****"; random_.set_seed(seed); CreateFrames(); } int OneToN(int n) { return random_.RandUint64() % n + 1; } void ReadAvailableData() { char output[ABSL_ARRAYSIZE(kPayload) + 1]; iovec iov; iov.iov_base = output; iov.iov_len = ABSL_ARRAYSIZE(output); int bytes_read = sequencer_->Readv(&iov, 1); EXPECT_NE(0, bytes_read); output_.append(output, bytes_read); } std::string output_; std::string peeked_; SimpleRandom random_; FrameList list_; }; TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) { EXPECT_CALL(stream_, OnDataAvailable()) .Times(AnyNumber()) .WillRepeatedly( Invoke(this, &QuicSequencerRandomTest::ReadAvailableData)); QuicByteCount total_bytes_consumed = 0; EXPECT_CALL(stream_, AddBytesConsumed(_)) .Times(AnyNumber()) .WillRepeatedly( testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) { total_bytes_consumed += bytes; })); while (!list_.empty()) { int index = OneToN(list_.size()) - 1; QUIC_LOG(ERROR) << "Sending index " << index << " " << list_[index].second; OnFrame(list_[index].first, list_[index].second.data()); list_.erase(list_.begin() + index); } ASSERT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, output_.size()); EXPECT_EQ(kPayload, output_); EXPECT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, total_bytes_consumed); } TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) { char buffer[10]; iovec iov[2]; iov[0].iov_base = &buffer[0]; iov[0].iov_len = 5; iov[1].iov_base = &buffer[5]; iov[1].iov_len = 5; EXPECT_CALL(stream_, OnDataAvailable()).Times(AnyNumber()); QuicByteCount total_bytes_consumed = 0; EXPECT_CALL(stream_, AddBytesConsumed(_)) .Times(AnyNumber()) .WillRepeatedly( testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) { total_bytes_consumed += bytes; })); while (output_.size() != ABSL_ARRAYSIZE(kPayload) - 1) { if (!list_.empty() && OneToN(2) == 1) { int index = OneToN(list_.size()) - 1; OnFrame(list_[index].first, list_[index].second.data()); list_.erase(list_.begin() + index); } else { bool has_bytes = sequencer_->HasBytesToRead(); iovec peek_iov[20]; int iovs_peeked = sequencer_->GetReadableRegions(peek_iov, 20); if (has_bytes) { ASSERT_LT(0, iovs_peeked); ASSERT_TRUE(sequencer_->GetReadableRegion(peek_iov)); } else { ASSERT_EQ(0, iovs_peeked); ASSERT_FALSE(sequencer_->GetReadableRegion(peek_iov)); } int total_bytes_to_peek = ABSL_ARRAYSIZE(buffer); for (int i = 0; i < iovs_peeked; ++i) { int bytes_to_peek = std::min<int>(peek_iov[i].iov_len, total_bytes_to_peek); peeked_.append(static_cast<char*>(peek_iov[i].iov_base), bytes_to_peek); total_bytes_to_peek -= bytes_to_peek; if (total_bytes_to_peek == 0) { break; } } int bytes_read = sequencer_->Readv(iov, 2); output_.append(buffer, bytes_read); ASSERT_EQ(output_.size(), peeked_.size()); } } EXPECT_EQ(std::string(kPayload), output_); EXPECT_EQ(std::string(kPayload), peeked_); EXPECT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, total_bytes_consumed); } TEST_F(QuicStreamSequencerTest, MarkConsumed) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(6, "ghi"); EXPECT_EQ(9u, sequencer_->NumBytesBuffered()); std::vector<std::string> expected = {"abcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_CALL(stream_, AddBytesConsumed(1)); sequencer_->MarkConsumed(1); std::vector<std::string> expected2 = {"bcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected2)); EXPECT_EQ(8u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(2)); sequencer_->MarkConsumed(2); std::vector<std::string> expected3 = {"defghi"}; ASSERT_TRUE(VerifyReadableRegions(expected3)); EXPECT_EQ(6u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(5)); sequencer_->MarkConsumed(5); std::vector<std::string> expected4{"i"}; ASSERT_TRUE(VerifyReadableRegions(expected4)); EXPECT_EQ(1u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, MarkConsumedError) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(9, "jklmnopqrstuvwxyz"); std::vector<std::string> expected{"abc"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_QUIC_BUG( { EXPECT_CALL(stream_, ResetWithError(QuicResetStreamError::FromInternal( QUIC_ERROR_PROCESSING_STREAM))); sequencer_->MarkConsumed(4); }, "Invalid argument to MarkConsumed." " expect to consume: 4, but not enough bytes available."); } TEST_F(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(9, "jkl"); std::vector<std::string> expected = {"abcdef"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_CALL(stream_, AddBytesConsumed(6)); sequencer_->MarkConsumed(6); } TEST_F(QuicStreamSequencerTest, Move) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(6, "ghi"); EXPECT_EQ(9u, sequencer_->NumBytesBuffered()); std::vector<std::string> expected = {"abcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected)); QuicStreamSequencer sequencer2(std::move(*sequencer_)); ASSERT_TRUE(VerifyReadableRegions(sequencer2, expected)); } TEST_F(QuicStreamSequencerTest, OverlappingFramesReceived) { QuicStreamId id = 1; QuicStreamFrame frame1(id, false, 1, absl::string_view("hello")); sequencer_->OnStreamFrame(frame1); QuicStreamFrame frame2(id, false, 2, absl::string_view("hello")); EXPECT_CALL(stream_, OnUnrecoverableError(QUIC_OVERLAPPING_STREAM_DATA, _)) .Times(0); sequencer_->OnStreamFrame(frame2); } TEST_F(QuicStreamSequencerTest, DataAvailableOnOverlappingFrames) { QuicStreamId id = 1; const std::string data(1000, '.'); QuicStreamFrame frame1(id, false, 0, data); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame1); EXPECT_CALL(stream_, AddBytesConsumed(500)); QuicStreamSequencerTest::ConsumeData(500); EXPECT_EQ(500u, sequencer_->NumBytesConsumed()); EXPECT_EQ(500u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame2(id, false, 500, data); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame2); EXPECT_CALL(stream_, AddBytesConsumed(1000)); QuicStreamSequencerTest::ConsumeData(1000); EXPECT_EQ(1500u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame3(id, false, 1498, absl::string_view("hello")); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame3); EXPECT_CALL(stream_, AddBytesConsumed(3)); QuicStreamSequencerTest::ConsumeData(3); EXPECT_EQ(1503u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame4(id, false, 1000, absl::string_view("hello")); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame4); EXPECT_EQ(1503u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, OnDataAvailableWhenReadableBytesIncrease) { sequencer_->set_level_triggered(true); QuicStreamId id = 1; QuicStreamFrame frame1(id, false, 0, "hello"); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame1); EXPECT_EQ(5u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame2(id, false, 5, " world"); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame2); EXPECT_EQ(11u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame3(id, false, 5, "a"); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame3); EXPECT_EQ(11u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadSingleFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "abc"); std::string actual; EXPECT_CALL(stream_, AddBytesConsumed(3)); sequencer_->Read(&actual); EXPECT_EQ("abc", actual); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadMultipleFramesWithMissingFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "abc"); OnFrame(3u, "def"); OnFrame(6u, "ghi"); OnFrame(10u, "xyz"); std::string actual; EXPECT_CALL(stream_, AddBytesConsumed(9)); sequencer_->Read(&actual); EXPECT_EQ("abcdefghi", actual); EXPECT_EQ(3u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadAndAppendToString) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "def"); OnFrame(3u, "ghi"); std::string actual = "abc"; EXPECT_CALL(stream_, AddBytesConsumed(6)); sequencer_->Read(&actual); EXPECT_EQ("abcdefghi", actual); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, StopReading) { EXPECT_CALL(stream_, OnDataAvailable()).Times(0); EXPECT_CALL(stream_, OnFinRead()); EXPECT_CALL(stream_, AddBytesConsumed(0)); sequencer_->StopReading(); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFrame(0u, "abc"); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFrame(3u, "def"); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFinFrame(6u, "ghi"); } TEST_F(QuicStreamSequencerTest, StopReadingWithLevelTriggered) { EXPECT_CALL(stream_, AddBytesConsumed(0)); EXPECT_CALL(stream_, AddBytesConsumed(3)).Times(3); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); EXPECT_CALL(stream_, OnFinRead()); sequencer_->set_level_triggered(true); sequencer_->StopReading(); OnFrame(0u, "abc"); OnFrame(3u, "def"); OnFinFrame(6u, "ghi"); } TEST_F(QuicStreamSequencerTest, CorruptFinFrames) { EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received new final offset: 1, which is " "different from close offset: 2")); OnFinFrame(2u, ""); OnFinFrame(0u, "a"); EXPECT_FALSE(sequencer_->HasBytesToRead()); } TEST_F(QuicStreamSequencerTest, ReceiveFinLessThanHighestOffset) { EXPECT_CALL(stream_, OnDataAvailable()).Times(1); EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received fin with offset: 0, which " "reduces current highest offset: 3")); OnFrame(0u, "abc"); OnFinFrame(0u, ""); } } } }
267
cpp
google/quiche
web_transport_write_blocked_list
quiche/quic/core/web_transport_write_blocked_list.cc
quiche/quic/core/web_transport_write_blocked_list_test.cc
#ifndef QUICHE_QUIC_CORE_WEB_TRANSPORT_WRITE_BLOCKED_LIST_H_ #define QUICHE_QUIC_CORE_WEB_TRANSPORT_WRITE_BLOCKED_LIST_H_ #include <cstddef> #include <limits> #include <ostream> #include <string> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_write_blocked_list.h" #include "quiche/common/btree_scheduler.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/web_transport/web_transport.h" namespace quic { class QUICHE_EXPORT WebTransportWriteBlockedList : public QuicWriteBlockedListInterface { public: static constexpr int kStaticUrgency = HttpStreamPriority::kMaximumUrgency + 1; bool HasWriteBlockedDataStreams() const override; size_t NumBlockedSpecialStreams() const override; size_t NumBlockedStreams() const override; void RegisterStream(QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& raw_priority) override; void UnregisterStream(QuicStreamId stream_id) override; void UpdateStreamPriority(QuicStreamId stream_id, const QuicStreamPriority& new_priority) override; bool ShouldYield(QuicStreamId id) const override; QuicStreamPriority GetPriorityOfStream(QuicStreamId id) const override; QuicStreamId PopFront() override; void UpdateBytesForStream(QuicStreamId , size_t ) override {} void AddStream(QuicStreamId stream_id) override; bool IsStreamBlocked(QuicStreamId stream_id) const override; size_t NumRegisteredGroups() const { return web_transport_session_schedulers_.size(); } size_t NumRegisteredHttpStreams() const { return main_schedule_.NumRegistered() - NumRegisteredGroups(); } private: class QUICHE_EXPORT ScheduleKey { public: static ScheduleKey HttpStream(QuicStreamId id) { return ScheduleKey(id, kNoSendGroup); } static ScheduleKey WebTransportSession(QuicStreamId session_id, webtransport::SendGroupId group_id) { return ScheduleKey(session_id, group_id); } static ScheduleKey WebTransportSession(const QuicStreamPriority& priority) { return ScheduleKey(priority.web_transport().session_id, priority.web_transport().send_group_number); } bool operator==(const ScheduleKey& other) const { return stream_ == other.stream_ && group_ == other.group_; } bool operator!=(const ScheduleKey& other) const { return !(*this == other); } template <typename H> friend H AbslHashValue(H h, const ScheduleKey& key) { return H::combine(std::move(h), key.stream_, key.group_); } bool has_group() const { return group_ != kNoSendGroup; } quic::QuicStreamId stream() const { return stream_; } std::string DebugString() const; friend inline std::ostream& operator<<(std::ostream& os, const ScheduleKey& key) { os << key.DebugString(); return os; } private: static constexpr webtransport::SendGroupId kNoSendGroup = std::numeric_limits<webtransport::SendGroupId>::max(); explicit ScheduleKey(quic::QuicStreamId stream, webtransport::SendGroupId group) : stream_(stream), group_(group) {} quic::QuicStreamId stream_; webtransport::SendGroupId group_; }; static constexpr int RemapUrgency(int urgency, bool is_http) { return urgency * 2 + (is_http ? 1 : 0); } using Subscheduler = quiche::BTreeScheduler<QuicStreamId, webtransport::SendOrder>; quiche::BTreeScheduler<ScheduleKey, int> main_schedule_; absl::flat_hash_map<QuicStreamId, QuicStreamPriority> priorities_; absl::flat_hash_map<ScheduleKey, Subscheduler> web_transport_session_schedulers_; }; } #endif #include "quiche/quic/core/web_transport_write_blocked_list.h" #include <cstddef> #include <optional> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { bool WebTransportWriteBlockedList::HasWriteBlockedDataStreams() const { return main_schedule_.NumScheduledInPriorityRange( std::nullopt, RemapUrgency(HttpStreamPriority::kMaximumUrgency, true)) > 0; } size_t WebTransportWriteBlockedList::NumBlockedSpecialStreams() const { return main_schedule_.NumScheduledInPriorityRange( RemapUrgency(kStaticUrgency, false), std::nullopt); } size_t WebTransportWriteBlockedList::NumBlockedStreams() const { size_t num_streams = main_schedule_.NumScheduled(); for (const auto& [key, scheduler] : web_transport_session_schedulers_) { if (scheduler.HasScheduled()) { num_streams += scheduler.NumScheduled(); QUICHE_DCHECK(main_schedule_.IsScheduled(key)); --num_streams; } } return num_streams; } void WebTransportWriteBlockedList::RegisterStream( QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& raw_priority) { QuicStreamPriority priority = is_static_stream ? QuicStreamPriority(HttpStreamPriority{kStaticUrgency, true}) : raw_priority; auto [unused, success] = priorities_.emplace(stream_id, priority); if (!success) { QUICHE_BUG(WTWriteBlocked_RegisterStream_already_registered) << "Tried to register stream " << stream_id << " that is already registered"; return; } if (priority.type() == QuicPriorityType::kHttp) { absl::Status status = main_schedule_.Register( ScheduleKey::HttpStream(stream_id), RemapUrgency(priority.http().urgency, true)); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_http_scheduler, !status.ok()) << status; return; } QUICHE_DCHECK_EQ(priority.type(), QuicPriorityType::kWebTransport); ScheduleKey group_key = ScheduleKey::WebTransportSession(priority); auto [it, created_new] = web_transport_session_schedulers_.try_emplace(group_key); absl::Status status = it->second.Register(stream_id, priority.web_transport().send_order); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_data_scheduler, !status.ok()) << status; if (created_new) { auto session_priority_it = priorities_.find(priority.web_transport().session_id); QUICHE_DLOG_IF(WARNING, session_priority_it == priorities_.end()) << "Stream " << stream_id << " is associated with session ID " << priority.web_transport().session_id << ", but the session control stream is not registered; assuming " "default urgency."; QuicStreamPriority session_priority = session_priority_it != priorities_.end() ? session_priority_it->second : QuicStreamPriority(); status = main_schedule_.Register( group_key, RemapUrgency(session_priority.http().urgency, false)); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_main_scheduler, !status.ok()) << status; } } void WebTransportWriteBlockedList::UnregisterStream(QuicStreamId stream_id) { auto map_it = priorities_.find(stream_id); if (map_it == priorities_.end()) { QUICHE_BUG(WTWriteBlocked_UnregisterStream_not_found) << "Stream " << stream_id << " not found"; return; } QuicStreamPriority priority = map_it->second; priorities_.erase(map_it); if (priority.type() != QuicPriorityType::kWebTransport) { absl::Status status = main_schedule_.Unregister(ScheduleKey::HttpStream(stream_id)); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_http, !status.ok()) << status; return; } ScheduleKey key = ScheduleKey::WebTransportSession(priority); auto subscheduler_it = web_transport_session_schedulers_.find(key); if (subscheduler_it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_UnregisterStream_no_subscheduler) << "Stream " << stream_id << " is a WebTransport data stream, but has no scheduler for the " "associated group"; return; } Subscheduler& subscheduler = subscheduler_it->second; absl::Status status = subscheduler.Unregister(stream_id); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_subscheduler_stream_failed, !status.ok()) << status; if (!subscheduler.HasRegistered()) { status = main_schedule_.Unregister(key); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_subscheduler_failed, !status.ok()) << status; web_transport_session_schedulers_.erase(subscheduler_it); } } void WebTransportWriteBlockedList::UpdateStreamPriority( QuicStreamId stream_id, const QuicStreamPriority& new_priority) { UnregisterStream(stream_id); RegisterStream(stream_id, false, new_priority); if (new_priority.type() == QuicPriorityType::kHttp) { for (auto& [key, subscheduler] : web_transport_session_schedulers_) { QUICHE_DCHECK(key.has_group()); if (key.stream() == stream_id) { absl::Status status = main_schedule_.UpdatePriority(key, new_priority.http().urgency); QUICHE_BUG_IF(WTWriteBlocked_UpdateStreamPriority_subscheduler_failed, !status.ok()) << status; } } } } QuicStreamId WebTransportWriteBlockedList::PopFront() { absl::StatusOr<ScheduleKey> main_key = main_schedule_.PopFront(); if (!main_key.ok()) { QUICHE_BUG(WTWriteBlocked_PopFront_no_streams) << "PopFront() called when no streams scheduled: " << main_key.status(); return 0; } if (!main_key->has_group()) { return main_key->stream(); } auto it = web_transport_session_schedulers_.find(*main_key); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_PopFront_no_subscheduler) << "Subscheduler for WebTransport group " << main_key->DebugString() << " not found"; return 0; } Subscheduler& subscheduler = it->second; absl::StatusOr<QuicStreamId> result = subscheduler.PopFront(); if (!result.ok()) { QUICHE_BUG(WTWriteBlocked_PopFront_subscheduler_empty) << "Subscheduler for group " << main_key->DebugString() << " is empty while in the main schedule"; return 0; } if (subscheduler.HasScheduled()) { absl::Status status = main_schedule_.Schedule(*main_key); QUICHE_BUG_IF(WTWriteBlocked_PopFront_reschedule_group, !status.ok()) << status; } return *result; } void WebTransportWriteBlockedList::AddStream(QuicStreamId stream_id) { QuicStreamPriority priority = GetPriorityOfStream(stream_id); absl::Status status; switch (priority.type()) { case QuicPriorityType::kHttp: status = main_schedule_.Schedule(ScheduleKey::HttpStream(stream_id)); QUICHE_BUG_IF(WTWriteBlocked_AddStream_http, !status.ok()) << status; break; case QuicPriorityType::kWebTransport: status = main_schedule_.Schedule(ScheduleKey::WebTransportSession(priority)); QUICHE_BUG_IF(WTWriteBlocked_AddStream_wt_main, !status.ok()) << status; auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_AddStream_no_subscheduler) << ScheduleKey::WebTransportSession(priority); return; } Subscheduler& subscheduler = it->second; status = subscheduler.Schedule(stream_id); QUICHE_BUG_IF(WTWriteBlocked_AddStream_wt_sub, !status.ok()) << status; break; } } bool WebTransportWriteBlockedList::IsStreamBlocked( QuicStreamId stream_id) const { QuicStreamPriority priority = GetPriorityOfStream(stream_id); switch (priority.type()) { case QuicPriorityType::kHttp: return main_schedule_.IsScheduled(ScheduleKey::HttpStream(stream_id)); case QuicPriorityType::kWebTransport: auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_IsStreamBlocked_no_subscheduler) << ScheduleKey::WebTransportSession(priority); return false; } const Subscheduler& subscheduler = it->second; return subscheduler.IsScheduled(stream_id); } QUICHE_NOTREACHED(); return false; } QuicStreamPriority WebTransportWriteBlockedList::GetPriorityOfStream( QuicStreamId id) const { auto it = priorities_.find(id); if (it == priorities_.end()) { QUICHE_BUG(WTWriteBlocked_GetPriorityOfStream_not_found) << "Stream " << id << " not found"; return QuicStreamPriority(); } return it->second; } std::string WebTransportWriteBlockedList::ScheduleKey::DebugString() const { return absl::StrFormat("(%d, %d)", stream_, group_); } bool WebTransportWriteBlockedList::ShouldYield(QuicStreamId id) const { QuicStreamPriority priority = GetPriorityOfStream(id); if (priority.type() == QuicPriorityType::kHttp) { absl::StatusOr<bool> should_yield = main_schedule_.ShouldYield(ScheduleKey::HttpStream(id)); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_http, !should_yield.ok()) << should_yield.status(); return *should_yield; } QUICHE_DCHECK_EQ(priority.type(), QuicPriorityType::kWebTransport); absl::StatusOr<bool> should_yield = main_schedule_.ShouldYield(ScheduleKey::WebTransportSession(priority)); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_wt_main, !should_yield.ok()) << should_yield.status(); if (*should_yield) { return true; } auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_ShouldYield_subscheduler_not_found) << "Subscheduler not found for " << ScheduleKey::WebTransportSession(priority); return false; } const Subscheduler& subscheduler = it->second; should_yield = subscheduler.ShouldYield(id); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_wt_subscheduler, !should_yield.ok()) << should_yield.status(); return *should_yield; } }
#include "quiche/quic/core/web_transport_write_blocked_list.h" #include <algorithm> #include <array> #include <cstddef> #include <iterator> #include <vector> #include "absl/algorithm/container.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic::test { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; class WebTransportWriteBlockedListTest : public ::quiche::test::QuicheTest { protected: void RegisterStaticStream(QuicStreamId id) { list_.RegisterStream(id, true, QuicStreamPriority()); } void RegisterHttpStream(QuicStreamId id, int urgency = HttpStreamPriority::kDefaultUrgency) { HttpStreamPriority priority; priority.urgency = urgency; list_.RegisterStream(id, false, QuicStreamPriority(priority)); } void RegisterWebTransportDataStream(QuicStreamId id, WebTransportStreamPriority priority) { list_.RegisterStream(id, false, QuicStreamPriority(priority)); } std::vector<QuicStreamId> PopAll() { std::vector<QuicStreamId> result; size_t expected_count = list_.NumBlockedStreams(); while (list_.NumBlockedStreams() > 0) { EXPECT_TRUE(list_.HasWriteBlockedDataStreams() || list_.HasWriteBlockedSpecialStream()); result.push_back(list_.PopFront()); EXPECT_EQ(list_.NumBlockedStreams(), --expected_count); } return result; } WebTransportWriteBlockedList list_; }; TEST_F(WebTransportWriteBlockedListTest, BasicHttpStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterHttpStream(3, HttpStreamPriority::kDefaultUrgency + 1); RegisterStaticStream(4); EXPECT_EQ(list_.GetPriorityOfStream(1), QuicStreamPriority()); EXPECT_EQ(list_.GetPriorityOfStream(2), QuicStreamPriority()); EXPECT_EQ(list_.GetPriorityOfStream(3).http().urgency, 4); EXPECT_EQ(list_.NumBlockedStreams(), 0); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 0); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 1); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 1, 2)); EXPECT_EQ(list_.NumBlockedStreams(), 0); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 0); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 2, 1)); } TEST_F(WebTransportWriteBlockedListTest, RegisterDuplicateStream) { RegisterHttpStream(1); EXPECT_QUICHE_BUG(RegisterHttpStream(1), "already registered"); } TEST_F(WebTransportWriteBlockedListTest, UnregisterMissingStream) { EXPECT_QUICHE_BUG(list_.UnregisterStream(1), "not found"); } TEST_F(WebTransportWriteBlockedListTest, GetPriorityMissingStream) { EXPECT_QUICHE_BUG(list_.GetPriorityOfStream(1), "not found"); } TEST_F(WebTransportWriteBlockedListTest, PopFrontMissing) { RegisterHttpStream(1); list_.AddStream(1); EXPECT_EQ(list_.PopFront(), 1); EXPECT_QUICHE_BUG(list_.PopFront(), "no streams scheduled"); } TEST_F(WebTransportWriteBlockedListTest, HasWriteBlockedDataStreams) { RegisterStaticStream(1); RegisterHttpStream(2); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); list_.AddStream(1); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); list_.AddStream(2); EXPECT_TRUE(list_.HasWriteBlockedDataStreams()); EXPECT_EQ(list_.PopFront(), 1); EXPECT_TRUE(list_.HasWriteBlockedDataStreams()); EXPECT_EQ(list_.PopFront(), 2); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); } TEST_F(WebTransportWriteBlockedListTest, NestedStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(5); list_.AddStream(4); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 5, 4, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(3, 5, 4)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(4); list_.AddStream(5); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(6, 3, 5, 4)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(5); list_.AddStream(4); list_.AddStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(6, 4, 5, 3)); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsWithHigherPriorityGroup) { RegisterHttpStream(1, HttpStreamPriority::kDefaultUrgency + 1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(5); list_.AddStream(4); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(4); list_.AddStream(5); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 6, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(5); list_.AddStream(4); list_.AddStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 6, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamVsControlStream) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 2)); list_.AddStream(1); list_.AddStream(2); EXPECT_THAT(PopAll(), ElementsAre(1, 2)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsSendOrder) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 100}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, -100}); list_.AddStream(4); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 3, 2, 4)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsDifferentGroups) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 1, 100}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 7, -100}); list_.AddStream(4); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 4, 3, 2)); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3, 4)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsDifferentSession) { RegisterWebTransportDataStream(1, WebTransportStreamPriority{10, 0, 0}); RegisterWebTransportDataStream(2, WebTransportStreamPriority{11, 0, 100}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{12, 0, -100}); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(3, 2, 1)); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); } TEST_F(WebTransportWriteBlockedListTest, UnregisterScheduledStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); for (QuicStreamId id : {1, 2, 3, 4, 5, 6}) { list_.AddStream(id); } EXPECT_EQ(list_.NumBlockedStreams(), 6); list_.UnregisterStream(1); EXPECT_EQ(list_.NumBlockedStreams(), 5); list_.UnregisterStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); list_.UnregisterStream(4); EXPECT_EQ(list_.NumBlockedStreams(), 3); list_.UnregisterStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 2); list_.UnregisterStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 1); list_.UnregisterStream(2); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, UnregisterUnscheduledStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 2); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(1); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(3); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(4); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 1); list_.UnregisterStream(5); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 1); list_.UnregisterStream(6); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 0); list_.UnregisterStream(2); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 0); EXPECT_EQ(list_.NumRegisteredGroups(), 0); RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); } TEST_F(WebTransportWriteBlockedListTest, IsStreamBlocked) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{9, 0, 0}); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_FALSE(list_.IsStreamBlocked(3)); list_.AddStream(3); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); list_.AddStream(1); EXPECT_TRUE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); ASSERT_EQ(list_.PopFront(), 1); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityHttp) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterHttpStream(3); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority( HttpStreamPriority{HttpStreamPriority::kMaximumUrgency, false})); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(2, 1, 3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityWebTransport) { RegisterWebTransportDataStream(1, WebTransportStreamPriority{0, 0, 0}); RegisterWebTransportDataStream(2, WebTransportStreamPriority{0, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{0, 0, 0}); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority(WebTransportStreamPriority{0, 0, 1})); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(2, 1, 3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityControlStream) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{2, 0, 0}); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(3, 4)); list_.AddStream(4); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority( HttpStreamPriority{HttpStreamPriority::kMaximumUrgency, false})); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); list_.AddStream(4); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); } TEST_F(WebTransportWriteBlockedListTest, ShouldYield) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 10}); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_FALSE(list_.ShouldYield(2)); EXPECT_FALSE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); list_.AddStream(1); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_TRUE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_TRUE(list_.ShouldYield(4)); PopAll(); list_.AddStream(2); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_FALSE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); PopAll(); list_.AddStream(4); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_TRUE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); PopAll(); } TEST_F(WebTransportWriteBlockedListTest, RandomizedTest) { RegisterHttpStream(1); RegisterHttpStream(2, HttpStreamPriority::kMinimumUrgency); RegisterHttpStream(3, HttpStreamPriority::kMaximumUrgency); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, +1}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, -1}); RegisterWebTransportDataStream(7, WebTransportStreamPriority{3, 8, 0}); RegisterWebTransportDataStream(8, WebTransportStreamPriority{3, 8, 100}); RegisterWebTransportDataStream(9, WebTransportStreamPriority{3, 8, 20000}); RegisterHttpStream(10, HttpStreamPriority::kDefaultUrgency + 1); constexpr std::array<QuicStreamId, 10> order = {3, 9, 8, 7, 10, 1, 4, 2, 5, 6}; SimpleRandom random; for (int i = 0; i < 1000; ++i) { std::vector<QuicStreamId> pushed_streams(order.begin(), order.end()); for (int j = pushed_streams.size() - 1; j > 0; --j) { std::swap(pushed_streams[j], pushed_streams[random.RandUint64() % (j + 1)]); } size_t stream_count = 1 + random.RandUint64() % order.size(); pushed_streams.resize(stream_count); for (QuicStreamId id : pushed_streams) { list_.AddStream(id); } std::vector<QuicStreamId> expected_streams; absl::c_copy_if( order, std::back_inserter(expected_streams), [&](QuicStreamId id) { return absl::c_find(pushed_streams, id) != pushed_streams.end(); }); ASSERT_THAT(PopAll(), ElementsAreArray(expected_streams)); } } } }
268
cpp
google/quiche
quic_coalesced_packet
quiche/quic/core/quic_coalesced_packet.cc
quiche/quic/core/quic_coalesced_packet_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_COALESCED_PACKET_H_ #define QUICHE_QUIC_CORE_QUIC_COALESCED_PACKET_H_ #include "quiche/quic/core/quic_packets.h" namespace quic { namespace test { class QuicCoalescedPacketPeer; } class QUICHE_EXPORT QuicCoalescedPacket { public: QuicCoalescedPacket(); ~QuicCoalescedPacket(); bool MaybeCoalescePacket(const SerializedPacket& packet, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, quiche::QuicheBufferAllocator* allocator, QuicPacketLength current_max_packet_length, QuicEcnCodepoint ecn_codepoint); void Clear(); void NeuterInitialPacket(); bool CopyEncryptedBuffers(char* buffer, size_t buffer_len, size_t* length_copied) const; std::string ToString(size_t serialized_length) const; bool ContainsPacketOfEncryptionLevel(EncryptionLevel level) const; TransmissionType TransmissionTypeOfPacket(EncryptionLevel level) const; size_t NumberOfPackets() const; const SerializedPacket* initial_packet() const { return initial_packet_.get(); } const QuicSocketAddress& self_address() const { return self_address_; } const QuicSocketAddress& peer_address() const { return peer_address_; } QuicPacketLength length() const { return length_; } QuicPacketLength max_packet_length() const { return max_packet_length_; } std::vector<size_t> packet_lengths() const; QuicEcnCodepoint ecn_codepoint() const { return ecn_codepoint_; } private: friend class test::QuicCoalescedPacketPeer; QuicSocketAddress self_address_; QuicSocketAddress peer_address_; QuicPacketLength length_; QuicPacketLength max_packet_length_; std::string encrypted_buffers_[NUM_ENCRYPTION_LEVELS]; TransmissionType transmission_types_[NUM_ENCRYPTION_LEVELS]; std::unique_ptr<SerializedPacket> initial_packet_; QuicEcnCodepoint ecn_codepoint_; }; } #endif #include "quiche/quic/core/quic_coalesced_packet.h" #include <string> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { QuicCoalescedPacket::QuicCoalescedPacket() : length_(0), max_packet_length_(0), ecn_codepoint_(ECN_NOT_ECT) {} QuicCoalescedPacket::~QuicCoalescedPacket() { Clear(); } bool QuicCoalescedPacket::MaybeCoalescePacket( const SerializedPacket& packet, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, quiche::QuicheBufferAllocator* allocator, QuicPacketLength current_max_packet_length, QuicEcnCodepoint ecn_codepoint) { if (packet.encrypted_length == 0) { QUIC_BUG(quic_bug_10611_1) << "Trying to coalesce an empty packet"; return true; } if (length_ == 0) { #ifndef NDEBUG for (const auto& buffer : encrypted_buffers_) { QUICHE_DCHECK(buffer.empty()); } #endif QUICHE_DCHECK(initial_packet_ == nullptr); max_packet_length_ = current_max_packet_length; self_address_ = self_address; peer_address_ = peer_address; } else { if (self_address_ != self_address || peer_address_ != peer_address) { QUIC_DLOG(INFO) << "Cannot coalesce packet because self/peer address changed"; return false; } if (max_packet_length_ != current_max_packet_length) { QUIC_BUG(quic_bug_10611_2) << "Max packet length changes in the middle of the write path"; return false; } if (ContainsPacketOfEncryptionLevel(packet.encryption_level)) { return false; } if (ecn_codepoint != ecn_codepoint_) { return false; } } if (length_ + packet.encrypted_length > max_packet_length_) { return false; } QUIC_DVLOG(1) << "Successfully coalesced packet: encryption_level: " << packet.encryption_level << ", encrypted_length: " << packet.encrypted_length << ", current length: " << length_ << ", max_packet_length: " << max_packet_length_; if (length_ > 0) { QUIC_CODE_COUNT(QUIC_SUCCESSFULLY_COALESCED_MULTIPLE_PACKETS); } ecn_codepoint_ = ecn_codepoint; length_ += packet.encrypted_length; transmission_types_[packet.encryption_level] = packet.transmission_type; if (packet.encryption_level == ENCRYPTION_INITIAL) { initial_packet_ = absl::WrapUnique<SerializedPacket>( CopySerializedPacket(packet, allocator, false)); return true; } encrypted_buffers_[packet.encryption_level] = std::string(packet.encrypted_buffer, packet.encrypted_length); return true; } void QuicCoalescedPacket::Clear() { self_address_ = QuicSocketAddress(); peer_address_ = QuicSocketAddress(); length_ = 0; max_packet_length_ = 0; for (auto& packet : encrypted_buffers_) { packet.clear(); } for (size_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { transmission_types_[i] = NOT_RETRANSMISSION; } initial_packet_ = nullptr; } void QuicCoalescedPacket::NeuterInitialPacket() { if (initial_packet_ == nullptr) { return; } if (length_ < initial_packet_->encrypted_length) { QUIC_BUG(quic_bug_10611_3) << "length_: " << length_ << ", is less than initial packet length: " << initial_packet_->encrypted_length; Clear(); return; } length_ -= initial_packet_->encrypted_length; if (length_ == 0) { Clear(); return; } transmission_types_[ENCRYPTION_INITIAL] = NOT_RETRANSMISSION; initial_packet_ = nullptr; } bool QuicCoalescedPacket::CopyEncryptedBuffers(char* buffer, size_t buffer_len, size_t* length_copied) const { *length_copied = 0; for (const auto& packet : encrypted_buffers_) { if (packet.empty()) { continue; } if (packet.length() > buffer_len) { return false; } memcpy(buffer, packet.data(), packet.length()); buffer += packet.length(); buffer_len -= packet.length(); *length_copied += packet.length(); } return true; } bool QuicCoalescedPacket::ContainsPacketOfEncryptionLevel( EncryptionLevel level) const { return !encrypted_buffers_[level].empty() || (level == ENCRYPTION_INITIAL && initial_packet_ != nullptr); } TransmissionType QuicCoalescedPacket::TransmissionTypeOfPacket( EncryptionLevel level) const { if (!ContainsPacketOfEncryptionLevel(level)) { QUIC_BUG(quic_bug_10611_4) << "Coalesced packet does not contain packet of encryption level: " << EncryptionLevelToString(level); return NOT_RETRANSMISSION; } return transmission_types_[level]; } size_t QuicCoalescedPacket::NumberOfPackets() const { size_t num_of_packets = 0; for (int8_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { if (ContainsPacketOfEncryptionLevel(static_cast<EncryptionLevel>(i))) { ++num_of_packets; } } return num_of_packets; } std::string QuicCoalescedPacket::ToString(size_t serialized_length) const { std::string info = absl::StrCat( "total_length: ", serialized_length, " padding_size: ", serialized_length - length_, " packets: {"); bool first_packet = true; for (int8_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { if (ContainsPacketOfEncryptionLevel(static_cast<EncryptionLevel>(i))) { absl::StrAppend(&info, first_packet ? "" : ", ", EncryptionLevelToString(static_cast<EncryptionLevel>(i))); first_packet = false; } } absl::StrAppend(&info, "}"); return info; } std::vector<size_t> QuicCoalescedPacket::packet_lengths() const { std::vector<size_t> lengths; for (const auto& packet : encrypted_buffers_) { if (lengths.empty()) { lengths.push_back( initial_packet_ == nullptr ? 0 : initial_packet_->encrypted_length); } else { lengths.push_back(packet.length()); } } return lengths; } }
#include "quiche/quic/core/quic_coalesced_packet.h" #include <string> #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { TEST(QuicCoalescedPacketTest, MaybeCoalescePacket) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ(0u, coalesced.NumberOfPackets()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(PTO_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_INITIAL)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ(1u, coalesced.NumberOfPackets()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_INITIAL}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet3(QuicPacketNumber(3), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet3.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet3.encryption_level = ENCRYPTION_ZERO_RTT; packet3.transmission_type = LOSS_RETRANSMISSION; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet3, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(LOSS_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_ZERO_RTT)); EXPECT_EQ( "total_length: 1500 padding_size: 500 packets: {ENCRYPTION_INITIAL, " "ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet4(QuicPacketNumber(4), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet4.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet4, QuicSocketAddress(QuicIpAddress::Loopback4(), 3), peer_address, &allocator, 1500, ECN_NOT_ECT)); SerializedPacket packet5(QuicPacketNumber(5), PACKET_4BYTE_PACKET_NUMBER, buffer, 501, false, false); packet5.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet5, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet6(QuicPacketNumber(6), PACKET_4BYTE_PACKET_NUMBER, buffer, 100, false, false); packet6.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_QUIC_BUG( coalesced.MaybeCoalescePacket(packet6, self_address, peer_address, &allocator, 1000, ECN_NOT_ECT), "Max packet length changes in the middle of the write path"); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); } TEST(QuicCoalescedPacketTest, CopyEncryptedBuffers) { QuicCoalescedPacket coalesced; quiche::SimpleBufferAllocator allocator; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); std::string buffer(500, 'a'); std::string buffer2(500, 'b'); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer.data(), 500, false, false); packet1.encryption_level = ENCRYPTION_ZERO_RTT; SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer2.data(), 500, false, false); packet2.encryption_level = ENCRYPTION_FORWARD_SECURE; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); char copy_buffer[1000]; size_t length_copied = 0; EXPECT_FALSE( coalesced.CopyEncryptedBuffers(copy_buffer, 900, &length_copied)); ASSERT_TRUE( coalesced.CopyEncryptedBuffers(copy_buffer, 1000, &length_copied)); EXPECT_EQ(1000u, length_copied); char expected[1000]; memset(expected, 'a', 500); memset(expected + 500, 'b', 500); quiche::test::CompareCharArraysWithHexError("copied buffers", copy_buffer, length_copied, expected, 1000); } TEST(QuicCoalescedPacketTest, NeuterInitialPacket) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); coalesced.NeuterInitialPacket(); EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(PTO_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_INITIAL)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_INITIAL}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(0u, coalesced.max_packet_length()); EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); SerializedPacket packet2(QuicPacketNumber(3), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet2.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet2.encryption_level = ENCRYPTION_ZERO_RTT; packet2.transmission_type = LOSS_RETRANSMISSION; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(LOSS_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_ZERO_RTT)); EXPECT_EQ( "total_length: 1500 padding_size: 500 packets: {ENCRYPTION_INITIAL, " "ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet3(QuicPacketNumber(5), PACKET_4BYTE_PACKET_NUMBER, buffer, 501, false, false); packet3.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_TRUE(coalesced.MaybeCoalescePacket(packet3, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1001u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1001u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); } TEST(QuicCoalescedPacketTest, DoNotCoalesceDifferentEcn) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ(0u, coalesced.NumberOfPackets()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_ECT1)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_ECT1); SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet2.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet2.encryption_level = ENCRYPTION_ZERO_RTT; packet2.transmission_type = LOSS_RETRANSMISSION; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_ECT1); } } } }
269
cpp
google/quiche
quic_received_packet_manager
quiche/quic/core/quic_received_packet_manager.cc
quiche/quic/core/quic_received_packet_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_RECEIVED_PACKET_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_RECEIVED_PACKET_MANAGER_H_ #include <cstddef> #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class RttStats; namespace test { class QuicConnectionPeer; class QuicReceivedPacketManagerPeer; class UberReceivedPacketManagerPeer; } struct QuicConnectionStats; class QUICHE_EXPORT QuicReceivedPacketManager { public: QuicReceivedPacketManager(); explicit QuicReceivedPacketManager(QuicConnectionStats* stats); QuicReceivedPacketManager(const QuicReceivedPacketManager&) = delete; QuicReceivedPacketManager& operator=(const QuicReceivedPacketManager&) = delete; virtual ~QuicReceivedPacketManager(); void SetFromConfig(const QuicConfig& config, Perspective perspective); virtual void RecordPacketReceived(const QuicPacketHeader& header, QuicTime receipt_time, QuicEcnCodepoint ecn); virtual bool IsMissing(QuicPacketNumber packet_number); virtual bool IsAwaitingPacket(QuicPacketNumber packet_number) const; const QuicFrame GetUpdatedAckFrame(QuicTime approximate_now); void DontWaitForPacketsBefore(QuicPacketNumber least_unacked); void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats); void ResetAckStates(); bool HasMissingPackets() const; virtual bool HasNewMissingPackets() const; virtual bool ack_frame_updated() const; QuicPacketNumber GetLargestObserved() const; QuicPacketNumber PeerFirstSendingPacketNumber() const; bool IsAckFrameEmpty() const; void set_connection_stats(QuicConnectionStats* stats) { stats_ = stats; } const QuicAckFrame& ack_frame() const { return ack_frame_; } void set_max_ack_ranges(size_t max_ack_ranges) { max_ack_ranges_ = max_ack_ranges; } void set_save_timestamps(bool save_timestamps, bool in_order_packets_only) { save_timestamps_ = save_timestamps; save_timestamps_for_in_order_packets_ = in_order_packets_only; } size_t min_received_before_ack_decimation() const { return min_received_before_ack_decimation_; } void set_min_received_before_ack_decimation(size_t new_value) { min_received_before_ack_decimation_ = new_value; } void set_ack_frequency(size_t new_value) { QUICHE_DCHECK_GT(new_value, 0u); ack_frequency_ = new_value; } void set_local_max_ack_delay(QuicTime::Delta local_max_ack_delay) { local_max_ack_delay_ = local_max_ack_delay; } QuicTime ack_timeout() const { return ack_timeout_; } void OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame); private: friend class test::QuicConnectionPeer; friend class test::QuicReceivedPacketManagerPeer; friend class test::UberReceivedPacketManagerPeer; void MaybeUpdateAckTimeoutTo(QuicTime time); void MaybeUpdateAckFrequency(QuicPacketNumber last_received_packet_number); QuicTime::Delta GetMaxAckDelay(QuicPacketNumber last_received_packet_number, const RttStats& rtt_stats) const; bool AckFrequencyFrameReceived() const { return last_ack_frequency_frame_sequence_number_ >= 0; } void MaybeTrimAckRanges(); QuicPacketNumber peer_least_packet_awaiting_ack_; QuicAckFrame ack_frame_; bool ack_frame_updated_; size_t max_ack_ranges_; QuicTime time_largest_observed_; bool save_timestamps_; bool save_timestamps_for_in_order_packets_; QuicPacketNumber least_received_packet_number_; QuicConnectionStats* stats_; QuicPacketCount num_retransmittable_packets_received_since_last_ack_sent_; size_t min_received_before_ack_decimation_; size_t ack_frequency_; float ack_decimation_delay_; bool unlimited_ack_decimation_; bool one_immediate_ack_; bool ignore_order_; QuicTime::Delta local_max_ack_delay_; QuicTime ack_timeout_; QuicTime time_of_previous_received_packet_; bool was_last_packet_missing_; QuicPacketNumber last_sent_largest_acked_; int64_t last_ack_frequency_frame_sequence_number_; }; } #endif #include "quiche/quic/core/quic_received_packet_manager.h" #include <algorithm> #include <limits> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const size_t kMaxPacketsAfterNewMissing = 4; const float kShortAckDecimationDelay = 0.125; } QuicReceivedPacketManager::QuicReceivedPacketManager() : QuicReceivedPacketManager(nullptr) {} QuicReceivedPacketManager::QuicReceivedPacketManager(QuicConnectionStats* stats) : ack_frame_updated_(false), max_ack_ranges_(0), time_largest_observed_(QuicTime::Zero()), save_timestamps_(false), save_timestamps_for_in_order_packets_(false), stats_(stats), num_retransmittable_packets_received_since_last_ack_sent_(0), min_received_before_ack_decimation_(kMinReceivedBeforeAckDecimation), ack_frequency_(kDefaultRetransmittablePacketsBeforeAck), ack_decimation_delay_(GetQuicFlag(quic_ack_decimation_delay)), unlimited_ack_decimation_(false), one_immediate_ack_(false), ignore_order_(false), local_max_ack_delay_( QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs())), ack_timeout_(QuicTime::Zero()), time_of_previous_received_packet_(QuicTime::Zero()), was_last_packet_missing_(false), last_ack_frequency_frame_sequence_number_(-1) {} QuicReceivedPacketManager::~QuicReceivedPacketManager() {} void QuicReceivedPacketManager::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (config.HasClientSentConnectionOption(kAKD3, perspective)) { ack_decimation_delay_ = kShortAckDecimationDelay; } if (config.HasClientSentConnectionOption(kAKDU, perspective)) { unlimited_ack_decimation_ = true; } if (config.HasClientSentConnectionOption(k1ACK, perspective)) { one_immediate_ack_ = true; } } void QuicReceivedPacketManager::RecordPacketReceived( const QuicPacketHeader& header, QuicTime receipt_time, const QuicEcnCodepoint ecn) { const QuicPacketNumber packet_number = header.packet_number; QUICHE_DCHECK(IsAwaitingPacket(packet_number)) << " packet_number:" << packet_number; was_last_packet_missing_ = IsMissing(packet_number); if (!ack_frame_updated_) { ack_frame_.received_packet_times.clear(); } ack_frame_updated_ = true; bool packet_reordered = false; if (LargestAcked(ack_frame_).IsInitialized() && LargestAcked(ack_frame_) > packet_number) { packet_reordered = true; ++stats_->packets_reordered; stats_->max_sequence_reordering = std::max(stats_->max_sequence_reordering, LargestAcked(ack_frame_) - packet_number); int64_t reordering_time_us = (receipt_time - time_largest_observed_).ToMicroseconds(); stats_->max_time_reordering_us = std::max(stats_->max_time_reordering_us, reordering_time_us); } if (!LargestAcked(ack_frame_).IsInitialized() || packet_number > LargestAcked(ack_frame_)) { ack_frame_.largest_acked = packet_number; time_largest_observed_ = receipt_time; } ack_frame_.packets.Add(packet_number); MaybeTrimAckRanges(); if (save_timestamps_) { if (save_timestamps_for_in_order_packets_ && packet_reordered) { QUIC_DLOG(WARNING) << "Not saving receive timestamp for packet " << packet_number; } else if (!ack_frame_.received_packet_times.empty() && ack_frame_.received_packet_times.back().second > receipt_time) { QUIC_LOG(WARNING) << "Receive time went backwards from: " << ack_frame_.received_packet_times.back().second.ToDebuggingValue() << " to " << receipt_time.ToDebuggingValue(); } else { ack_frame_.received_packet_times.push_back( std::make_pair(packet_number, receipt_time)); } } if (ecn != ECN_NOT_ECT) { if (!ack_frame_.ecn_counters.has_value()) { ack_frame_.ecn_counters = QuicEcnCounts(); } switch (ecn) { case ECN_NOT_ECT: QUICHE_NOTREACHED(); break; case ECN_ECT0: ack_frame_.ecn_counters->ect0++; break; case ECN_ECT1: ack_frame_.ecn_counters->ect1++; break; case ECN_CE: ack_frame_.ecn_counters->ce++; break; } } if (least_received_packet_number_.IsInitialized()) { least_received_packet_number_ = std::min(least_received_packet_number_, packet_number); } else { least_received_packet_number_ = packet_number; } } void QuicReceivedPacketManager::MaybeTrimAckRanges() { while (max_ack_ranges_ > 0 && ack_frame_.packets.NumIntervals() > max_ack_ranges_) { ack_frame_.packets.RemoveSmallestInterval(); } } bool QuicReceivedPacketManager::IsMissing(QuicPacketNumber packet_number) { return LargestAcked(ack_frame_).IsInitialized() && packet_number < LargestAcked(ack_frame_) && !ack_frame_.packets.Contains(packet_number); } bool QuicReceivedPacketManager::IsAwaitingPacket( QuicPacketNumber packet_number) const { return quic::IsAwaitingPacket(ack_frame_, packet_number, peer_least_packet_awaiting_ack_); } const QuicFrame QuicReceivedPacketManager::GetUpdatedAckFrame( QuicTime approximate_now) { if (time_largest_observed_ == QuicTime::Zero()) { ack_frame_.ack_delay_time = QuicTime::Delta::Infinite(); } else { ack_frame_.ack_delay_time = approximate_now < time_largest_observed_ ? QuicTime::Delta::Zero() : approximate_now - time_largest_observed_; } const size_t initial_ack_ranges = ack_frame_.packets.NumIntervals(); uint64_t num_iterations = 0; while (max_ack_ranges_ > 0 && ack_frame_.packets.NumIntervals() > max_ack_ranges_) { num_iterations++; QUIC_BUG_IF(quic_rpm_too_many_ack_ranges, (num_iterations % 100000) == 0) << "Too many ack ranges to remove, possibly a dead loop. " "initial_ack_ranges:" << initial_ack_ranges << " max_ack_ranges:" << max_ack_ranges_ << ", current_ack_ranges:" << ack_frame_.packets.NumIntervals() << " num_iterations:" << num_iterations; ack_frame_.packets.RemoveSmallestInterval(); } for (auto it = ack_frame_.received_packet_times.begin(); it != ack_frame_.received_packet_times.end();) { if (LargestAcked(ack_frame_) - it->first >= std::numeric_limits<uint8_t>::max()) { it = ack_frame_.received_packet_times.erase(it); } else { ++it; } } #if QUIC_FRAME_DEBUG QuicFrame frame = QuicFrame(&ack_frame_); frame.delete_forbidden = true; return frame; #else return QuicFrame(&ack_frame_); #endif } void QuicReceivedPacketManager::DontWaitForPacketsBefore( QuicPacketNumber least_unacked) { if (!least_unacked.IsInitialized()) { return; } QUICHE_DCHECK(!peer_least_packet_awaiting_ack_.IsInitialized() || peer_least_packet_awaiting_ack_ <= least_unacked); if (!peer_least_packet_awaiting_ack_.IsInitialized() || least_unacked > peer_least_packet_awaiting_ack_) { peer_least_packet_awaiting_ack_ = least_unacked; bool packets_updated = ack_frame_.packets.RemoveUpTo(least_unacked); if (packets_updated) { ack_frame_updated_ = true; } } QUICHE_DCHECK(ack_frame_.packets.Empty() || !peer_least_packet_awaiting_ack_.IsInitialized() || ack_frame_.packets.Min() >= peer_least_packet_awaiting_ack_); } QuicTime::Delta QuicReceivedPacketManager::GetMaxAckDelay( QuicPacketNumber last_received_packet_number, const RttStats& rtt_stats) const { if (AckFrequencyFrameReceived() || last_received_packet_number < PeerFirstSendingPacketNumber() + min_received_before_ack_decimation_) { return local_max_ack_delay_; } QuicTime::Delta ack_delay = std::min( local_max_ack_delay_, rtt_stats.min_rtt() * ack_decimation_delay_); return std::max(ack_delay, kAlarmGranularity); } void QuicReceivedPacketManager::MaybeUpdateAckFrequency( QuicPacketNumber last_received_packet_number) { if (AckFrequencyFrameReceived()) { return; } if (last_received_packet_number < PeerFirstSendingPacketNumber() + min_received_before_ack_decimation_) { return; } ack_frequency_ = unlimited_ack_decimation_ ? std::numeric_limits<size_t>::max() : kMaxRetransmittablePacketsBeforeAck; } void QuicReceivedPacketManager::MaybeUpdateAckTimeout( bool should_last_packet_instigate_acks, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats) { if (!ack_frame_updated_) { return; } if (!ignore_order_ && was_last_packet_missing_ && last_sent_largest_acked_.IsInitialized() && last_received_packet_number < last_sent_largest_acked_) { ack_timeout_ = now; return; } if (!should_last_packet_instigate_acks) { return; } ++num_retransmittable_packets_received_since_last_ack_sent_; MaybeUpdateAckFrequency(last_received_packet_number); if (num_retransmittable_packets_received_since_last_ack_sent_ >= ack_frequency_) { ack_timeout_ = now; return; } if (!ignore_order_ && HasNewMissingPackets()) { ack_timeout_ = now; return; } const QuicTime updated_ack_time = std::max( now, std::min(last_packet_receipt_time, now) + GetMaxAckDelay(last_received_packet_number, *rtt_stats)); if (!ack_timeout_.IsInitialized() || ack_timeout_ > updated_ack_time) { ack_timeout_ = updated_ack_time; } } void QuicReceivedPacketManager::ResetAckStates() { ack_frame_updated_ = false; ack_timeout_ = QuicTime::Zero(); num_retransmittable_packets_received_since_last_ack_sent_ = 0; last_sent_largest_acked_ = LargestAcked(ack_frame_); } bool QuicReceivedPacketManager::HasMissingPackets() const { if (ack_frame_.packets.Empty()) { return false; } if (ack_frame_.packets.NumIntervals() > 1) { return true; } return peer_least_packet_awaiting_ack_.IsInitialized() && ack_frame_.packets.Min() > peer_least_packet_awaiting_ack_; } bool QuicReceivedPacketManager::HasNewMissingPackets() const { if (one_immediate_ack_) { return HasMissingPackets() && ack_frame_.packets.LastIntervalLength() == 1; } return HasMissingPackets() && ack_frame_.packets.LastIntervalLength() <= kMaxPacketsAfterNewMissing; } bool QuicReceivedPacketManager::ack_frame_updated() const { return ack_frame_updated_; } QuicPacketNumber QuicReceivedPacketManager::GetLargestObserved() const { return LargestAcked(ack_frame_); } QuicPacketNumber QuicReceivedPacketManager::PeerFirstSendingPacketNumber() const { if (!least_received_packet_number_.IsInitialized()) { QUIC_BUG(quic_bug_10849_1) << "No packets have been received yet"; return QuicPacketNumber(1); } return least_received_packet_number_; } bool QuicReceivedPacketManager::IsAckFrameEmpty() const { return ack_frame_.packets.Empty(); } void QuicReceivedPacketManager::OnAckFrequencyFrame( const QuicAckFrequencyFrame& frame) { int64_t new_sequence_number = frame.sequence_number; if (new_sequence_number <= last_ack_frequency_frame_sequence_number_) { return; } last_ack_frequency_frame_sequence_number_ = new_sequence_number; ack_frequency_ = frame.packet_tolerance; local_max_ack_delay_ = frame.max_ack_delay; ignore_order_ = frame.ignore_order; } }
#include "quiche/quic/core/quic_received_packet_manager.h" #include <algorithm> #include <cstddef> #include <ostream> #include <vector> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class QuicReceivedPacketManagerPeer { public: static void SetOneImmediateAck(QuicReceivedPacketManager* manager, bool one_immediate_ack) { manager->one_immediate_ack_ = one_immediate_ack; } static void SetAckDecimationDelay(QuicReceivedPacketManager* manager, float ack_decimation_delay) { manager->ack_decimation_delay_ = ack_decimation_delay; } }; namespace { const bool kInstigateAck = true; const QuicTime::Delta kMinRttMs = QuicTime::Delta::FromMilliseconds(40); const QuicTime::Delta kDelayedAckTime = QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); class QuicReceivedPacketManagerTest : public QuicTest { protected: QuicReceivedPacketManagerTest() : received_manager_(&stats_) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); rtt_stats_.UpdateRtt(kMinRttMs, QuicTime::Delta::Zero(), QuicTime::Zero()); received_manager_.set_save_timestamps(true, false); } void RecordPacketReceipt(uint64_t packet_number) { RecordPacketReceipt(packet_number, QuicTime::Zero()); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time) { RecordPacketReceipt(packet_number, receipt_time, ECN_NOT_ECT); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time, QuicEcnCodepoint ecn_codepoint) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(packet_number); received_manager_.RecordPacketReceived(header, receipt_time, ecn_codepoint); } bool HasPendingAck() { return received_manager_.ack_timeout().IsInitialized(); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, uint64_t last_received_packet_number) { received_manager_.MaybeUpdateAckTimeout( should_last_packet_instigate_acks, QuicPacketNumber(last_received_packet_number), clock_.ApproximateNow(), clock_.ApproximateNow(), &rtt_stats_); } void CheckAckTimeout(QuicTime time) { QUICHE_DCHECK(HasPendingAck()); QUICHE_DCHECK_EQ(received_manager_.ack_timeout(), time); if (time <= clock_.ApproximateNow()) { received_manager_.ResetAckStates(); QUICHE_DCHECK(!HasPendingAck()); } } MockClock clock_; RttStats rtt_stats_; QuicConnectionStats stats_; QuicReceivedPacketManager received_manager_; }; TEST_F(QuicReceivedPacketManagerTest, DontWaitForPacketsBefore) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(2u); received_manager_.RecordPacketReceived(header, QuicTime::Zero(), ECN_NOT_ECT); header.packet_number = QuicPacketNumber(7u); received_manager_.RecordPacketReceived(header, QuicTime::Zero(), ECN_NOT_ECT); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(3u))); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(6u))); received_manager_.DontWaitForPacketsBefore(QuicPacketNumber(4)); EXPECT_FALSE(received_manager_.IsAwaitingPacket(QuicPacketNumber(3u))); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(6u))); } TEST_F(QuicReceivedPacketManagerTest, GetUpdatedAckFrame) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(2u); QuicTime two_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_FALSE(received_manager_.ack_frame_updated()); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); EXPECT_TRUE(received_manager_.ack_frame_updated()); QuicFrame ack = received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(QuicTime::Delta::Zero(), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); QuicTime four_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(4); ack = received_manager_.GetUpdatedAckFrame(four_ms); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); header.packet_number = QuicPacketNumber(999u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); header.packet_number = QuicPacketNumber(4u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); header.packet_number = QuicPacketNumber(1000u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); EXPECT_TRUE(received_manager_.ack_frame_updated()); ack = received_manager_.GetUpdatedAckFrame(two_ms); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(2u, ack.ack_frame->received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, UpdateReceivedConnectionStats) { EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1); EXPECT_TRUE(received_manager_.ack_frame_updated()); RecordPacketReceipt(6); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(4u, stats_.max_sequence_reordering); EXPECT_EQ(1000, stats_.max_time_reordering_us); EXPECT_EQ(1u, stats_.packets_reordered); } TEST_F(QuicReceivedPacketManagerTest, LimitAckRanges) { received_manager_.set_max_ack_ranges(10); EXPECT_FALSE(received_manager_.ack_frame_updated()); for (int i = 0; i < 100; ++i) { RecordPacketReceipt(1 + 2 * i); EXPECT_TRUE(received_manager_.ack_frame_updated()); received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); EXPECT_GE(10u, received_manager_.ack_frame().packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(1u + 2 * i), received_manager_.ack_frame().packets.Max()); for (int j = 0; j < std::min(10, i + 1); ++j) { ASSERT_GE(i, j); EXPECT_TRUE(received_manager_.ack_frame().packets.Contains( QuicPacketNumber(1 + (i - j) * 2))); if (i > j) { EXPECT_FALSE(received_manager_.ack_frame().packets.Contains( QuicPacketNumber((i - j) * 2))); } } } } TEST_F(QuicReceivedPacketManagerTest, TrimAckRangesEarly) { const size_t kMaxAckRanges = 10; received_manager_.set_max_ack_ranges(kMaxAckRanges); for (size_t i = 0; i < kMaxAckRanges + 10; ++i) { RecordPacketReceipt(1 + 2 * i); if (i < kMaxAckRanges) { EXPECT_EQ(i + 1, received_manager_.ack_frame().packets.NumIntervals()); } else { EXPECT_EQ(kMaxAckRanges, received_manager_.ack_frame().packets.NumIntervals()); } } } TEST_F(QuicReceivedPacketManagerTest, IgnoreOutOfOrderTimestamps) { EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(received_manager_.ack_frame_updated()); EXPECT_EQ(1u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, IgnoreOutOfOrderPackets) { received_manager_.set_save_timestamps(true, true); EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(received_manager_.ack_frame_updated()); EXPECT_EQ(1u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(4, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(3)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, HasMissingPackets) { EXPECT_QUIC_BUG(received_manager_.PeerFirstSendingPacketNumber(), "No packets have been received yet"); RecordPacketReceipt(4, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(4), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_FALSE(received_manager_.HasMissingPackets()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_FALSE(received_manager_.HasMissingPackets()); EXPECT_EQ(QuicPacketNumber(3), received_manager_.PeerFirstSendingPacketNumber()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(1), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_TRUE(received_manager_.HasMissingPackets()); RecordPacketReceipt(2, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(1), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_FALSE(received_manager_.HasMissingPackets()); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(6, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 6); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent1Ack) { QuicReceivedPacketManagerPeer::SetOneImmediateAck(&received_manager_, true); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(6, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 6); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderAckReceiptCausesNoAck) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); } TEST_F(QuicReceivedPacketManagerTest, AckReceiptCausesAckSend) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); clock_.AdvanceTime(kDelayedAckTime); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 4); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 5); EXPECT_FALSE(HasPendingAck()); } TEST_F(QuicReceivedPacketManagerTest, AckSentEveryNthPacket) { EXPECT_FALSE(HasPendingAck()); received_manager_.set_ack_frequency(3); for (size_t i = 1; i <= 39; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(QuicReceivedPacketManagerTest, AckDecimationReducesAcks) { EXPECT_FALSE(HasPendingAck()); received_manager_.set_min_received_before_ack_decimation(10); for (size_t i = 1; i <= 29; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i <= 10) { if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } continue; } if (i == 20) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kMinRttMs * 0.25); } } RecordPacketReceipt(30, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 30); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimation) { EXPECT_FALSE(HasPendingAck()); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationMin1ms) { EXPECT_FALSE(HasPendingAck()); rtt_stats_.UpdateRtt(kAlarmGranularity, QuicTime::Delta::Zero(), clock_.ApproximateNow()); QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationUnlimitedAggregation) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kAKDU); config.SetConnectionOptionsToSend(connection_options); received_manager_.SetFromConfig(config, Perspective::IS_CLIENT); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (int i = 1; i <= 18; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(ack_time); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationEighthRtt) { EXPECT_FALSE(HasPendingAck()); QuicReceivedPacketManagerPeer::SetAckDecimationDelay(&received_manager_, 0.125); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.125; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, UpdateMaxAckDelayAndAckFrequencyFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = QuicTime::Delta::FromMilliseconds(10); frame.packet_tolerance = 5; received_manager_.OnAckFrequencyFrame(frame); for (int i = 1; i <= 50; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % frame.packet_tolerance == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + frame.max_ack_delay); } } } TEST_F(QuicReceivedPacketManagerTest, DisableOutOfOrderAckByIgnoreOrderFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 2; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, DisableMissingPaketsAckByIgnoreOrderFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; config.SetConnectionOptionsToSend({kAFFE}); received_manager_.SetFromConfig(config, Perspective::IS_CLIENT); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 2; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, AckDecimationDisabledWhenAckFrequencyFrameIsReceived) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 3; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); uint64_t kFirstDecimatedPacket = 101; uint64_t FiftyPacketsAfterAckDecimation = kFirstDecimatedPacket + 50; for (uint64_t i = 1; i < FiftyPacketsAfterAckDecimation; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(QuicReceivedPacketManagerTest, UpdateAckTimeoutOnPacketReceiptTime) { EXPECT_FALSE(HasPendingAck()); QuicTime packet_receipt_time3 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); RecordPacketReceipt(3, packet_receipt_time3); received_manager_.MaybeUpdateAckTimeout( kInstigateAck, QuicPacketNumber(3), packet_receipt_time3, clock_.ApproximateNow(), &rtt_stats_); CheckAckTimeout(packet_receipt_time3 + kDelayedAckTime); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, UpdateAckTimeoutOnPacketReceiptTimeLongerQueuingTime) { EXPECT_FALSE(HasPendingAck()); QuicTime packet_receipt_time3 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); RecordPacketReceipt(3, packet_receipt_time3); received_manager_.MaybeUpdateAckTimeout( kInstigateAck, QuicPacketNumber(3), packet_receipt_time3, clock_.ApproximateNow(), &rtt_stats_); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, CountEcnPackets) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, QuicTime::Zero(), ECN_NOT_ECT); RecordPacketReceipt(4, QuicTime::Zero(), ECN_ECT0); RecordPacketReceipt(5, QuicTime::Zero(), ECN_ECT1); RecordPacketReceipt(6, QuicTime::Zero(), ECN_CE); QuicFrame ack = received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); EXPECT_TRUE(ack.ack_frame->ecn_counters.has_value()); EXPECT_EQ(ack.ack_frame->ecn_counters->ect0, 1); EXPECT_EQ(ack.ack_frame->ecn_counters->ect1, 1); EXPECT_EQ(ack.ack_frame->ecn_counters->ce, 1); } } } }
270
cpp
google/quiche
quic_sent_packet_manager
quiche/quic/core/quic_sent_packet_manager.cc
quiche/quic/core/quic_sent_packet_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_SENT_PACKET_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_SENT_PACKET_MANAGER_H_ #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/congestion_control/pacing_sender.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/congestion_control/uber_loss_algorithm.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_sustained_bandwidth_recorder.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_transmission_info.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_unacked_packet_map.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class QuicConnectionPeer; class QuicSentPacketManagerPeer; } class QuicClock; class QuicConfig; struct QuicConnectionStats; class QUICHE_EXPORT QuicSentPacketManager { public: class QUICHE_EXPORT DebugDelegate { public: struct QUICHE_EXPORT SendParameters { CongestionControlType congestion_control_type; bool use_pacing; QuicPacketCount initial_congestion_window; }; virtual ~DebugDelegate() {} virtual void OnSpuriousPacketRetransmission( TransmissionType , QuicByteCount ) {} virtual void OnIncomingAck(QuicPacketNumber , EncryptionLevel , const QuicAckFrame& , QuicTime , QuicPacketNumber , bool , QuicPacketNumber ) { } virtual void OnPacketLoss(QuicPacketNumber , EncryptionLevel , TransmissionType , QuicTime ) {} virtual void OnApplicationLimited() {} virtual void OnAdjustNetworkParameters(QuicBandwidth , QuicTime::Delta , QuicByteCount , QuicByteCount ) {} virtual void OnOvershootingDetected() {} virtual void OnConfigProcessed(const SendParameters& ) {} virtual void OnSendAlgorithmChanged(CongestionControlType ) {} }; class QUICHE_EXPORT NetworkChangeVisitor { public: virtual ~NetworkChangeVisitor() {} virtual void OnCongestionChange() = 0; virtual void OnPathMtuIncreased(QuicPacketLength packet_size) = 0; virtual void OnInFlightEcnPacketAcked() = 0; virtual void OnInvalidEcnFeedback() = 0; }; enum RetransmissionTimeoutMode { HANDSHAKE_MODE, LOSS_MODE, PTO_MODE, }; QuicSentPacketManager(Perspective perspective, const QuicClock* clock, QuicRandom* random, QuicConnectionStats* stats, CongestionControlType congestion_control_type); QuicSentPacketManager(const QuicSentPacketManager&) = delete; QuicSentPacketManager& operator=(const QuicSentPacketManager&) = delete; virtual ~QuicSentPacketManager(); virtual void SetFromConfig(const QuicConfig& config); void ReserveUnackedPacketsInitialCapacity(int initial_capacity) { unacked_packets_.ReserveInitialCapacity(initial_capacity); } void ApplyConnectionOptions(const QuicTagVector& connection_options); void ResumeConnectionState( const CachedNetworkParameters& cached_network_params, bool max_bandwidth_resumption); void SetMaxPacingRate(QuicBandwidth max_pacing_rate) { pacing_sender_.set_max_pacing_rate(max_pacing_rate); } QuicTime::Delta GetDeferredSendAlarmDelay() const { return deferred_send_alarm_delay_.value_or(QuicTime::Delta::Zero()); } void SetDeferredSendAlarmDelay(QuicTime::Delta delay) { deferred_send_alarm_delay_ = delay; } QuicBandwidth MaxPacingRate() const { return pacing_sender_.max_pacing_rate(); } void SetHandshakeConfirmed(); void MarkZeroRttPacketsForRetransmission(); void MarkInitialPacketsForRetransmission(); void AdjustNetworkParameters( const SendAlgorithmInterface::NetworkParams& params); void SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner); void OnConfigNegotiated(); void OnConnectionClosed(); bool MaybeRetransmitOldestPacket(TransmissionType type); void NeuterUnencryptedPackets(); bool HasUnackedCryptoPackets() const { return unacked_packets_.HasPendingCryptoPackets(); } bool HasInFlightPackets() const { return unacked_packets_.HasInFlightPackets(); } QuicPacketNumber GetLeastUnacked() const { return unacked_packets_.GetLeastUnacked(); } bool OnPacketSent(SerializedPacket* mutable_packet, QuicTime sent_time, TransmissionType transmission_type, HasRetransmittableData has_retransmittable_data, bool measure_rtt, QuicEcnCodepoint ecn_codepoint); bool CanSendAckFrequency() const; QuicAckFrequencyFrame GetUpdatedAckFrequencyFrame() const; RetransmissionTimeoutMode OnRetransmissionTimeout(); QuicTime::Delta TimeUntilSend(QuicTime now) const; const QuicTime GetRetransmissionTime() const; const QuicTime::Delta GetPathDegradingDelay() const; const QuicTime::Delta GetNetworkBlackholeDelay( int8_t num_rtos_for_blackhole_detection) const; QuicTime::Delta GetMtuReductionDelay( int8_t num_rtos_for_blackhole_detection) const; const RttStats* GetRttStats() const { return &rtt_stats_; } void SetRttStats(const RttStats& rtt_stats) { rtt_stats_.CloneFrom(rtt_stats); } QuicBandwidth BandwidthEstimate() const { return send_algorithm_->BandwidthEstimate(); } const QuicSustainedBandwidthRecorder* SustainedBandwidthRecorder() const { return &sustained_bandwidth_recorder_; } QuicPacketCount GetCongestionWindowInTcpMss() const { return send_algorithm_->GetCongestionWindow() / kDefaultTCPMSS; } QuicPacketCount EstimateMaxPacketsInFlight( QuicByteCount max_packet_length) const { return send_algorithm_->GetCongestionWindow() / max_packet_length; } QuicByteCount GetCongestionWindowInBytes() const { return send_algorithm_->GetCongestionWindow(); } QuicByteCount GetAvailableCongestionWindowInBytes() const; QuicBandwidth GetPacingRate() const { return send_algorithm_->PacingRate(GetBytesInFlight()); } QuicPacketCount GetSlowStartThresholdInTcpMss() const { return send_algorithm_->GetSlowStartThreshold() / kDefaultTCPMSS; } QuicTime::Delta GetSlowStartDuration() const; std::string GetDebugState() const; QuicByteCount GetBytesInFlight() const { return unacked_packets_.bytes_in_flight(); } std::unique_ptr<SendAlgorithmInterface> OnConnectionMigration( bool reset_send_algorithm); void OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time, QuicTime ack_receive_time); void OnAckRange(QuicPacketNumber start, QuicPacketNumber end); void OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp); AckResult OnAckFrameEnd(QuicTime ack_receive_time, QuicPacketNumber ack_packet_number, EncryptionLevel ack_decrypted_level, const std::optional<QuicEcnCounts>& ecn_counts); void EnableMultiplePacketNumberSpacesSupport(); void SetDebugDelegate(DebugDelegate* debug_delegate); QuicPacketNumber GetLargestObserved() const { return unacked_packets_.largest_acked(); } QuicPacketNumber GetLargestAckedPacket( EncryptionLevel decrypted_packet_level) const; QuicPacketNumber GetLargestSentPacket() const { return unacked_packets_.largest_sent_packet(); } QuicPacketNumber GetLeastPacketAwaitedByPeer( EncryptionLevel encryption_level) const; QuicPacketNumber GetLargestPacketPeerKnowsIsAcked( EncryptionLevel decrypted_packet_level) const; void SetNetworkChangeVisitor(NetworkChangeVisitor* visitor) { QUICHE_DCHECK(!network_change_visitor_); QUICHE_DCHECK(visitor); network_change_visitor_ = visitor; } bool InSlowStart() const { return send_algorithm_->InSlowStart(); } size_t GetConsecutivePtoCount() const { return consecutive_pto_count_; } void OnApplicationLimited(); const SendAlgorithmInterface* GetSendAlgorithm() const { return send_algorithm_.get(); } bool EnableECT0() { return send_algorithm_->EnableECT0(); } bool EnableECT1() { return send_algorithm_->EnableECT1(); } void SetSessionNotifier(SessionNotifierInterface* session_notifier) { unacked_packets_.SetSessionNotifier(session_notifier); } NextReleaseTimeResult GetNextReleaseTime() const; QuicPacketCount initial_congestion_window() const { return initial_congestion_window_; } QuicPacketNumber largest_packet_peer_knows_is_acked() const { QUICHE_DCHECK(!supports_multiple_packet_number_spaces()); return largest_packet_peer_knows_is_acked_; } size_t pending_timer_transmission_count() const { return pending_timer_transmission_count_; } QuicTime::Delta peer_max_ack_delay() const { return peer_max_ack_delay_; } void set_peer_max_ack_delay(QuicTime::Delta peer_max_ack_delay) { QUICHE_DCHECK_LE( peer_max_ack_delay, (QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs) * 0.5)); peer_max_ack_delay_ = peer_max_ack_delay; } const QuicUnackedPacketMap& unacked_packets() const { return unacked_packets_; } const UberLossAlgorithm* uber_loss_algorithm() const { return &uber_loss_algorithm_; } void SetSendAlgorithm(CongestionControlType congestion_control_type); void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm); void MaybeSendProbePacket(); void EnableIetfPtoAndLossDetection(); void RetransmitDataOfSpaceIfAny(PacketNumberSpace space); bool IsLessThanThreePTOs(QuicTime::Delta timeout) const; QuicTime::Delta GetPtoDelay() const; bool supports_multiple_packet_number_spaces() const { return unacked_packets_.supports_multiple_packet_number_spaces(); } bool handshake_mode_disabled() const { return handshake_mode_disabled_; } bool zero_rtt_packet_acked() const { return zero_rtt_packet_acked_; } bool one_rtt_packet_acked() const { return one_rtt_packet_acked_; } void OnUserAgentIdKnown() { loss_algorithm_->OnUserAgentIdKnown(); } QuicTime GetEarliestPacketSentTimeForPto( PacketNumberSpace* packet_number_space) const; void set_num_ptos_for_path_degrading(int num_ptos_for_path_degrading) { num_ptos_for_path_degrading_ = num_ptos_for_path_degrading; } void SetInitialRtt(QuicTime::Delta rtt, bool trusted); private: friend class test::QuicConnectionPeer; friend class test::QuicSentPacketManagerPeer; RetransmissionTimeoutMode GetRetransmissionMode() const; void RetransmitCryptoPackets(); const QuicTime::Delta GetCryptoRetransmissionDelay() const; const QuicTime::Delta GetProbeTimeoutDelay(PacketNumberSpace space) const; bool MaybeUpdateRTT(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time, QuicTime ack_receive_time); void InvokeLossDetection(QuicTime time); void MaybeInvokeCongestionEvent(bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, std::optional<QuicEcnCounts> ecn_counts, const QuicEcnCounts& previous_counts); void MarkPacketHandled(QuicPacketNumber packet_number, QuicTransmissionInfo* info, QuicTime ack_receive_time, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp); void MarkForRetransmission(QuicPacketNumber packet_number, TransmissionType transmission_type); void PostProcessNewlyAckedPackets(QuicPacketNumber ack_packet_number, EncryptionLevel ack_decrypted_level, const QuicAckFrame& ack_frame, QuicTime ack_receive_time, bool rtt_updated, QuicByteCount prior_bytes_in_flight, std::optional<QuicEcnCounts> ecn_counts); void RecordOneSpuriousRetransmission(const QuicTransmissionInfo& info); void NeuterHandshakePackets(); bool ShouldAddMaxAckDelay(PacketNumberSpace space) const; QuicTime::Delta GetNConsecutiveRetransmissionTimeoutDelay( int num_timeouts) const; bool PeerCompletedAddressValidation() const; void OnAckFrequencyFrameSent( const QuicAckFrequencyFrame& ack_frequency_frame); void OnAckFrequencyFrameAcked( const QuicAckFrequencyFrame& ack_frequency_frame); bool IsEcnFeedbackValid(PacketNumberSpace space, const std::optional<QuicEcnCounts>& ecn_counts, QuicPacketCount newly_acked_ect0, QuicPacketCount newly_acked_ect1); void RecordEcnMarkingSent(QuicEcnCodepoint ecn_codepoint, EncryptionLevel level); QuicUnackedPacketMap unacked_packets_; const QuicClock* clock_; QuicRandom* random_; QuicConnectionStats* stats_; DebugDelegate* debug_delegate_; NetworkChangeVisitor* network_change_visitor_; QuicPacketCount initial_congestion_window_; RttStats rtt_stats_; std::unique_ptr<SendAlgorithmInterface> send_algorithm_; LossDetectionInterface* loss_algorithm_; UberLossAlgorithm uber_loss_algorithm_; size_t consecutive_crypto_retransmission_count_; size_t pending_timer_transmission_count_; bool using_pacing_; bool conservative_handshake_retransmits_; AckedPacketVector packets_acked_; LostPacketVector packets_lost_; QuicPacketNumber largest_newly_acked_; QuicPacketLength largest_mtu_acked_; PacingSender pacing_sender_; bool handshake_finished_; QuicSustainedBandwidthRecorder sustained_bandwidth_recorder_; QuicPacketNumber largest_packet_peer_knows_is_acked_; QuicPacketNumber largest_packets_peer_knows_is_acked_[NUM_PACKET_NUMBER_SPACES]; QuicTime::Delta peer_max_ack_delay_; QuicTime::Delta peer_min_ack_delay_ = QuicTime::Delta::Infinite(); bool use_smoothed_rtt_in_ack_delay_ = false; quiche::QuicheCircularDeque< std::pair<QuicTime::Delta, uint64_t>> in_use_sent_ack_delays_; QuicAckFrame last_ack_frame_; bool rtt_updated_; PacketNumberQueue::const_reverse_iterator acked_packets_iter_; size_t consecutive_pto_count_; bool handshake_mode_disabled_; bool handshake_packet_acked_; bool zero_rtt_packet_acked_; bool one_rtt_packet_acked_; int num_ptos_for_path_degrading_; bool ignore_pings_; bool ignore_ack_delay_; QuicPacketCount ect0_packets_sent_[NUM_PACKET_NUMBER_SPACES] = {0, 0, 0}; QuicPacketCount ect1_packets_sent_[NUM_PACKET_NUMBER_SPACES] = {0, 0, 0}; QuicEcnCounts peer_ack_ecn_counts_[NUM_PACKET_NUMBER_SPACES]; std::optional<QuicTime::Delta> deferred_send_alarm_delay_; }; } #endif #include "quiche/quic/core/quic_sent_packet_manager.h" #include <algorithm> #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/congestion_control/general_loss_algorithm.h" #include "quiche/quic/core/congestion_control/pacing_sender.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_transmission_info.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/print_elements.h" namespace quic { namespace { static const int64_t kDefaultRetransmissionTimeMs = 500; static const int64_t kMinHandshakeTimeoutMs = 10; static const size_t kDefaultMaxTailLossProbes = 2; static const float kPtoMultiplierWithoutRttSamples = 3; inline bool ShouldForceRetransmission(TransmissionType transmission_type) { return transmission_type == HANDSHAKE_RETRANSMISSION || transmission_type == PTO_RETRANSMISSION; } static const uint32_t kConservativeUnpacedBurst = 2; static const uint32_t kNumProbeTimeoutsForPathDegradingDelay = 4; } #define ENDPOINT \ (unacked_packets_.perspective() == Perspective::IS_SERVER ? "Server: " \ : "Client: ") QuicSentPacketManager::QuicSentPacketManager( Perspective perspective, const QuicClock* clock, QuicRand
#include "quiche/quic/core/quic_sent_packet_manager.h" #include <algorithm> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_mem_slice.h" using testing::_; using testing::AnyNumber; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::IsEmpty; using testing::Not; using testing::Pointwise; using testing::Return; using testing::StrictMock; using testing::WithArgs; namespace quic { namespace test { namespace { const uint32_t kDefaultLength = 1000; const QuicStreamId kStreamId = 7; const std::optional<QuicEcnCounts> kEmptyCounts = std::nullopt; MATCHER(PacketNumberEq, "") { return std::get<0>(arg).packet_number == QuicPacketNumber(std::get<1>(arg)); } class MockDebugDelegate : public QuicSentPacketManager::DebugDelegate { public: MOCK_METHOD(void, OnSpuriousPacketRetransmission, (TransmissionType transmission_type, QuicByteCount byte_size), (override)); MOCK_METHOD(void, OnPacketLoss, (QuicPacketNumber lost_packet_number, EncryptionLevel encryption_level, TransmissionType transmission_type, QuicTime detection_time), (override)); }; class QuicSentPacketManagerTest : public QuicTest { public: bool RetransmitCryptoPacket(uint64_t packet_number) { EXPECT_CALL( *send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), kDefaultLength, HAS_RETRANSMITTABLE_DATA)); SerializedPacket packet(CreatePacket(packet_number, false)); packet.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, false, 0, absl::string_view()))); packet.has_crypto_handshake = IS_HANDSHAKE; manager_.OnPacketSent(&packet, clock_.Now(), HANDSHAKE_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); return true; } bool RetransmitDataPacket(uint64_t packet_number, TransmissionType type, EncryptionLevel level) { EXPECT_CALL( *send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), kDefaultLength, HAS_RETRANSMITTABLE_DATA)); SerializedPacket packet(CreatePacket(packet_number, true)); packet.encryption_level = level; manager_.OnPacketSent(&packet, clock_.Now(), type, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); return true; } bool RetransmitDataPacket(uint64_t packet_number, TransmissionType type) { return RetransmitDataPacket(packet_number, type, ENCRYPTION_INITIAL); } protected: const CongestionControlType kInitialCongestionControlType = kCubicBytes; QuicSentPacketManagerTest() : manager_(Perspective::IS_SERVER, &clock_, QuicRandom::GetInstance(), &stats_, kInitialCongestionControlType), send_algorithm_(new StrictMock<MockSendAlgorithm>), network_change_visitor_(new StrictMock<MockNetworkChangeVisitor>) { QuicSentPacketManagerPeer::SetSendAlgorithm(&manager_, send_algorithm_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1000)); manager_.SetNetworkChangeVisitor(network_change_visitor_.get()); manager_.SetSessionNotifier(&notifier_); EXPECT_CALL(*send_algorithm_, GetCongestionControlType()) .WillRepeatedly(Return(kInitialCongestionControlType)); EXPECT_CALL(*send_algorithm_, BandwidthEstimate()) .Times(AnyNumber()) .WillRepeatedly(Return(QuicBandwidth::Zero())); EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber()); EXPECT_CALL(*network_change_visitor_, OnPathMtuIncreased(1000)) .Times(AnyNumber()); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(true)); EXPECT_CALL(notifier_, HasUnackedCryptoData()) .WillRepeatedly(Return(false)); EXPECT_CALL(notifier_, OnStreamFrameRetransmitted(_)).Times(AnyNumber()); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillRepeatedly(Return(true)); } ~QuicSentPacketManagerTest() override {} QuicByteCount BytesInFlight() { return manager_.GetBytesInFlight(); } void VerifyUnackedPackets(uint64_t* packets, size_t num_packets) { if (num_packets == 0) { EXPECT_TRUE(manager_.unacked_packets().empty()); EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetNumRetransmittablePackets( &manager_)); return; } EXPECT_FALSE(manager_.unacked_packets().empty()); EXPECT_EQ(QuicPacketNumber(packets[0]), manager_.GetLeastUnacked()); for (size_t i = 0; i < num_packets; ++i) { EXPECT_TRUE( manager_.unacked_packets().IsUnacked(QuicPacketNumber(packets[i]))) << packets[i]; } } void VerifyRetransmittablePackets(uint64_t* packets, size_t num_packets) { EXPECT_EQ( num_packets, QuicSentPacketManagerPeer::GetNumRetransmittablePackets(&manager_)); for (size_t i = 0; i < num_packets; ++i) { EXPECT_TRUE(QuicSentPacketManagerPeer::HasRetransmittableFrames( &manager_, packets[i])) << " packets[" << i << "]:" << packets[i]; } } void ExpectAck(uint64_t largest_observed) { EXPECT_CALL( *send_algorithm_, OnCongestionEvent(true, _, _, Pointwise(PacketNumberEq(), {largest_observed}), IsEmpty(), _, _)); EXPECT_CALL(*network_change_visitor_, OnCongestionChange()); } void ExpectUpdatedRtt(uint64_t ) { EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, IsEmpty(), IsEmpty(), _, _)); EXPECT_CALL(*network_change_visitor_, OnCongestionChange()); } void ExpectAckAndLoss(bool rtt_updated, uint64_t largest_observed, uint64_t lost_packet) { EXPECT_CALL( *send_algorithm_, OnCongestionEvent(rtt_updated, _, _, Pointwise(PacketNumberEq(), {largest_observed}), Pointwise(PacketNumberEq(), {lost_packet}), _, _)); EXPECT_CALL(*network_change_visitor_, OnCongestionChange()); } void ExpectAcksAndLosses(bool rtt_updated, uint64_t* packets_acked, size_t num_packets_acked, uint64_t* packets_lost, size_t num_packets_lost) { std::vector<QuicPacketNumber> ack_vector; for (size_t i = 0; i < num_packets_acked; ++i) { ack_vector.push_back(QuicPacketNumber(packets_acked[i])); } std::vector<QuicPacketNumber> lost_vector; for (size_t i = 0; i < num_packets_lost; ++i) { lost_vector.push_back(QuicPacketNumber(packets_lost[i])); } EXPECT_CALL(*send_algorithm_, OnCongestionEvent( rtt_updated, _, _, Pointwise(PacketNumberEq(), ack_vector), Pointwise(PacketNumberEq(), lost_vector), _, _)); EXPECT_CALL(*network_change_visitor_, OnCongestionChange()) .Times(AnyNumber()); } void RetransmitAndSendPacket(uint64_t old_packet_number, uint64_t new_packet_number) { RetransmitAndSendPacket(old_packet_number, new_packet_number, PTO_RETRANSMISSION); } void RetransmitAndSendPacket(uint64_t old_packet_number, uint64_t new_packet_number, TransmissionType transmission_type) { bool is_lost = false; if (transmission_type == HANDSHAKE_RETRANSMISSION || transmission_type == PTO_RETRANSMISSION) { EXPECT_CALL(notifier_, RetransmitFrames(_, _)) .WillOnce(WithArgs<1>( Invoke([this, new_packet_number](TransmissionType type) { return RetransmitDataPacket(new_packet_number, type); }))); } else { EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1); is_lost = true; } QuicSentPacketManagerPeer::MarkForRetransmission( &manager_, old_packet_number, transmission_type); if (!is_lost) { return; } EXPECT_CALL( *send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(new_packet_number), kDefaultLength, HAS_RETRANSMITTABLE_DATA)); SerializedPacket packet(CreatePacket(new_packet_number, true)); manager_.OnPacketSent(&packet, clock_.Now(), transmission_type, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); } SerializedPacket CreateDataPacket(uint64_t packet_number) { return CreatePacket(packet_number, true); } SerializedPacket CreatePacket(uint64_t packet_number, bool retransmittable) { SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); if (retransmittable) { packet.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(kStreamId, false, 0, absl::string_view()))); } return packet; } SerializedPacket CreatePingPacket(uint64_t packet_number) { SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); packet.retransmittable_frames.push_back(QuicFrame(QuicPingFrame())); return packet; } void SendDataPacket(uint64_t packet_number) { SendDataPacket(packet_number, ENCRYPTION_INITIAL, ECN_NOT_ECT); } void SendDataPacket(uint64_t packet_number, EncryptionLevel encryption_level) { SendDataPacket(packet_number, encryption_level, ECN_NOT_ECT); } void SendDataPacket(uint64_t packet_number, EncryptionLevel encryption_level, QuicEcnCodepoint ecn_codepoint) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), _, _)); SerializedPacket packet(CreateDataPacket(packet_number)); packet.encryption_level = encryption_level; manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ecn_codepoint); } void SendPingPacket(uint64_t packet_number, EncryptionLevel encryption_level) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), _, _)); SerializedPacket packet(CreatePingPacket(packet_number)); packet.encryption_level = encryption_level; manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); } void SendCryptoPacket(uint64_t packet_number) { EXPECT_CALL( *send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), kDefaultLength, HAS_RETRANSMITTABLE_DATA)); SerializedPacket packet(CreatePacket(packet_number, false)); packet.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, false, 0, absl::string_view()))); packet.has_crypto_handshake = IS_HANDSHAKE; manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(true)); } void SendAckPacket(uint64_t packet_number, uint64_t largest_acked) { SendAckPacket(packet_number, largest_acked, ENCRYPTION_INITIAL); } void SendAckPacket(uint64_t packet_number, uint64_t largest_acked, EncryptionLevel level) { EXPECT_CALL( *send_algorithm_, OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number), kDefaultLength, NO_RETRANSMITTABLE_DATA)); SerializedPacket packet(CreatePacket(packet_number, false)); packet.largest_acked = QuicPacketNumber(largest_acked); packet.encryption_level = level; manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION, NO_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); } quiche::SimpleBufferAllocator allocator_; QuicSentPacketManager manager_; MockClock clock_; QuicConnectionStats stats_; MockSendAlgorithm* send_algorithm_; std::unique_ptr<MockNetworkChangeVisitor> network_change_visitor_; StrictMock<MockSessionNotifier> notifier_; }; TEST_F(QuicSentPacketManagerTest, IsUnacked) { VerifyUnackedPackets(nullptr, 0); SendDataPacket(1); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); uint64_t retransmittable[] = {1}; VerifyRetransmittablePackets(retransmittable, ABSL_ARRAYSIZE(retransmittable)); } TEST_F(QuicSentPacketManagerTest, IsUnAckedRetransmit) { SendDataPacket(1); RetransmitAndSendPacket(1, 2); EXPECT_TRUE(QuicSentPacketManagerPeer::IsRetransmission(&manager_, 2)); uint64_t unacked[] = {1, 2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); std::vector<uint64_t> retransmittable = {1, 2}; VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size()); } TEST_F(QuicSentPacketManagerTest, RetransmitThenAck) { SendDataPacket(1); RetransmitAndSendPacket(1, 2); ExpectAck(2); manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); EXPECT_TRUE(manager_.HasInFlightPackets()); VerifyRetransmittablePackets(nullptr, 0); } TEST_F(QuicSentPacketManagerTest, RetransmitThenAckBeforeSend) { SendDataPacket(1); EXPECT_CALL(notifier_, RetransmitFrames(_, _)) .WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) { return RetransmitDataPacket(2, type); }))); QuicSentPacketManagerPeer::MarkForRetransmission(&manager_, 1, PTO_RETRANSMISSION); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); uint64_t unacked[] = {2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); EXPECT_EQ(0u, stats_.packets_spuriously_retransmitted); } TEST_F(QuicSentPacketManagerTest, RetransmitThenStopRetransmittingBeforeSend) { SendDataPacket(1); EXPECT_CALL(notifier_, RetransmitFrames(_, _)).WillRepeatedly(Return(true)); QuicSentPacketManagerPeer::MarkForRetransmission(&manager_, 1, PTO_RETRANSMISSION); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); uint64_t unacked[] = {1}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); VerifyRetransmittablePackets(nullptr, 0); EXPECT_EQ(0u, stats_.packets_spuriously_retransmitted); } TEST_F(QuicSentPacketManagerTest, RetransmitThenAckPrevious) { SendDataPacket(1); RetransmitAndSendPacket(1, 2); QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15); clock_.AdvanceTime(rtt); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); uint64_t unacked[] = {2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); EXPECT_TRUE(manager_.HasInFlightPackets()); VerifyRetransmittablePackets(nullptr, 0); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillOnce(Return(false)); ExpectAck(2); manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(1u, stats_.packets_spuriously_retransmitted); } TEST_F(QuicSentPacketManagerTest, RetransmitThenAckPreviousThenNackRetransmit) { SendDataPacket(1); RetransmitAndSendPacket(1, 2); QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15); clock_.AdvanceTime(rtt); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); SendDataPacket(3); SendDataPacket(4); SendDataPacket(5); clock_.AdvanceTime(rtt); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1); ExpectAckAndLoss(true, 3, 2); manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2), ENCRYPTION_INITIAL, kEmptyCounts)); ExpectAck(4); manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3), ENCRYPTION_INITIAL, kEmptyCounts)); ExpectAck(5); manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4), ENCRYPTION_INITIAL, kEmptyCounts)); uint64_t unacked[] = {2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); EXPECT_FALSE(manager_.HasInFlightPackets()); VerifyRetransmittablePackets(nullptr, 0); EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime()); } TEST_F(QuicSentPacketManagerTest, DISABLED_RetransmitTwiceThenAckPreviousBeforeSend) { SendDataPacket(1); RetransmitAndSendPacket(1, 2); EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true)); EXPECT_CALL(*network_change_visitor_, OnCongestionChange()); manager_.OnRetransmissionTimeout(); ExpectUpdatedRtt(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); uint64_t unacked[] = {2}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); EXPECT_FALSE(manager_.HasInFlightPackets()); VerifyRetransmittablePackets(nullptr, 0); EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime()); } TEST_F(QuicSentPacketManagerTest, RetransmitTwiceThenAckFirst) { StrictMock<MockDebugDelegate> debug_delegate; EXPECT_CALL(debug_delegate, OnSpuriousPacketRetransmission(PTO_RETRANSMISSION, kDefaultLength)) .Times(1); manager_.SetDebugDelegate(&debug_delegate); SendDataPacket(1); RetransmitAndSendPacket(1, 2); RetransmitAndSendPacket(2, 3); QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15); clock_.AdvanceTime(rtt); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)) .Times(2) .WillRepeatedly(Return(false)); uint64_t unacked[] = {2, 3}; VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked)); EXPECT_TRUE(manager_.HasInFlightPackets()); VerifyRetransmittablePackets(nullptr, 0); SendDataPacket(4); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)) .WillOnce(Return(false)) .WillRepeatedly(Return(true)); uint64_t acked[] = {3, 4}; ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0); manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2), ENCRYPTION_INITIAL, kEmptyCounts)); uint64_t unacked2[] = {2}; VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2)); EXPECT_TRUE(manager_.HasInFlightPackets()); SendDataPacket(5); ExpectAckAndLoss(true, 5, 2); EXPECT_CALL(debug_delegate, OnPacketLoss(QuicPacketNumber(2), _, LOSS_RETRANSMISSION, _)); EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false)); EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1); manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3), ENCRYPTION_INITIAL, kEmptyCounts)); uint64_t unacked3[] = {2}; VerifyUnackedPackets(unacked3, ABSL_ARRAYSIZE(unacked3)); EXPECT_FALSE(manager_.HasInFlightPackets()); EXPECT_EQ(1u, stats_.packets_spuriously_retransmitted); EXPECT_EQ(1u, stats_.packets_lost); EXPECT_LT(0.0, stats_.total_loss_detection_response_time); EXPECT_LE(1u, stats_.sent_packets_max_sequence_reordering); } TEST_F(QuicSentPacketManagerTest, AckOriginalTransmission) { auto loss_algorithm = std::make_unique<MockLossAlgorithm>(); QuicSentPacketManagerPeer::SetLossAlgorithm(&manager_, loss_algorithm.get()); SendDataPacket(1); RetransmitAndSendPacket(1, 2); { ExpectAck(1); EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _)); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); } SendDataPacket(3); SendDataPacket(4); { ExpectAck(4); EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _)); manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(5)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2), ENCRYPTION_INITIAL, kEmptyCounts)); RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION); } { uint64_t acked[] = {3}; ExpectAcksAndLosses(false, acked, ABSL_ARRAYSIZE(acked), nullptr, 0); EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*loss_algorithm, SpuriousLossDetected(_, _, _, QuicPacketNumber(3), QuicPacketNumber(4))); manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(0u, stats_.packet_spuriously_detected_lost); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(1u, stats_.packet_spuriously_detected_lost); ExpectAck(5); EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillOnce(Return(false)); manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6)); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4), ENCRYPTION_INITIAL, kEmptyCounts)); } } TEST_F(QuicSentPacketManagerTest, GetLeastUnacked) { EXPECT_EQ(QuicPacketNumber(1u), manager_.GetLeastUnacked()); } TEST_F(QuicSentPacketManagerTest, GetLeastUnackedUnacked) { SendDataPacket(1); EXPECT_EQ(QuicPacketNumber(1u), manager_.GetLeastUnacked()); } TEST_F(QuicSentPacketManagerTest, AckAckAndUpdateRtt) { EXPECT_FALSE(manager_.largest_packet_peer_knows_is_acked().IsInitialized()); SendDataPacket(1); SendAckPacket(2, 1); uint64_t acked[] = {1, 2}; ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0); manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::FromMilliseconds(5), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(QuicPacketNumber(1), manager_.largest_packet_peer_knows_is_acked()); SendAckPacket(3, 3); uint64_t acked2[] = {3}; ExpectAcksAndLosses(true, acked2, ABSL_ARRAYSIZE(acked2), nullptr, 0); manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(QuicPacketNumber(3u), manager_.largest_packet_peer_knows_is_acked()); } TEST_F(QuicSentPacketManagerTest, Rtt) { QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(20); SendDataPacket(1); clock_.AdvanceTime(expected_rtt); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt()); } TEST_F(QuicSentPacketManagerTest, RttWithInvalidDelta) { QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(10); SendDataPacket(1); clock_.AdvanceTime(expected_rtt); ExpectAck(1); manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::FromMilliseconds(11), clock_.Now()); manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(PACKETS_NEWLY_ACKED, manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL, kEmptyCounts)); EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt()); } TEST_F(QuicSentPacketManagerTest, RttWithInfiniteDelta) { QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(10); SendDataPacket(1); clock_.AdvanceTime(expected_rtt); ExpectAck(1); manager_.
271
cpp
google/quiche
quic_time
quiche/quic/core/quic_time.cc
quiche/quic/core/quic_time_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_TIME_H_ #define QUICHE_QUIC_CORE_QUIC_TIME_H_ #include <cmath> #include <cstdint> #include <limits> #include <ostream> #include <string> #include "absl/time/time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QuicClock; class QuicTime; class QUICHE_EXPORT QuicTimeDelta { public: explicit QuicTimeDelta(absl::Duration duration) : time_offset_((duration == absl::InfiniteDuration()) ? kInfiniteTimeUs : absl::ToInt64Microseconds(duration)) {} static constexpr QuicTimeDelta Zero() { return QuicTimeDelta(0); } static constexpr QuicTimeDelta Infinite() { return QuicTimeDelta(kInfiniteTimeUs); } static constexpr QuicTimeDelta FromSeconds(int64_t secs) { return QuicTimeDelta(secs * 1000 * 1000); } static constexpr QuicTimeDelta FromMilliseconds(int64_t ms) { return QuicTimeDelta(ms * 1000); } static constexpr QuicTimeDelta FromMicroseconds(int64_t us) { return QuicTimeDelta(us); } constexpr int64_t ToSeconds() const { return time_offset_ / 1000 / 1000; } constexpr int64_t ToMilliseconds() const { return time_offset_ / 1000; } constexpr int64_t ToMicroseconds() const { return time_offset_; } constexpr absl::Duration ToAbsl() { if (ABSL_PREDICT_FALSE(IsInfinite())) { return absl::InfiniteDuration(); } return absl::Microseconds(time_offset_); } constexpr bool IsZero() const { return time_offset_ == 0; } constexpr bool IsInfinite() const { return time_offset_ == kInfiniteTimeUs; } std::string ToDebuggingValue() const; private: friend inline bool operator==(QuicTimeDelta lhs, QuicTimeDelta rhs); friend inline bool operator<(QuicTimeDelta lhs, QuicTimeDelta rhs); friend inline QuicTimeDelta operator<<(QuicTimeDelta lhs, size_t rhs); friend inline QuicTimeDelta operator>>(QuicTimeDelta lhs, size_t rhs); friend inline constexpr QuicTimeDelta operator+(QuicTimeDelta lhs, QuicTimeDelta rhs); friend inline constexpr QuicTimeDelta operator-(QuicTimeDelta lhs, QuicTimeDelta rhs); friend inline constexpr QuicTimeDelta operator*(QuicTimeDelta lhs, int rhs); friend inline QuicTimeDelta operator*(QuicTimeDelta lhs, double rhs); friend inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs); friend inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs); friend inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs); static constexpr int64_t kInfiniteTimeUs = std::numeric_limits<int64_t>::max(); explicit constexpr QuicTimeDelta(int64_t time_offset) : time_offset_(time_offset) {} int64_t time_offset_; friend class QuicTime; }; class QUICHE_EXPORT QuicTime { public: using Delta = QuicTimeDelta; static constexpr QuicTime Zero() { return QuicTime(0); } static constexpr QuicTime Infinite() { return QuicTime(Delta::kInfiniteTimeUs); } QuicTime(const QuicTime& other) = default; QuicTime& operator=(const QuicTime& other) { time_ = other.time_; return *this; } int64_t ToDebuggingValue() const { return time_; } bool IsInitialized() const { return 0 != time_; } private: friend class QuicClock; friend inline bool operator==(QuicTime lhs, QuicTime rhs); friend inline bool operator<(QuicTime lhs, QuicTime rhs); friend inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs); friend inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs); friend inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs); explicit constexpr QuicTime(int64_t time) : time_(time) {} int64_t time_; }; class QUICHE_EXPORT QuicWallTime { public: static constexpr QuicWallTime FromUNIXSeconds(uint64_t seconds) { return QuicWallTime(seconds * 1000000); } static constexpr QuicWallTime FromUNIXMicroseconds(uint64_t microseconds) { return QuicWallTime(microseconds); } static constexpr QuicWallTime Zero() { return QuicWallTime(0); } uint64_t ToUNIXSeconds() const; uint64_t ToUNIXMicroseconds() const; bool IsAfter(QuicWallTime other) const; bool IsBefore(QuicWallTime other) const; bool IsZero() const; QuicTimeDelta AbsoluteDifference(QuicWallTime other) const; [[nodiscard]] QuicWallTime Add(QuicTimeDelta delta) const; [[nodiscard]] QuicWallTime Subtract(QuicTimeDelta delta) const; bool operator==(const QuicWallTime& other) const { return microseconds_ == other.microseconds_; } QuicTimeDelta operator-(const QuicWallTime& rhs) const { return QuicTimeDelta::FromMicroseconds(microseconds_ - rhs.microseconds_); } private: explicit constexpr QuicWallTime(uint64_t microseconds) : microseconds_(microseconds) {} uint64_t microseconds_; }; inline bool operator==(QuicTimeDelta lhs, QuicTimeDelta rhs) { return lhs.time_offset_ == rhs.time_offset_; } inline bool operator!=(QuicTimeDelta lhs, QuicTimeDelta rhs) { return !(lhs == rhs); } inline bool operator<(QuicTimeDelta lhs, QuicTimeDelta rhs) { return lhs.time_offset_ < rhs.time_offset_; } inline bool operator>(QuicTimeDelta lhs, QuicTimeDelta rhs) { return rhs < lhs; } inline bool operator<=(QuicTimeDelta lhs, QuicTimeDelta rhs) { return !(rhs < lhs); } inline bool operator>=(QuicTimeDelta lhs, QuicTimeDelta rhs) { return !(lhs < rhs); } inline QuicTimeDelta operator<<(QuicTimeDelta lhs, size_t rhs) { return QuicTimeDelta(lhs.time_offset_ << rhs); } inline QuicTimeDelta operator>>(QuicTimeDelta lhs, size_t rhs) { return QuicTimeDelta(lhs.time_offset_ >> rhs); } inline bool operator==(QuicTime lhs, QuicTime rhs) { return lhs.time_ == rhs.time_; } inline bool operator!=(QuicTime lhs, QuicTime rhs) { return !(lhs == rhs); } inline bool operator<(QuicTime lhs, QuicTime rhs) { return lhs.time_ < rhs.time_; } inline bool operator>(QuicTime lhs, QuicTime rhs) { return rhs < lhs; } inline bool operator<=(QuicTime lhs, QuicTime rhs) { return !(rhs < lhs); } inline bool operator>=(QuicTime lhs, QuicTime rhs) { return !(lhs < rhs); } inline std::ostream& operator<<(std::ostream& output, const QuicTime t) { output << t.ToDebuggingValue(); return output; } inline constexpr QuicTimeDelta operator+(QuicTimeDelta lhs, QuicTimeDelta rhs) { return QuicTimeDelta(lhs.time_offset_ + rhs.time_offset_); } inline constexpr QuicTimeDelta operator-(QuicTimeDelta lhs, QuicTimeDelta rhs) { return QuicTimeDelta(lhs.time_offset_ - rhs.time_offset_); } inline constexpr QuicTimeDelta operator*(QuicTimeDelta lhs, int rhs) { return QuicTimeDelta(lhs.time_offset_ * rhs); } inline QuicTimeDelta operator*(QuicTimeDelta lhs, double rhs) { return QuicTimeDelta(static_cast<int64_t>( std::llround(static_cast<double>(lhs.time_offset_) * rhs))); } inline QuicTimeDelta operator*(int lhs, QuicTimeDelta rhs) { return rhs * lhs; } inline QuicTimeDelta operator*(double lhs, QuicTimeDelta rhs) { return rhs * lhs; } inline QuicTime operator+(QuicTime lhs, QuicTimeDelta rhs) { return QuicTime(lhs.time_ + rhs.time_offset_); } inline QuicTime operator-(QuicTime lhs, QuicTimeDelta rhs) { return QuicTime(lhs.time_ - rhs.time_offset_); } inline QuicTimeDelta operator-(QuicTime lhs, QuicTime rhs) { return QuicTimeDelta(lhs.time_ - rhs.time_); } inline std::ostream& operator<<(std::ostream& output, const QuicTimeDelta delta) { output << delta.ToDebuggingValue(); return output; } } #endif #include "quiche/quic/core/quic_time.h" #include <cinttypes> #include <cstdlib> #include <limits> #include <string> #include "absl/strings/str_cat.h" namespace quic { std::string QuicTime::Delta::ToDebuggingValue() const { constexpr int64_t kMillisecondInMicroseconds = 1000; constexpr int64_t kSecondInMicroseconds = 1000 * kMillisecondInMicroseconds; int64_t absolute_value = std::abs(time_offset_); if (absolute_value >= kSecondInMicroseconds && absolute_value % kSecondInMicroseconds == 0) { return absl::StrCat(time_offset_ / kSecondInMicroseconds, "s"); } if (absolute_value >= kMillisecondInMicroseconds && absolute_value % kMillisecondInMicroseconds == 0) { return absl::StrCat(time_offset_ / kMillisecondInMicroseconds, "ms"); } return absl::StrCat(time_offset_, "us"); } uint64_t QuicWallTime::ToUNIXSeconds() const { return microseconds_ / 1000000; } uint64_t QuicWallTime::ToUNIXMicroseconds() const { return microseconds_; } bool QuicWallTime::IsAfter(QuicWallTime other) const { return microseconds_ > other.microseconds_; } bool QuicWallTime::IsBefore(QuicWallTime other) const { return microseconds_ < other.microseconds_; } bool QuicWallTime::IsZero() const { return microseconds_ == 0; } QuicTime::Delta QuicWallTime::AbsoluteDifference(QuicWallTime other) const { uint64_t d; if (microseconds_ > other.microseconds_) { d = microseconds_ - other.microseconds_; } else { d = other.microseconds_ - microseconds_; } if (d > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { d = std::numeric_limits<int64_t>::max(); } return QuicTime::Delta::FromMicroseconds(d); } QuicWallTime QuicWallTime::Add(QuicTime::Delta delta) const { uint64_t microseconds = microseconds_ + delta.ToMicroseconds(); if (microseconds < microseconds_) { microseconds = std::numeric_limits<uint64_t>::max(); } return QuicWallTime(microseconds); } QuicWallTime QuicWallTime::Subtract(QuicTime::Delta delta) const { uint64_t microseconds = microseconds_ - delta.ToMicroseconds(); if (microseconds > microseconds_) { microseconds = 0; } return QuicWallTime(microseconds); } }
#include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class QuicTimeDeltaTest : public QuicTest {}; TEST_F(QuicTimeDeltaTest, Zero) { EXPECT_TRUE(QuicTime::Delta::Zero().IsZero()); EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite()); EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsZero()); } TEST_F(QuicTimeDeltaTest, Infinite) { EXPECT_TRUE(QuicTime::Delta::Infinite().IsInfinite()); EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite()); EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsInfinite()); } TEST_F(QuicTimeDeltaTest, FromTo) { EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), QuicTime::Delta::FromMicroseconds(1000)); EXPECT_EQ(QuicTime::Delta::FromSeconds(1), QuicTime::Delta::FromMilliseconds(1000)); EXPECT_EQ(QuicTime::Delta::FromSeconds(1), QuicTime::Delta::FromMicroseconds(1000000)); EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds()); EXPECT_EQ(2, QuicTime::Delta::FromMilliseconds(2000).ToSeconds()); EXPECT_EQ(1000, QuicTime::Delta::FromMilliseconds(1).ToMicroseconds()); EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2000).ToMicroseconds(), QuicTime::Delta::FromSeconds(2).ToMicroseconds()); } TEST_F(QuicTimeDeltaTest, Add) { EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000), QuicTime::Delta::Zero() + QuicTime::Delta::FromMilliseconds(2)); } TEST_F(QuicTimeDeltaTest, Subtract) { EXPECT_EQ(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMilliseconds(2) - QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicTimeDeltaTest, Multiply) { int i = 2; EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000), QuicTime::Delta::FromMilliseconds(2) * i); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000), i * QuicTime::Delta::FromMilliseconds(2)); double d = 2; EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000), QuicTime::Delta::FromMilliseconds(2) * d); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000), d * QuicTime::Delta::FromMilliseconds(2)); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(5), QuicTime::Delta::FromMicroseconds(9) * 0.5); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2), QuicTime::Delta::FromMicroseconds(12) * 0.2); } TEST_F(QuicTimeDeltaTest, Max) { EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000), std::max(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMicroseconds(2000))); } TEST_F(QuicTimeDeltaTest, NotEqual) { EXPECT_TRUE(QuicTime::Delta::FromSeconds(0) != QuicTime::Delta::FromSeconds(1)); EXPECT_FALSE(QuicTime::Delta::FromSeconds(0) != QuicTime::Delta::FromSeconds(0)); } TEST_F(QuicTimeDeltaTest, DebuggingValue) { const QuicTime::Delta one_us = QuicTime::Delta::FromMicroseconds(1); const QuicTime::Delta one_ms = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta one_s = QuicTime::Delta::FromSeconds(1); EXPECT_EQ("1s", one_s.ToDebuggingValue()); EXPECT_EQ("3s", (3 * one_s).ToDebuggingValue()); EXPECT_EQ("1ms", one_ms.ToDebuggingValue()); EXPECT_EQ("3ms", (3 * one_ms).ToDebuggingValue()); EXPECT_EQ("1us", one_us.ToDebuggingValue()); EXPECT_EQ("3us", (3 * one_us).ToDebuggingValue()); EXPECT_EQ("3001us", (3 * one_ms + one_us).ToDebuggingValue()); EXPECT_EQ("3001ms", (3 * one_s + one_ms).ToDebuggingValue()); EXPECT_EQ("3000001us", (3 * one_s + one_us).ToDebuggingValue()); } class QuicTimeTest : public QuicTest { protected: MockClock clock_; }; TEST_F(QuicTimeTest, Initialized) { EXPECT_FALSE(QuicTime::Zero().IsInitialized()); EXPECT_TRUE((QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1)) .IsInitialized()); } TEST_F(QuicTimeTest, CopyConstruct) { QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234); EXPECT_NE(time_1, QuicTime(QuicTime::Zero())); EXPECT_EQ(time_1, QuicTime(time_1)); } TEST_F(QuicTimeTest, CopyAssignment) { QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234); QuicTime time_2 = QuicTime::Zero(); EXPECT_NE(time_1, time_2); time_2 = time_1; EXPECT_EQ(time_1, time_2); } TEST_F(QuicTimeTest, Add) { QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1); QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); QuicTime::Delta diff = time_2 - time_1; EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), diff); EXPECT_EQ(1000, diff.ToMicroseconds()); EXPECT_EQ(1, diff.ToMilliseconds()); } TEST_F(QuicTimeTest, Subtract) { QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1); QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), time_2 - time_1); } TEST_F(QuicTimeTest, SubtractDelta) { QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_EQ(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1), time - QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicTimeTest, Max) { QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1); QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_EQ(time_2, std::max(time_1, time_2)); } TEST_F(QuicTimeTest, MockClock) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicTime now = clock_.ApproximateNow(); QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1000); EXPECT_EQ(now, time); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); now = clock_.ApproximateNow(); EXPECT_NE(now, time); time = time + QuicTime::Delta::FromMilliseconds(1); EXPECT_EQ(now, time); } TEST_F(QuicTimeTest, LE) { const QuicTime zero = QuicTime::Zero(); const QuicTime one = zero + QuicTime::Delta::FromSeconds(1); EXPECT_TRUE(zero <= zero); EXPECT_TRUE(zero <= one); EXPECT_TRUE(one <= one); EXPECT_FALSE(one <= zero); } } }
272
cpp
google/quiche
quic_stream_priority
quiche/quic/core/quic_stream_priority.cc
quiche/quic/core/quic_stream_priority_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_PRIORITY_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_PRIORITY_H_ #include <cstdint> #include <optional> #include <string> #include <tuple> #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/web_transport/web_transport.h" namespace quic { struct QUICHE_EXPORT HttpStreamPriority { static constexpr int kMinimumUrgency = 0; static constexpr int kMaximumUrgency = 7; static constexpr int kDefaultUrgency = 3; static constexpr bool kDefaultIncremental = false; static constexpr absl::string_view kUrgencyKey = "u"; static constexpr absl::string_view kIncrementalKey = "i"; int urgency = kDefaultUrgency; bool incremental = kDefaultIncremental; bool operator==(const HttpStreamPriority& other) const { return std::tie(urgency, incremental) == std::tie(other.urgency, other.incremental); } bool operator!=(const HttpStreamPriority& other) const { return !(*this == other); } }; struct QUICHE_EXPORT WebTransportStreamPriority { QuicStreamId session_id = 0; uint64_t send_group_number = 0; webtransport::SendOrder send_order = 0; bool operator==(const WebTransportStreamPriority& other) const { return session_id == other.session_id && send_group_number == other.send_group_number && send_order == other.send_order; } bool operator!=(const WebTransportStreamPriority& other) const { return !(*this == other); } }; class QUICHE_EXPORT QuicStreamPriority { public: QuicStreamPriority() : value_(HttpStreamPriority()) {} explicit QuicStreamPriority(HttpStreamPriority priority) : value_(priority) {} explicit QuicStreamPriority(WebTransportStreamPriority priority) : value_(priority) {} QuicPriorityType type() const { return absl::visit(TypeExtractor(), value_); } HttpStreamPriority http() const { if (absl::holds_alternative<HttpStreamPriority>(value_)) { return absl::get<HttpStreamPriority>(value_); } QUICHE_BUG(invalid_priority_type_http) << "Tried to access HTTP priority for a priority type" << type(); return HttpStreamPriority(); } WebTransportStreamPriority web_transport() const { if (absl::holds_alternative<WebTransportStreamPriority>(value_)) { return absl::get<WebTransportStreamPriority>(value_); } QUICHE_BUG(invalid_priority_type_wt) << "Tried to access WebTransport priority for a priority type" << type(); return WebTransportStreamPriority(); } bool operator==(const QuicStreamPriority& other) const { return value_ == other.value_; } private: struct TypeExtractor { QuicPriorityType operator()(const HttpStreamPriority&) { return QuicPriorityType::kHttp; } QuicPriorityType operator()(const WebTransportStreamPriority&) { return QuicPriorityType::kWebTransport; } }; absl::variant<HttpStreamPriority, WebTransportStreamPriority> value_; }; QUICHE_EXPORT std::string SerializePriorityFieldValue( HttpStreamPriority priority); QUICHE_EXPORT std::optional<HttpStreamPriority> ParsePriorityFieldValue( absl::string_view priority_field_value); } #endif #include "quiche/quic/core/quic_stream_priority.h" #include <optional> #include <string> #include <vector> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/structured_headers.h" namespace quic { std::string SerializePriorityFieldValue(HttpStreamPriority priority) { quiche::structured_headers::Dictionary dictionary; if (priority.urgency != HttpStreamPriority::kDefaultUrgency && priority.urgency >= HttpStreamPriority::kMinimumUrgency && priority.urgency <= HttpStreamPriority::kMaximumUrgency) { dictionary[HttpStreamPriority::kUrgencyKey] = quiche::structured_headers::ParameterizedMember( quiche::structured_headers::Item( static_cast<int64_t>(priority.urgency)), {}); } if (priority.incremental != HttpStreamPriority::kDefaultIncremental) { dictionary[HttpStreamPriority::kIncrementalKey] = quiche::structured_headers::ParameterizedMember( quiche::structured_headers::Item(priority.incremental), {}); } std::optional<std::string> priority_field_value = quiche::structured_headers::SerializeDictionary(dictionary); if (!priority_field_value.has_value()) { QUICHE_BUG(priority_field_value_serialization_failed); return ""; } return *priority_field_value; } std::optional<HttpStreamPriority> ParsePriorityFieldValue( absl::string_view priority_field_value) { std::optional<quiche::structured_headers::Dictionary> parsed_dictionary = quiche::structured_headers::ParseDictionary(priority_field_value); if (!parsed_dictionary.has_value()) { return std::nullopt; } uint8_t urgency = HttpStreamPriority::kDefaultUrgency; bool incremental = HttpStreamPriority::kDefaultIncremental; for (const auto& [name, value] : *parsed_dictionary) { if (value.member_is_inner_list) { continue; } const std::vector<quiche::structured_headers::ParameterizedItem>& member = value.member; if (member.size() != 1) { QUICHE_BUG(priority_field_value_parsing_internal_error); continue; } const quiche::structured_headers::Item item = member[0].item; if (name == HttpStreamPriority::kUrgencyKey && item.is_integer()) { int parsed_urgency = item.GetInteger(); if (parsed_urgency >= HttpStreamPriority::kMinimumUrgency && parsed_urgency <= HttpStreamPriority::kMaximumUrgency) { urgency = parsed_urgency; } } else if (name == HttpStreamPriority::kIncrementalKey && item.is_boolean()) { incremental = item.GetBoolean(); } } return HttpStreamPriority{urgency, incremental}; } }
#include "quiche/quic/core/quic_stream_priority.h" #include <optional> #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic::test { TEST(HttpStreamPriority, DefaultConstructed) { HttpStreamPriority priority; EXPECT_EQ(HttpStreamPriority::kDefaultUrgency, priority.urgency); EXPECT_EQ(HttpStreamPriority::kDefaultIncremental, priority.incremental); } TEST(HttpStreamPriority, Equals) { EXPECT_EQ((HttpStreamPriority()), (HttpStreamPriority{HttpStreamPriority::kDefaultUrgency, HttpStreamPriority::kDefaultIncremental})); EXPECT_EQ((HttpStreamPriority{5, true}), (HttpStreamPriority{5, true})); EXPECT_EQ((HttpStreamPriority{2, false}), (HttpStreamPriority{2, false})); EXPECT_EQ((HttpStreamPriority{11, true}), (HttpStreamPriority{11, true})); EXPECT_NE((HttpStreamPriority{1, true}), (HttpStreamPriority{3, true})); EXPECT_NE((HttpStreamPriority{4, false}), (HttpStreamPriority{4, true})); EXPECT_NE((HttpStreamPriority{6, true}), (HttpStreamPriority{2, false})); EXPECT_NE((HttpStreamPriority{12, true}), (HttpStreamPriority{9, true})); EXPECT_NE((HttpStreamPriority{2, false}), (HttpStreamPriority{8, false})); } TEST(WebTransportStreamPriority, DefaultConstructed) { WebTransportStreamPriority priority; EXPECT_EQ(priority.session_id, 0); EXPECT_EQ(priority.send_group_number, 0); EXPECT_EQ(priority.send_order, 0); } TEST(WebTransportStreamPriority, Equals) { EXPECT_EQ(WebTransportStreamPriority(), (WebTransportStreamPriority{0, 0, 0})); EXPECT_NE(WebTransportStreamPriority(), (WebTransportStreamPriority{1, 2, 3})); EXPECT_NE(WebTransportStreamPriority(), (WebTransportStreamPriority{0, 0, 1})); } TEST(QuicStreamPriority, Default) { EXPECT_EQ(QuicStreamPriority().type(), QuicPriorityType::kHttp); EXPECT_EQ(QuicStreamPriority().http(), HttpStreamPriority()); } TEST(QuicStreamPriority, Equals) { EXPECT_EQ(QuicStreamPriority(), QuicStreamPriority(HttpStreamPriority())); } TEST(QuicStreamPriority, Type) { EXPECT_EQ(QuicStreamPriority(HttpStreamPriority()).type(), QuicPriorityType::kHttp); EXPECT_EQ(QuicStreamPriority(WebTransportStreamPriority()).type(), QuicPriorityType::kWebTransport); } TEST(SerializePriorityFieldValueTest, SerializePriorityFieldValue) { EXPECT_EQ("", SerializePriorityFieldValue( { 3, false})); EXPECT_EQ("u=5", SerializePriorityFieldValue( { 5, false})); EXPECT_EQ("i", SerializePriorityFieldValue( { 3, true})); EXPECT_EQ("u=0, i", SerializePriorityFieldValue( { 0, true})); EXPECT_EQ("i", SerializePriorityFieldValue( { 9, true})); } TEST(ParsePriorityFieldValueTest, ParsePriorityFieldValue) { std::optional<HttpStreamPriority> result = ParsePriorityFieldValue(""); ASSERT_TRUE(result.has_value()); EXPECT_EQ(3, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("i=?1"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(3, result->urgency); EXPECT_TRUE(result->incremental); result = ParsePriorityFieldValue("u=5"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(5, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("u=5, i"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(5, result->urgency); EXPECT_TRUE(result->incremental); result = ParsePriorityFieldValue("i, u=1"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(1, result->urgency); EXPECT_TRUE(result->incremental); result = ParsePriorityFieldValue("u=5, i=?1, i=?0, u=2"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(2, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("a=42, u=4, i=?0"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(4, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("u=-2, i"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(3, result->urgency); EXPECT_TRUE(result->incremental); result = ParsePriorityFieldValue("u=4.2, i=\"foo\""); ASSERT_TRUE(result.has_value()); EXPECT_EQ(3, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("a=4, b=?1"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(3, result->urgency); EXPECT_FALSE(result->incremental); result = ParsePriorityFieldValue("000"); EXPECT_FALSE(result.has_value()); result = ParsePriorityFieldValue("a=(1 2), u=1"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(1, result->urgency); EXPECT_FALSE(result->incremental); } }
273
cpp
google/quiche
quic_connection_id_manager
quiche/quic/core/quic_connection_id_manager.cc
quiche/quic/core/quic_connection_id_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_ID_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_CONNECTION_ID_MANAGER_H_ #include <cstddef> #include <memory> #include <optional> #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_retire_connection_id_frame.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_interval_set.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicConnectionIdManagerPeer; } struct QUICHE_EXPORT QuicConnectionIdData { QuicConnectionIdData(const QuicConnectionId& connection_id, uint64_t sequence_number, const StatelessResetToken& stateless_reset_token); QuicConnectionId connection_id; uint64_t sequence_number; StatelessResetToken stateless_reset_token; }; class QUICHE_EXPORT QuicConnectionIdManagerVisitorInterface { public: virtual ~QuicConnectionIdManagerVisitorInterface() = default; virtual void OnPeerIssuedConnectionIdRetired() = 0; virtual bool SendNewConnectionId(const QuicNewConnectionIdFrame& frame) = 0; virtual bool MaybeReserveConnectionId( const QuicConnectionId& connection_id) = 0; virtual void OnSelfIssuedConnectionIdRetired( const QuicConnectionId& connection_id) = 0; }; class QUICHE_EXPORT QuicPeerIssuedConnectionIdManager { public: QuicPeerIssuedConnectionIdManager( size_t active_connection_id_limit, const QuicConnectionId& initial_peer_issued_connection_id, const QuicClock* clock, QuicAlarmFactory* alarm_factory, QuicConnectionIdManagerVisitorInterface* visitor, QuicConnectionContext* context); ~QuicPeerIssuedConnectionIdManager(); QuicErrorCode OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame, std::string* error_detail, bool* is_duplicate_frame); bool HasUnusedConnectionId() const { return !unused_connection_id_data_.empty(); } const QuicConnectionIdData* ConsumeOneUnusedConnectionId(); void MaybeRetireUnusedConnectionIds( const std::vector<QuicConnectionId>& active_connection_ids_on_path); bool IsConnectionIdActive(const QuicConnectionId& cid) const; std::vector<uint64_t> ConsumeToBeRetiredConnectionIdSequenceNumbers(); void ReplaceConnectionId(const QuicConnectionId& old_connection_id, const QuicConnectionId& new_connection_id); private: friend class test::QuicConnectionIdManagerPeer; void PrepareToRetireActiveConnectionId(const QuicConnectionId& cid); bool IsConnectionIdNew(const QuicNewConnectionIdFrame& frame); void PrepareToRetireConnectionIdPriorTo( uint64_t retire_prior_to, std::vector<QuicConnectionIdData>* cid_data_vector); size_t active_connection_id_limit_; const QuicClock* clock_; std::unique_ptr<QuicAlarm> retire_connection_id_alarm_; std::vector<QuicConnectionIdData> active_connection_id_data_; std::vector<QuicConnectionIdData> unused_connection_id_data_; std::vector<QuicConnectionIdData> to_be_retired_connection_id_data_; QuicIntervalSet<uint64_t> recent_new_connection_id_sequence_numbers_; uint64_t max_new_connection_id_frame_retire_prior_to_ = 0u; }; class QUICHE_EXPORT QuicSelfIssuedConnectionIdManager { public: QuicSelfIssuedConnectionIdManager( size_t active_connection_id_limit, const QuicConnectionId& initial_connection_id, const QuicClock* clock, QuicAlarmFactory* alarm_factory, QuicConnectionIdManagerVisitorInterface* visitor, QuicConnectionContext* context, ConnectionIdGeneratorInterface& generator); virtual ~QuicSelfIssuedConnectionIdManager(); std::optional<QuicNewConnectionIdFrame> MaybeIssueNewConnectionIdForPreferredAddress(); QuicErrorCode OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame, QuicTime::Delta pto_delay, std::string* error_detail); std::vector<QuicConnectionId> GetUnretiredConnectionIds() const; QuicConnectionId GetOneActiveConnectionId() const; void RetireConnectionId(); void MaybeSendNewConnectionIds(); bool HasConnectionIdToConsume() const; std::optional<QuicConnectionId> ConsumeOneConnectionId(); bool IsConnectionIdInUse(const QuicConnectionId& cid) const; private: friend class test::QuicConnectionIdManagerPeer; std::optional<QuicNewConnectionIdFrame> MaybeIssueNewConnectionId(); size_t active_connection_id_limit_; const QuicClock* clock_; QuicConnectionIdManagerVisitorInterface* visitor_; std::vector<std::pair<QuicConnectionId, uint64_t>> active_connection_ids_; std::vector<std::pair<QuicConnectionId, QuicTime>> to_be_retired_connection_ids_; std::unique_ptr<QuicAlarm> retire_connection_id_alarm_; QuicConnectionId last_connection_id_; uint64_t next_connection_id_sequence_number_; uint64_t last_connection_id_consumed_by_self_sequence_number_; ConnectionIdGeneratorInterface& connection_id_generator_; }; } #endif #include "quiche/quic/core/quic_connection_id_manager.h" #include <algorithm> #include <cstdio> #include <optional> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QuicConnectionIdData::QuicConnectionIdData( const QuicConnectionId& connection_id, uint64_t sequence_number, const StatelessResetToken& stateless_reset_token) : connection_id(connection_id), sequence_number(sequence_number), stateless_reset_token(stateless_reset_token) {} namespace { class RetirePeerIssuedConnectionIdAlarm : public QuicAlarm::DelegateWithContext { public: explicit RetirePeerIssuedConnectionIdAlarm( QuicConnectionIdManagerVisitorInterface* visitor, QuicConnectionContext* context) : QuicAlarm::DelegateWithContext(context), visitor_(visitor) {} RetirePeerIssuedConnectionIdAlarm(const RetirePeerIssuedConnectionIdAlarm&) = delete; RetirePeerIssuedConnectionIdAlarm& operator=( const RetirePeerIssuedConnectionIdAlarm&) = delete; void OnAlarm() override { visitor_->OnPeerIssuedConnectionIdRetired(); } private: QuicConnectionIdManagerVisitorInterface* visitor_; }; std::vector<QuicConnectionIdData>::const_iterator FindConnectionIdData( const std::vector<QuicConnectionIdData>& cid_data_vector, const QuicConnectionId& cid) { return std::find_if(cid_data_vector.begin(), cid_data_vector.end(), [&cid](const QuicConnectionIdData& cid_data) { return cid == cid_data.connection_id; }); } std::vector<QuicConnectionIdData>::iterator FindConnectionIdData( std::vector<QuicConnectionIdData>* cid_data_vector, const QuicConnectionId& cid) { return std::find_if(cid_data_vector->begin(), cid_data_vector->end(), [&cid](const QuicConnectionIdData& cid_data) { return cid == cid_data.connection_id; }); } } QuicPeerIssuedConnectionIdManager::QuicPeerIssuedConnectionIdManager( size_t active_connection_id_limit, const QuicConnectionId& initial_peer_issued_connection_id, const QuicClock* clock, QuicAlarmFactory* alarm_factory, QuicConnectionIdManagerVisitorInterface* visitor, QuicConnectionContext* context) : active_connection_id_limit_(active_connection_id_limit), clock_(clock), retire_connection_id_alarm_(alarm_factory->CreateAlarm( new RetirePeerIssuedConnectionIdAlarm(visitor, context))) { QUICHE_DCHECK_GE(active_connection_id_limit_, 2u); QUICHE_DCHECK(!initial_peer_issued_connection_id.IsEmpty()); active_connection_id_data_.emplace_back<const QuicConnectionId&, uint64_t, const StatelessResetToken&>( initial_peer_issued_connection_id, 0u, {}); recent_new_connection_id_sequence_numbers_.Add(0u, 1u); } QuicPeerIssuedConnectionIdManager::~QuicPeerIssuedConnectionIdManager() { retire_connection_id_alarm_->Cancel(); } bool QuicPeerIssuedConnectionIdManager::IsConnectionIdNew( const QuicNewConnectionIdFrame& frame) { auto is_old_connection_id = [&frame](const QuicConnectionIdData& cid_data) { return cid_data.connection_id == frame.connection_id; }; if (std::any_of(active_connection_id_data_.begin(), active_connection_id_data_.end(), is_old_connection_id)) { return false; } if (std::any_of(unused_connection_id_data_.begin(), unused_connection_id_data_.end(), is_old_connection_id)) { return false; } if (std::any_of(to_be_retired_connection_id_data_.begin(), to_be_retired_connection_id_data_.end(), is_old_connection_id)) { return false; } return true; } void QuicPeerIssuedConnectionIdManager::PrepareToRetireConnectionIdPriorTo( uint64_t retire_prior_to, std::vector<QuicConnectionIdData>* cid_data_vector) { auto it2 = cid_data_vector->begin(); for (auto it = cid_data_vector->begin(); it != cid_data_vector->end(); ++it) { if (it->sequence_number >= retire_prior_to) { *it2++ = *it; } else { to_be_retired_connection_id_data_.push_back(*it); if (!retire_connection_id_alarm_->IsSet()) { retire_connection_id_alarm_->Set(clock_->ApproximateNow()); } } } cid_data_vector->erase(it2, cid_data_vector->end()); } QuicErrorCode QuicPeerIssuedConnectionIdManager::OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& frame, std::string* error_detail, bool* is_duplicate_frame) { if (recent_new_connection_id_sequence_numbers_.Contains( frame.sequence_number)) { *is_duplicate_frame = true; return QUIC_NO_ERROR; } if (!IsConnectionIdNew(frame)) { *error_detail = "Received a NEW_CONNECTION_ID frame that reuses a previously seen Id."; return IETF_QUIC_PROTOCOL_VIOLATION; } recent_new_connection_id_sequence_numbers_.AddOptimizedForAppend( frame.sequence_number, frame.sequence_number + 1); if (recent_new_connection_id_sequence_numbers_.Size() > kMaxNumConnectionIdSequenceNumberIntervals) { *error_detail = "Too many disjoint connection Id sequence number intervals."; return IETF_QUIC_PROTOCOL_VIOLATION; } if (frame.sequence_number < max_new_connection_id_frame_retire_prior_to_) { to_be_retired_connection_id_data_.emplace_back(frame.connection_id, frame.sequence_number, frame.stateless_reset_token); if (!retire_connection_id_alarm_->IsSet()) { retire_connection_id_alarm_->Set(clock_->ApproximateNow()); } return QUIC_NO_ERROR; } if (frame.retire_prior_to > max_new_connection_id_frame_retire_prior_to_) { max_new_connection_id_frame_retire_prior_to_ = frame.retire_prior_to; PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to, &active_connection_id_data_); PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to, &unused_connection_id_data_); } if (active_connection_id_data_.size() + unused_connection_id_data_.size() >= active_connection_id_limit_) { *error_detail = "Peer provides more connection IDs than the limit."; return QUIC_CONNECTION_ID_LIMIT_ERROR; } unused_connection_id_data_.emplace_back( frame.connection_id, frame.sequence_number, frame.stateless_reset_token); return QUIC_NO_ERROR; } const QuicConnectionIdData* QuicPeerIssuedConnectionIdManager::ConsumeOneUnusedConnectionId() { if (unused_connection_id_data_.empty()) { return nullptr; } active_connection_id_data_.push_back(unused_connection_id_data_.back()); unused_connection_id_data_.pop_back(); return &active_connection_id_data_.back(); } void QuicPeerIssuedConnectionIdManager::PrepareToRetireActiveConnectionId( const QuicConnectionId& cid) { auto it = FindConnectionIdData(active_connection_id_data_, cid); if (it == active_connection_id_data_.end()) { return; } to_be_retired_connection_id_data_.push_back(*it); active_connection_id_data_.erase(it); if (!retire_connection_id_alarm_->IsSet()) { retire_connection_id_alarm_->Set(clock_->ApproximateNow()); } } void QuicPeerIssuedConnectionIdManager::MaybeRetireUnusedConnectionIds( const std::vector<QuicConnectionId>& active_connection_ids_on_path) { std::vector<QuicConnectionId> cids_to_retire; for (const auto& cid_data : active_connection_id_data_) { if (std::find(active_connection_ids_on_path.begin(), active_connection_ids_on_path.end(), cid_data.connection_id) == active_connection_ids_on_path.end()) { cids_to_retire.push_back(cid_data.connection_id); } } for (const auto& cid : cids_to_retire) { PrepareToRetireActiveConnectionId(cid); } } bool QuicPeerIssuedConnectionIdManager::IsConnectionIdActive( const QuicConnectionId& cid) const { return FindConnectionIdData(active_connection_id_data_, cid) != active_connection_id_data_.end(); } std::vector<uint64_t> QuicPeerIssuedConnectionIdManager:: ConsumeToBeRetiredConnectionIdSequenceNumbers() { std::vector<uint64_t> result; for (auto const& cid_data : to_be_retired_connection_id_data_) { result.push_back(cid_data.sequence_number); } to_be_retired_connection_id_data_.clear(); return result; } void QuicPeerIssuedConnectionIdManager::ReplaceConnectionId( const QuicConnectionId& old_connection_id, const QuicConnectionId& new_connection_id) { auto it1 = FindConnectionIdData(&active_connection_id_data_, old_connection_id); if (it1 != active_connection_id_data_.end()) { it1->connection_id = new_connection_id; return; } auto it2 = FindConnectionIdData(&to_be_retired_connection_id_data_, old_connection_id); if (it2 != to_be_retired_connection_id_data_.end()) { it2->connection_id = new_connection_id; } } namespace { class RetireSelfIssuedConnectionIdAlarmDelegate : public QuicAlarm::DelegateWithContext { public: explicit RetireSelfIssuedConnectionIdAlarmDelegate( QuicSelfIssuedConnectionIdManager* connection_id_manager, QuicConnectionContext* context) : QuicAlarm::DelegateWithContext(context), connection_id_manager_(connection_id_manager) {} RetireSelfIssuedConnectionIdAlarmDelegate( const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete; RetireSelfIssuedConnectionIdAlarmDelegate& operator=( const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete; void OnAlarm() override { connection_id_manager_->RetireConnectionId(); } private: QuicSelfIssuedConnectionIdManager* connection_id_manager_; }; } QuicSelfIssuedConnectionIdManager::QuicSelfIssuedConnectionIdManager( size_t active_connection_id_limit, const QuicConnectionId& initial_connection_id, const QuicClock* clock, QuicAlarmFactory* alarm_factory, QuicConnectionIdManagerVisitorInterface* visitor, QuicConnectionContext* context, ConnectionIdGeneratorInterface& generator) : active_connection_id_limit_(active_connection_id_limit), clock_(clock), visitor_(visitor), retire_connection_id_alarm_(alarm_factory->CreateAlarm( new RetireSelfIssuedConnectionIdAlarmDelegate(this, context))), last_connection_id_(initial_connection_id), next_connection_id_sequence_number_(1u), last_connection_id_consumed_by_self_sequence_number_(0u), connection_id_generator_(generator) { active_connection_ids_.emplace_back(initial_connection_id, 0u); } QuicSelfIssuedConnectionIdManager::~QuicSelfIssuedConnectionIdManager() { retire_connection_id_alarm_->Cancel(); } std::optional<QuicNewConnectionIdFrame> QuicSelfIssuedConnectionIdManager::MaybeIssueNewConnectionId() { std::optional<QuicConnectionId> new_cid = connection_id_generator_.GenerateNextConnectionId(last_connection_id_); if (!new_cid.has_value()) { return {}; } if (!visitor_->MaybeReserveConnectionId(*new_cid)) { return {}; } QuicNewConnectionIdFrame frame; frame.connection_id = *new_cid; frame.sequence_number = next_connection_id_sequence_number_++; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); active_connection_ids_.emplace_back(frame.connection_id, frame.sequence_number); frame.retire_prior_to = active_connection_ids_.front().second; last_connection_id_ = frame.connection_id; return frame; } std::optional<QuicNewConnectionIdFrame> QuicSelfIssuedConnectionIdManager:: MaybeIssueNewConnectionIdForPreferredAddress() { std::optional<QuicNewConnectionIdFrame> frame = MaybeIssueNewConnectionId(); QUICHE_DCHECK(!frame.has_value() || (frame->sequence_number == 1u)); return frame; } QuicErrorCode QuicSelfIssuedConnectionIdManager::OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame, QuicTime::Delta pto_delay, std::string* error_detail) { QUICHE_DCHECK(!active_connection_ids_.empty()); if (frame.sequence_number >= next_connection_id_sequence_number_) { *error_detail = "To be retired connecton ID is never issued."; return IETF_QUIC_PROTOCOL_VIOLATION; } auto it = std::find_if(active_connection_ids_.begin(), active_connection_ids_.end(), [&frame](const std::pair<QuicConnectionId, uint64_t>& p) { return p.second == frame.sequence_number; }); if (it == active_connection_ids_.end()) { return QUIC_NO_ERROR; } if (to_be_retired_connection_ids_.size() + active_connection_ids_.size() >= kMaxNumConnectonIdsInUse) { *error_detail = "There are too many connection IDs in use."; return QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE; } QuicTime retirement_time = clock_->ApproximateNow() + 3 * pto_delay; if (!to_be_retired_connection_ids_.empty()) { retirement_time = std::max(retirement_time, to_be_retired_connection_ids_.back().second); } to_be_retired_connection_ids_.emplace_back(it->first, retirement_time); if (!retire_connection_id_alarm_->IsSet()) { retire_connection_id_alarm_->Set(retirement_time); } active_connection_ids_.erase(it); MaybeSendNewConnectionIds(); return QUIC_NO_ERROR; } std::vector<QuicConnectionId> QuicSelfIssuedConnectionIdManager::GetUnretiredConnectionIds() const { std::vector<QuicConnectionId> unretired_ids; for (const auto& cid_pair : to_be_retired_connection_ids_) { unretired_ids.push_back(cid_pair.first); } for (const auto& cid_pair : active_connection_ids_) { unretired_ids.push_back(cid_pair.first); } return unretired_ids; } QuicConnectionId QuicSelfIssuedConnectionIdManager::GetOneActiveConnectionId() const { QUICHE_DCHECK(!active_connection_ids_.empty()); return active_connection_ids_.front().first; } void QuicSelfIssuedConnectionIdManager::RetireConnectionId() { if (to_be_retired_connection_ids_.empty()) { QUIC_BUG(quic_bug_12420_1) << "retire_connection_id_alarm fired but there is no connection ID " "to be retired."; return; } QuicTime now = clock_->ApproximateNow(); auto it = to_be_retired_connection_ids_.begin(); do { visitor_->OnSelfIssuedConnectionIdRetired(it->first); ++it; } while (it != to_be_retired_connection_ids_.end() && it->second <= now); to_be_retired_connection_ids_.erase(to_be_retired_connection_ids_.begin(), it); if (!to_be_retired_connection_ids_.empty()) { retire_connection_id_alarm_->Set( to_be_retired_connection_ids_.front().second); } } void QuicSelfIssuedConnectionIdManager::MaybeSendNewConnectionIds() { while (active_connection_ids_.size() < active_connection_id_limit_) { std::optional<QuicNewConnectionIdFrame> frame = MaybeIssueNewConnectionId(); if (!frame.has_value()) { break; } if (!visitor_->SendNewConnectionId(*frame)) { break; } } } bool QuicSelfIssuedConnectionIdManager::HasConnectionIdToConsume() const { for (const auto& active_cid_data : active_connection_ids_) { if (active_cid_data.second > last_connection_id_consumed_by_self_sequence_number_) { return true; } } return false; } std::optional<QuicConnectionId> QuicSelfIssuedConnectionIdManager::ConsumeOneConnectionId() { for (const auto& active_cid_data : active_connection_ids_) { if (active_cid_data.second > last_connection_id_consumed_by_self_sequence_number_) { last_connection_id_consumed_by_self_sequence_number_ = active_cid_data.second; return active_cid_data.first; } } return std::nullopt; } bool QuicSelfIssuedConnectionIdManager::IsConnectionIdInUse( const QuicConnectionId& cid) const { for (const auto& active_cid_data : active_connection_ids_) { if (active_cid_data.first == cid) { return true; } } for (const auto& to_be_retired_cid_data : to_be_retired_connection_ids_) { if (to_be_retired_cid_data.first == cid) { return true; } } return false; } }
#include "quiche/quic/core/quic_connection_id_manager.h" #include <cstddef> #include <optional> #include <string> #include <vector> #include "quiche/quic/core/frames/quic_retire_connection_id_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/quic_connection_id_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic::test { namespace { using ::quic::test::IsError; using ::quic::test::IsQuicNoError; using ::quic::test::QuicConnectionIdManagerPeer; using ::quic::test::TestConnectionId; using ::testing::_; using ::testing::ElementsAre; using ::testing::IsNull; using ::testing::Return; using ::testing::StrictMock; class TestPeerIssuedConnectionIdManagerVisitor : public QuicConnectionIdManagerVisitorInterface { public: void SetPeerIssuedConnectionIdManager( QuicPeerIssuedConnectionIdManager* peer_issued_connection_id_manager) { peer_issued_connection_id_manager_ = peer_issued_connection_id_manager; } void OnPeerIssuedConnectionIdRetired() override { if (!peer_issued_connection_id_manager_->IsConnectionIdActive( current_peer_issued_connection_id_)) { current_peer_issued_connection_id_ = peer_issued_connection_id_manager_->ConsumeOneUnusedConnectionId() ->connection_id; } most_recent_retired_connection_id_sequence_numbers_ = peer_issued_connection_id_manager_ ->ConsumeToBeRetiredConnectionIdSequenceNumbers(); } const std::vector<uint64_t>& most_recent_retired_connection_id_sequence_numbers() { return most_recent_retired_connection_id_sequence_numbers_; } void SetCurrentPeerConnectionId(QuicConnectionId cid) { current_peer_issued_connection_id_ = cid; } const QuicConnectionId& GetCurrentPeerConnectionId() { return current_peer_issued_connection_id_; } bool SendNewConnectionId(const QuicNewConnectionIdFrame& ) override { return false; } bool MaybeReserveConnectionId(const QuicConnectionId&) override { return false; } void OnSelfIssuedConnectionIdRetired( const QuicConnectionId& ) override {} private: QuicPeerIssuedConnectionIdManager* peer_issued_connection_id_manager_ = nullptr; QuicConnectionId current_peer_issued_connection_id_; std::vector<uint64_t> most_recent_retired_connection_id_sequence_numbers_; }; class QuicPeerIssuedConnectionIdManagerTest : public QuicTest { public: QuicPeerIssuedConnectionIdManagerTest() : peer_issued_cid_manager_( 2, initial_connection_id_, &clock_, &alarm_factory_, &cid_manager_visitor_, nullptr) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); cid_manager_visitor_.SetPeerIssuedConnectionIdManager( &peer_issued_cid_manager_); cid_manager_visitor_.SetCurrentPeerConnectionId(initial_connection_id_); retire_peer_issued_cid_alarm_ = QuicConnectionIdManagerPeer::GetRetirePeerIssuedConnectionIdAlarm( &peer_issued_cid_manager_); } protected: MockClock clock_; test::MockAlarmFactory alarm_factory_; TestPeerIssuedConnectionIdManagerVisitor cid_manager_visitor_; QuicConnectionId initial_connection_id_ = TestConnectionId(0); QuicPeerIssuedConnectionIdManager peer_issued_cid_manager_; QuicAlarm* retire_peer_issued_cid_alarm_ = nullptr; std::string error_details_; bool duplicate_frame_ = false; }; TEST_F(QuicPeerIssuedConnectionIdManagerTest, ConnectionIdSequenceWhenMigrationSucceed) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); const QuicConnectionIdData* aternative_connection_id_data = peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); ASSERT_THAT(aternative_connection_id_data, testing::NotNull()); EXPECT_EQ(aternative_connection_id_data->connection_id, TestConnectionId(1)); EXPECT_EQ(aternative_connection_id_data->stateless_reset_token, frame.stateless_reset_token); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {TestConnectionId(1)}); cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(1)); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(0u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 2u; frame.retire_prior_to = 1u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {TestConnectionId(2)}); cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(2)); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(1u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(3); frame.sequence_number = 3u; frame.retire_prior_to = 2u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {TestConnectionId(3)}); cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(3)); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(2u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(4); frame.sequence_number = 4u; frame.retire_prior_to = 3u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ConnectionIdSequenceWhenMigrationFail) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {initial_connection_id_}); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(1u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 2u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {initial_connection_id_}); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(2u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(3); frame.sequence_number = 3u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {TestConnectionId(3)}); cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(3)); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(0u)); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(4); frame.sequence_number = 4u; frame.retire_prior_to = 3u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); EXPECT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); EXPECT_FALSE(retire_peer_issued_cid_alarm_->IsSet()); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ReceivesNewConnectionIdOutOfOrder) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(3); frame.sequence_number = 3u; frame.retire_prior_to = 2u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 2u; frame.retire_prior_to = 1u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } { EXPECT_FALSE( peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(0))); EXPECT_FALSE( peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(1))); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT(cid_manager_visitor_ .most_recent_retired_connection_id_sequence_numbers(), ElementsAre(0u, 1u)); EXPECT_EQ(cid_manager_visitor_.GetCurrentPeerConnectionId(), TestConnectionId(2)); EXPECT_EQ( peer_issued_cid_manager_.ConsumeOneUnusedConnectionId()->connection_id, TestConnectionId(3)); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, VisitedNewConnectionIdFrameIsIgnored) { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(); peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds( {initial_connection_id_}); ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet()); alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_); EXPECT_THAT( cid_manager_visitor_.most_recent_retired_connection_id_sequence_numbers(), ElementsAre(1u)); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); EXPECT_EQ(true, duplicate_frame_); EXPECT_THAT(peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(), testing::IsNull()); } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ErrorWhenActiveConnectionIdLimitExceeded) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 2u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsError(QUIC_CONNECTION_ID_LIMIT_ERROR)); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ErrorWhenTheSameConnectionIdIsSeenWithDifferentSequenceNumbers) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 2u; frame.retire_prior_to = 1u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(TestConnectionId(2)); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, NewConnectionIdFrameWithTheSameSequenceNumberIsIgnored) { { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(TestConnectionId(2)); EXPECT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); EXPECT_EQ(true, duplicate_frame_); EXPECT_EQ( peer_issued_cid_manager_.ConsumeOneUnusedConnectionId()->connection_id, TestConnectionId(1)); EXPECT_THAT(peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(), IsNull()); } } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ErrorWhenThereAreTooManyGapsInIssuedConnectionIdSequenceNumbers) { for (int i = 2; i <= 38; i += 2) { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(i); frame.sequence_number = i; frame.retire_prior_to = i; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsQuicNoError()); } QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(40); frame.sequence_number = 40u; frame.retire_prior_to = 40u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame( frame, &error_details_, &duplicate_frame_), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_F(QuicPeerIssuedConnectionIdManagerTest, ReplaceConnectionId) { ASSERT_TRUE( peer_issued_cid_manager_.IsConnectionIdActive(initial_connection_id_)); peer_issued_cid_manager_.ReplaceConnectionId(initial_connection_id_, TestConnectionId(1)); EXPECT_FALSE( peer_issued_cid_manager_.IsConnectionIdActive(initial_connection_id_)); EXPECT_TRUE( peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(1))); } class TestSelfIssuedConnectionIdManagerVisitor : public QuicConnectionIdManagerVisitorInterface { public: void OnPeerIssuedConnectionIdRetired() override {} MOCK_METHOD(bool, SendNewConnectionId, (const QuicNewConnectionIdFrame& frame), (override)); MOCK_METHOD(bool, MaybeReserveConnectionId, (const QuicConnectionId& connection_id), (override)); MOCK_METHOD(void, OnSelfIssuedConnectionIdRetired, (const QuicConnectionId& connection_id), (override)); }; class QuicSelfIssuedConnectionIdManagerTest : public QuicTest { public: QuicSelfIssuedConnectionIdManagerTest() : cid_manager_( 2, initial_connection_id_, &clock_, &alarm_factory_, &cid_manager_visitor_, nullptr, connection_id_generator_) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); retire_self_issued_cid_alarm_ = QuicConnectionIdManagerPeer::GetRetireSelfIssuedConnectionIdAlarm( &cid_manager_); } protected: QuicConnectionId CheckGenerate(QuicConnectionId old_cid) { QuicConnectionId new_cid = old_cid; (*new_cid.mutable_data())++; EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(old_cid)) .WillOnce(Return(new_cid)); return new_cid; } MockClock clock_; test::MockAlarmFactory alarm_factory_; TestSelfIssuedConnectionIdManagerVisitor cid_manager_visitor_; QuicConnectionId initial_connection_id_ = TestConnectionId(0); StrictMock<QuicSelfIssuedConnectionIdManager> cid_manager_; QuicAlarm* retire_self_issued_cid_alarm_ = nullptr; std::string error_details_; QuicTime::Delta pto_delay_ = QuicTime::Delta::FromMilliseconds(10); MockConnectionIdGenerator connection_id_generator_; }; MATCHER_P3(ExpectedNewConnectionIdFrame, connection_id, sequence_number, retire_prior_to, "") { return (arg.connection_id == connection_id) && (arg.sequence_number == sequence_number) && (arg.retire_prior_to == retire_prior_to); } TEST_F(QuicSelfIssuedConnectionIdManagerTest, RetireSelfIssuedConnectionIdInOrder) { QuicConnectionId cid0 = initial_connection_id_; QuicConnectionId cid1 = CheckGenerate(cid0); QuicConnectionId cid2 = CheckGenerate(cid1); QuicConnectionId cid3 = CheckGenerate(cid2); QuicConnectionId cid4 = CheckGenerate(cid3); QuicConnectionId cid5 = CheckGenerate(cid4); EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid1, 1u, 0u))) .WillOnce(Return(true)); cid_manager_.MaybeSendNewConnectionIds(); { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid2, 2u, 1u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 0u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid3)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid3, 3u, 2u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 1u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid4)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid4, 4u, 3u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 2u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid5)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid5, 5u, 4u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 3u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } } TEST_F(QuicSelfIssuedConnectionIdManagerTest, RetireSelfIssuedConnectionIdOutOfOrder) { QuicConnectionId cid0 = initial_connection_id_; QuicConnectionId cid1 = CheckGenerate(cid0); QuicConnectionId cid2 = CheckGenerate(cid1); QuicConnectionId cid3 = CheckGenerate(cid2); QuicConnectionId cid4 = CheckGenerate(cid3); EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid1, 1u, 0u))) .WillOnce(Return(true)); cid_manager_.MaybeSendNewConnectionIds(); { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid2, 2u, 0u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 1u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 1u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid3)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid3, 3u, 2u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 0u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid4)) .WillOnce(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(ExpectedNewConnectionIdFrame(cid4, 4u, 2u))) .WillOnce(Return(true)); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 3u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } { QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 0u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); } } TEST_F(QuicSelfIssuedConnectionIdManagerTest, ScheduleConnectionIdRetirementOneAtATime) { QuicConnectionId cid0 = initial_connection_id_; QuicConnectionId cid1 = CheckGenerate(cid0); QuicConnectionId cid2 = CheckGenerate(cid1); QuicConnectionId cid3 = CheckGenerate(cid2); EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_)) .Times(3) .WillRepeatedly(Return(true)); EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_)) .Times(3) .WillRepeatedly(Return(true)); QuicTime::Delta connection_id_expire_timeout = 3 * pto_delay_; QuicRetireConnectionIdFrame retire_cid_frame; cid_manager_.MaybeSendNewConnectionIds(); retire_cid_frame.sequence_number = 0u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(), ElementsAre(cid0, cid1, cid2)); EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet()); EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(), clock_.ApproximateNow() + connection_id_expire_timeout); EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid0)); clock_.AdvanceTime(connection_id_expire_timeout); alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_); EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(), ElementsAre(cid1, cid2)); EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet()); retire_cid_frame.sequence_number = 1u; ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame( retire_cid_frame, pto_delay_, &error_details_), IsQuicNoError()); EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(), ElementsAre(cid1, cid2, cid3)); EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet()); EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(), clock_.ApproximateNow() + connection_id_expire_timeout); EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid1)); clock_.AdvanceTime(connection_id_expire_timeout); alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_); EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(), ElementsAre(cid2, cid3)); EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet()); } TEST_F(QuicSelfIssuedConnectionIdManagerTest, ScheduleMultipleConnectionIdRetirement) { QuicConnectionId cid0 = initial_connection_id_; QuicConnectionId cid1 = CheckGenerate(cid0); QuicConnectionId cid2 = CheckGenerate(cid1); QuicConnectionId cid3 = CheckGenerate(cid2); EXPECT_CALL(cid_manager_visitor_, M
274
cpp
google/quiche
quic_connection
quiche/quic/core/quic_connection.cc
quiche/quic/core/quic_connection_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ #define QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ #include <cstddef> #include <cstdint> #include <list> #include <map> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_max_streams_frame.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_connection_id_manager.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_idle_network_detector.h" #include "quiche/quic/core/quic_lru_cache.h" #include "quiche/quic/core/quic_mtu_discovery.h" #include "quiche/quic/core/quic_network_blackhole_detector.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.h" #include "quiche/quic/core/quic_ping_manager.h" #include "quiche/quic/core/quic_sent_packet_manager.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/uber_received_packet_manager.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { class QuicClock; class QuicConfig; class QuicConnection; namespace test { class QuicConnectionPeer; } class QUICHE_EXPORT MultiPortPathContextObserver { public: virtual void OnMultiPortPathContextAvailable( std::unique_ptr<QuicPathValidationContext>) = 0; virtual ~MultiPortPathContextObserver() = default; }; class QUICHE_EXPORT QuicConnectionVisitorInterface { public: virtual ~QuicConnectionVisitorInterface() {} virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0; virtual void OnCryptoFrame(const QuicCryptoFrame& frame) = 0; virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0; virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0; virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0; virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0; virtual void OnMessageReceived(absl::string_view message) = 0; virtual void OnHandshakeDoneReceived() = 0; virtual void OnNewTokenReceived(absl::string_view token) = 0; virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0; virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0; virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) = 0; virtual void OnWriteBlocked() = 0; virtual void OnSuccessfulVersionNegotiation( const ParsedQuicVersion& version) = 0; virtual void OnPacketReceived(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, bool is_connectivity_probe) = 0; virtual void OnCanWrite() = 0; virtual void OnCongestionWindowChange(QuicTime now) = 0; virtual void OnConnectionMigration(AddressChangeType type) = 0; virtual void OnPathDegrading() = 0; virtual void OnForwardProgressMadeAfterPathDegrading() = 0; virtual void OnAckNeedsRetransmittableFrame() = 0; virtual void SendAckFrequency(const QuicAckFrequencyFrame& frame) = 0; virtual void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) = 0; virtual void SendRetireConnectionId(uint64_t sequence_number) = 0; virtual bool MaybeReserveConnectionId( const QuicConnectionId& server_connection_id) = 0; virtual void OnServerConnectionIdRetired( const QuicConnectionId& server_connection_id) = 0; virtual bool WillingAndAbleToWrite() const = 0; virtual bool ShouldKeepConnectionAlive() const = 0; virtual std::string GetStreamsInfoForLogging() const = 0; virtual bool AllowSelfAddressChange() const = 0; virtual HandshakeState GetHandshakeState() const = 0; virtual void OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0; virtual void OnPacketDecrypted(EncryptionLevel level) = 0; virtual void OnOneRttPacketAcknowledged() = 0; virtual void OnHandshakePacketSent() = 0; virtual void OnKeyUpdate(KeyUpdateReason reason) = 0; virtual std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; virtual void BeforeConnectionCloseSent() = 0; virtual bool ValidateToken(absl::string_view token) = 0; virtual bool MaybeSendAddressToken() = 0; virtual void CreateContextForMultiPortPath( std::unique_ptr<MultiPortPathContextObserver> context_observer) = 0; virtual void MigrateToMultiPortPath( std::unique_ptr<QuicPathValidationContext> context) = 0; virtual void OnServerPreferredAddressAvailable( const QuicSocketAddress& server_preferred_address) = 0; virtual void MaybeBundleOpportunistically() = 0; virtual QuicByteCount GetFlowControlSendWindowSize(QuicStreamId id) = 0; }; class QUICHE_EXPORT QuicConnectionDebugVisitor : public QuicSentPacketManager::DebugDelegate { public: ~QuicConnectionDebugVisitor() override {} virtual void OnPacketSent(QuicPacketNumber , QuicPacketLength , bool , TransmissionType , EncryptionLevel , const QuicFrames& , const QuicFrames& , QuicTime , uint32_t ) {} virtual void OnCoalescedPacketSent( const QuicCoalescedPacket& , size_t ) {} virtual void OnPingSent() {} virtual void OnPacketReceived(const QuicSocketAddress& , const QuicSocketAddress& , const QuicEncryptedPacket& ) {} virtual void OnUnauthenticatedHeader(const QuicPacketHeader& ) {} virtual void OnIncorrectConnectionId(QuicConnectionId ) {} virtual void OnUndecryptablePacket(EncryptionLevel , bool ) {} virtual void OnAttemptingToProcessUndecryptablePacket( EncryptionLevel ) {} virtual void OnDuplicatePacket(QuicPacketNumber ) {} virtual void OnProtocolVersionMismatch(ParsedQuicVersion ) {} virtual void OnPacketHeader(const QuicPacketHeader& , QuicTime , EncryptionLevel ) {} virtual void OnStreamFrame(const QuicStreamFrame& ) {} virtual void OnCryptoFrame(const QuicCryptoFrame& ) {} virtual void OnPaddingFrame(const QuicPaddingFrame& ) {} virtual void OnPingFrame(const QuicPingFrame& , QuicTime::Delta ) {} virtual void OnGoAwayFrame(const QuicGoAwayFrame& ) {} virtual void OnRstStreamFrame(const QuicRstStreamFrame& ) {} virtual void OnConnectionCloseFrame( const QuicConnectionCloseFrame& ) {} virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& , const QuicTime& ) {} virtual void OnBlockedFrame(const QuicBlockedFrame& ) {} virtual void OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& ) {} virtual void OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& ) {} virtual void OnNewTokenFrame(const QuicNewTokenFrame& ) {} virtual void OnMessageFrame(const QuicMessageFrame& ) {} virtual void OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& ) {} virtual void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& ) {} virtual void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) {} virtual void OnSuccessfulVersionNegotiation( const ParsedQuicVersion& ) {} virtual void OnSendConnectionState( const CachedNetworkParameters& ) {} virtual void OnReceiveConnectionState( const CachedNetworkParameters& ) {} virtual void OnSetFromConfig(const QuicConfig& ) {} virtual void OnRttChanged(QuicTime::Delta ) const {} virtual void OnStopSendingFrame(const QuicStopSendingFrame& ) {} virtual void OnPathChallengeFrame(const QuicPathChallengeFrame& ) {} virtual void OnPathResponseFrame(const QuicPathResponseFrame& ) {} virtual void OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& ) { } virtual void OnMaxStreamsFrame(const QuicMaxStreamsFrame& ) {} virtual void OnAckFrequencyFrame(const QuicAckFrequencyFrame& ) {} virtual void OnResetStreamAtFrame(const QuicResetStreamAtFrame& ) {} virtual void OnNPacketNumbersSkipped(QuicPacketCount , QuicTime ) {} virtual void OnPacketDiscarded(const SerializedPacket& ) {} virtual void OnTransportParametersSent( const TransportParameters& ) {} virtual void OnTransportParametersReceived( const TransportParameters& ) {} virtual void OnTransportParametersResumed( const TransportParameters& ) {} virtual void OnZeroRttRejected(int ) {} virtual void OnZeroRttPacketAcked() {} virtual void OnPeerAddressChange(AddressChangeType , QuicTime::Delta ) {} virtual void OnPeerMigrationValidated(QuicTime::Delta ) {} virtual void OnEncryptedClientHelloSent(absl::string_view ) {} virtual void OnEncryptedClientHelloReceived( absl::string_view ) {} }; class QUICHE_EXPORT QuicConnectionHelperInterface { public: virtual ~QuicConnectionHelperInterface() {} virtual const QuicClock* GetClock() const = 0; virtual QuicRandom* GetRandomGenerator() = 0; virtual quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() = 0; }; class QUICHE_EXPORT QuicConnection : public QuicFramerVisitorInterface, public QuicBlockedWriterInterface, public QuicPacketCreator::DelegateInterface, public QuicSentPacketManager::NetworkChangeVisitor, public QuicNetworkBlackholeDetector::Delegate, public QuicIdleNetworkDetector::Delegate, public QuicPathValidator::SendDelegate, public QuicConnectionIdManagerVisitorInterface, public QuicPingManager::Delegate, public QuicConnectionAlarmsDelegate { public: QuicConnection(QuicConnectionId server_connection_id, QuicSocketAddress initial_self_address, QuicSocketAddress initial_peer_address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, QuicPacketWriter* writer, bool owns_writer, Perspective perspective, const ParsedQuicVersionVector& supported_versions, ConnectionIdGeneratorInterface& generator); QuicConnection(const QuicConnection&) = delete; QuicConnection& operator=(const QuicConnection&) = delete; ~QuicConnection() override; struct MultiPortStats { RttStats rtt_stats; RttStats rtt_stats_when_default_path_degrading; size_t num_multi_port_probe_failures_when_path_not_degrading = 0; size_t num_multi_port_probe_failures_when_path_degrading = 0; size_t num_multi_port_paths_created = 0; size_t num_client_probing_attempts = 0; size_t num_successful_probes = 0; }; void SetFromConfig(const QuicConfig& config); void ApplyConnectionOptions(const QuicTagVector& connection_options); virtual void OnSendConnectionState( const CachedNetworkParameters& cached_network_params); virtual void OnReceiveConnectionState( const CachedNetworkParameters& cached_network_params); virtual void ResumeConnectionState( const CachedNetworkParameters& cached_network_params, bool max_bandwidth_resumption); virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate); void AdjustNetworkParameters( const SendAlgorithmInterface::NetworkParams& params); void AdjustNetworkParameters(QuicBandwidth bandwidth, QuicTime::Delta rtt, bool allow_cwnd_to_decrease); void SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner); void OnConfigNegotiated(); virtual QuicBandwidth MaxPacingRate() const; virtual size_t SendCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset); virtual QuicConsumedData SendStreamData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state); virtual bool SendControlFrame(const QuicFrame& frame); virtual void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error); virtual void CloseConnection( QuicErrorCode error, const std::string& details, ConnectionCloseBehavior connection_close_behavior); virtual void CloseConnection( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details, ConnectionCloseBehavior connection_close_behavior); QuicConnectionStats& mutable_stats() { return stats_; } const QuicConnectionStats& GetStats(); virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet); void OnBlockedWriterCanWrite() override; bool IsWriterBlocked() const override { return writer_ != nullptr && writer_->IsWriteBlocked(); } virtual void OnCanWrite(); void OnWriteError(int error_code); bool IsMsgTooBig(const QuicPacketWriter* writer, const WriteResult& result); void OnSendAlarm() override; void WriteIfNotBlocked(); void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) { QUICHE_DCHECK(writer != nullptr); if (writer_ != nullptr && owns_writer_) { delete writer_; } writer_ = writer; owns_writer_ = owns_writer; } void SetSelfAddress(QuicSocketAddress address) { default_path_.self_address = address; } QuicTransportVersion transport_version() const { return framer_.transport_version(); } ParsedQuicVersion version() const { return framer_.version(); } const ParsedQuicVersionVector& supported_versions() const { return framer_.supported_versions(); } void SetVersionNegotiated() { version_negotiated_ = true; } void OnError(QuicFramer* framer) override; bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override; void OnPacket() override; void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) override; void OnRetryPacket(QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag) override; bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; void OnDecryptedPacket(size_t length, EncryptionLevel level) override; bool OnPacketHeader(const QuicPacketHeader& header) override; void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override; bool OnStreamFrame(const QuicStreamFrame& frame) override; bool OnCryptoFrame(const QuicCryptoFrame& frame) override; bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override; bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override; bool OnAckFrameEnd(QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) override; bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; bool OnPaddingFrame(const QuicPaddingFrame& frame) override; bool OnPingFrame(const QuicPingFrame& frame) override; bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; bool OnBlockedFrame(const QuicBlockedFrame& frame) override; bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override; bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; bool OnMessageFrame(const QuicMessageFrame& frame) override; bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override; bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override; void OnPacketComplete() override; bool IsValidStatelessResetToken( const StatelessResetToken& token) const override; void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) override; void OnKeyUpdate(KeyUpdateReason reason) override; void OnDecryptedFirstPacketInKeyPhase() override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneR
#include "quiche/quic/core/quic_connection.h" #include <errno.h> #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/congestion_control/loss_detection_interface.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_path_response_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_coalesced_packet_peer.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_packet_creator_peer.h" #include "quiche/quic/test_tools/quic_path_validator_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" #include "quiche/quic/test_tools/simple_session_notifier.h" #include "quiche/common/simple_buffer_allocator.h" using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::DoAll; using testing::ElementsAre; using testing::Ge; using testing::IgnoreResult; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Lt; using testing::Ref; using testing::Return; using testing::SaveArg; using testing::SetArgPointee; using testing::StrictMock; namespace quic { namespace test { namespace { const char data1[] = "foo data"; const char data2[] = "bar data"; const bool kHasStopWaiting = true; const int kDefaultRetransmissionTimeMs = 500; DiversificationNonce kTestDiversificationNonce = { 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', }; const StatelessResetToken kTestStatelessResetToken{ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}; const QuicSocketAddress kPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 12345); const QuicSocketAddress kSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 443); const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress( []() { QuicIpAddress address; address.FromString("2604:31c0::"); return address; }(), 443); QuicStreamId GetNthClientInitiatedStreamId(int n, QuicTransportVersion version) { return QuicUtils::GetFirstBidirectionalStreamId(version, Perspective::IS_CLIENT) + n * 2; } QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: return INITIAL; case ENCRYPTION_HANDSHAKE: return HANDSHAKE; case ENCRYPTION_ZERO_RTT: return ZERO_RTT_PROTECTED; case ENCRYPTION_FORWARD_SECURE: QUICHE_DCHECK(false); return INVALID_PACKET_TYPE; default: QUICHE_DCHECK(false); return INVALID_PACKET_TYPE; } } class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter { public: TaggingEncrypterWithConfidentialityLimit( uint8_t tag, QuicPacketCount confidentiality_limit) : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {} QuicPacketCount GetConfidentialityLimit() const override { return confidentiality_limit_; } private: QuicPacketCount confidentiality_limit_; }; class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter { public: StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag, QuicPacketCount integrity_limit) : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {} QuicPacketCount GetIntegrityLimit() const override { return integrity_limit_; } private: QuicPacketCount integrity_limit_; }; class TestConnectionHelper : public QuicConnectionHelperInterface { public: TestConnectionHelper(MockClock* clock, MockRandom* random_generator) : clock_(clock), random_generator_(random_generator) { clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); } TestConnectionHelper(const TestConnectionHelper&) = delete; TestConnectionHelper& operator=(const TestConnectionHelper&) = delete; const QuicClock* GetClock() const override { return clock_; } QuicRandom* GetRandomGenerator() override { return random_generator_; } quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override { return &buffer_allocator_; } private: MockClock* clock_; MockRandom* random_generator_; quiche::SimpleBufferAllocator buffer_allocator_; }; class TestConnection : public QuicConnection { public: TestConnection(QuicConnectionId connection_id, QuicSocketAddress initial_self_address, QuicSocketAddress initial_peer_address, TestConnectionHelper* helper, TestAlarmFactory* alarm_factory, TestPacketWriter* writer, Perspective perspective, ParsedQuicVersion version, ConnectionIdGeneratorInterface& generator) : QuicConnection(connection_id, initial_self_address, initial_peer_address, helper, alarm_factory, writer, false, perspective, SupportedVersions(version), generator), notifier_(nullptr) { writer->set_perspective(perspective); SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); SetDataProducer(&producer_); ON_CALL(*this, OnSerializedPacket(_)) .WillByDefault([this](SerializedPacket packet) { QuicConnection::OnSerializedPacket(std::move(packet)); }); } TestConnection(const TestConnection&) = delete; TestConnection& operator=(const TestConnection&) = delete; MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override)); void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override { QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable); if (is_migration_linkable) { num_linkable_client_migration_++; } else { num_unlinkable_client_migration_++; } } uint32_t num_unlinkable_client_migration() const { return num_unlinkable_client_migration_; } uint32_t num_linkable_client_migration() const { return num_linkable_client_migration_; } void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) { QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm); } void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) { QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm); } void SendPacket(EncryptionLevel , uint64_t packet_number, std::unique_ptr<QuicPacket> packet, HasRetransmittableData retransmittable, bool has_ack, bool has_pending_frames) { ScopedPacketFlusher flusher(this); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = QuicConnectionPeer::GetFramer(this)->EncryptPayload( ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet, buffer, kMaxOutgoingPacketSize); SerializedPacket serialized_packet( QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer, encrypted_length, has_ack, has_pending_frames); serialized_packet.peer_address = kPeerAddress; if (retransmittable == HAS_RETRANSMITTABLE_DATA) { serialized_packet.retransmittable_frames.push_back( QuicFrame(QuicPingFrame())); } OnSerializedPacket(std::move(serialized_packet)); } QuicConsumedData SaveAndSendStreamData(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION); } QuicConsumedData SaveAndSendStreamData(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state, TransmissionType transmission_type) { ScopedPacketFlusher flusher(this); producer_.SaveStreamData(id, data); if (notifier_ != nullptr) { return notifier_->WriteOrBufferData(id, data.length(), state, transmission_type); } return QuicConnection::SendStreamData(id, data.length(), offset, state); } QuicConsumedData SendStreamDataWithString(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { ScopedPacketFlusher flusher(this); if (!QuicUtils::IsCryptoStreamId(transport_version(), id) && this->encryption_level() == ENCRYPTION_INITIAL) { this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) { OnHandshakeComplete(); } if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(this); } } return SaveAndSendStreamData(id, data, offset, state); } QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level, QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { ScopedPacketFlusher flusher(this); QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT); SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(encryption_level)); SetDefaultEncryptionLevel(encryption_level); return SaveAndSendStreamData(id, data, offset, state); } QuicConsumedData SendStreamData3() { return SendStreamDataWithString( GetNthClientInitiatedStreamId(1, transport_version()), "food", 0, NO_FIN); } QuicConsumedData SendStreamData5() { return SendStreamDataWithString( GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0, NO_FIN); } QuicConsumedData EnsureWritableAndSendStreamData5() { EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA)); return SendStreamData5(); } QuicConsumedData SendCryptoStreamData() { QuicStreamOffset offset = 0; absl::string_view data("chlo"); if (!QuicVersionUsesCryptoFrames(transport_version())) { return SendCryptoDataWithString(data, offset); } producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data); size_t bytes_written; if (notifier_) { bytes_written = notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset); } else { bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL, data.length(), offset); } return QuicConsumedData(bytes_written, false); } QuicConsumedData SendCryptoDataWithString(absl::string_view data, QuicStreamOffset offset) { return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL); } QuicConsumedData SendCryptoDataWithString(absl::string_view data, QuicStreamOffset offset, EncryptionLevel encryption_level) { if (!QuicVersionUsesCryptoFrames(transport_version())) { return SendStreamDataWithString( QuicUtils::GetCryptoStreamId(transport_version()), data, offset, NO_FIN); } producer_.SaveCryptoData(encryption_level, offset, data); size_t bytes_written; if (notifier_) { bytes_written = notifier_->WriteCryptoData(encryption_level, data.length(), offset); } else { bytes_written = QuicConnection::SendCryptoData(encryption_level, data.length(), offset); } return QuicConsumedData(bytes_written, false); } void set_version(ParsedQuicVersion version) { QuicConnectionPeer::GetFramer(this)->set_version(version); } void SetSupportedVersions(const ParsedQuicVersionVector& versions) { QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions); writer()->SetSupportedVersions(versions); } void set_perspective(Perspective perspective) { writer()->set_perspective(perspective); QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this); QuicConnectionPeer::SetPerspective(this, perspective); QuicSentPacketManagerPeer::SetPerspective( QuicConnectionPeer::GetSentPacketManager(this), perspective); QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators( TestConnectionId()); } void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) { ASSERT_EQ(Perspective::IS_SERVER, perspective()); if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) { OnConfigNegotiated(); } else { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kMTUH); config.SetInitialReceivedConnectionOptions(connection_options); EXPECT_CALL(*send_algorithm, SetFromConfig(_, _)); SetFromConfig(config); } EXPECT_CALL(*send_algorithm, PacingRate(_)) .WillRepeatedly(Return(QuicBandwidth::Infinite())); } TestAlarmFactory::TestAlarm* GetAckAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetAckAlarm(this)); } TestAlarmFactory::TestAlarm* GetPingAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetPingAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetRetransmissionAlarm(this)); } TestAlarmFactory::TestAlarm* GetSendAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetSendAlarm(this)); } TestAlarmFactory::TestAlarm* GetTimeoutAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this)); } TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetMtuDiscoveryAlarm(this)); } TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this)); } TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this)); } TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this)); } TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetBlackholeDetectorAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this)); } TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetMultiPortProbingAlarm(this)); } void PathDegradingTimeout() { QUICHE_DCHECK(PathDegradingDetectionInProgress()); GetBlackholeDetectorAlarm()->Fire(); } bool PathDegradingDetectionInProgress() { return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized(); } bool BlackholeDetectionInProgress() { return QuicConnectionPeer::GetBlackholeDetectionDeadline(this) .IsInitialized(); } bool PathMtuReductionDetectionInProgress() { return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this) .IsInitialized(); } QuicByteCount GetBytesInFlight() { return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight(); } void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; } void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) { next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr); } void SendOrQueuePacket(SerializedPacket packet) override { QuicConnection::SendOrQueuePacket(std::move(packet)); self_address_on_default_path_while_sending_packet_ = self_address(); } QuicSocketAddress self_address_on_default_path_while_sending_packet() { return self_address_on_default_path_while_sending_packet_; } SimpleDataProducer* producer() { return &producer_; } using QuicConnection::active_effective_peer_migration_type; using QuicConnection::IsCurrentPacketConnectivityProbing; using QuicConnection::SelectMutualVersion; using QuicConnection::set_defer_send_in_response_to_packets; protected: QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override { if (next_effective_peer_addr_) { return *std::move(next_effective_peer_addr_); } return QuicConnection::GetEffectivePeerAddressFromCurrentPacket(); } private: TestPacketWriter* writer() { return static_cast<TestPacketWriter*>(QuicConnection::writer()); } SimpleDataProducer producer_; SimpleSessionNotifier* notifier_; std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_; QuicSocketAddress self_address_on_default_path_while_sending_packet_; uint32_t num_unlinkable_client_migration_ = 0; uint32_t num_linkable_client_migration_ = 0; }; enum class AckResponse { kDefer, kImmediate }; struct TestParams { TestParams(ParsedQuicVersion version, AckResponse ack_response) : version(version), ack_response(ack_response) {} ParsedQuicVersion version; AckResponse ack_response; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")); } std::vector<TestParams> GetTestParams() { QuicFlagSaver flags; std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (size_t i = 0; i < all_supported_versions.size(); ++i) { for (AckResponse ack_response : {AckResponse::kDefer, AckResponse::kImmediate}) { params.push_back(TestParams(all_supported_versions[i], ack_response)); } } return params; } class QuicConnectionTest : public QuicTestWithParam<TestParams> { public: void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame, ConnectionCloseSource ) { saved_connection_close_frame_ = frame; connection_close_frame_count_++; } protected: QuicConnectionTest() : connection_id_(TestConnectionId()), framer_(SupportedVersions(version()), QuicTime::Zero(), Perspective::IS_CLIENT, connection_id_.length()), send_algorithm_(new StrictMock<MockSendAlgorithm>), loss_algorithm_(new MockLossAlgorithm()), helper_(new TestConnectionHelper(&clock_, &random_generator_)), alarm_factory_(new TestAlarmFactory()), peer_framer_(SupportedVersions(version()), QuicTime::Zero(), Perspective::IS_SERVER, connection_id_.length()), peer_creator_(connection_id_, &peer_framer_, nullptr), writer_( new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)), connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT, version(), connection_id_generator_), creator_(QuicConnectionPeer::GetPacketCreator(&connection_)), manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)), frame1_(0, false, 0, absl::string_view(data1)), frame2_(0, false, 3, absl::string_view(data2)), crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)), packet_number_length_(PACKET_4BYTE_PACKET_NUMBER), connection_id_included_(CONNECTION_ID_PRESENT), notifier_(&connection_), connection_close_frame_count_(0) { QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")"; connection_.set_defer_send_in_response_to_packets(GetParam().ack_response == AckResponse::kDefer); framer_.SetInitialObfuscators(TestConnectionId()); connection_.InstallInitialCrypters(TestConnectionId()); CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(), TestConnectionId(), &crypters); peer_creator_.SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter)); if (version().KnowsWhichDecrypterToUse()) { peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } else { peer_framer_.SetDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { peer_creator_.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); } QuicFramerPeer::SetLastSerializedServerConnectionId( QuicConnectionPeer::GetFramer(&connection_), connection_id_); QuicFramerPeer::SetLastWrittenPacketNumberLength( QuicConnectionPeer::GetFramer(&connection_), packet_number_length_); QuicStreamId stream_id; if (QuicVersionUsesCryptoFrames(version().transport_version)) { stream_id = QuicUtils::GetFirstBidirectionalStreamId( version().transport_version, Perspective::IS_CLIENT); } else { stream_id = QuicUtils::GetCryptoStreamId(version().transport_version); } frame1_.stream_id = stream_id; frame2_.stream_id = stream_id; connection_.set_visitor(&visitor_); connection_.SetSessionNotifier(&notifier_); connection_.set_notifier(&notifier_); connection_.SetSendAlgorithm(send_algorithm_); connection_.SetLossAlgorithm(loss_algorithm_.get()); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, PacingRate(_)) .WillRepeatedly(Return(QuicBandwidth::Zero())); EXPECT_CALL(*send_algorithm_, BandwidthEstimate()) .Times(AnyNumber()) .WillRepeatedly(Return(QuicBandwidth::Zero())); EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionControlType()) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionControlType()) .Times(AnyNumber()); EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillRepeatedly( Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite)); EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnCanWrite()) .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite)); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(false)); EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber()); EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()) .Times(testing::AtMost(1)); EXPECT_CALL(*loss_algorithm_, GetLossTimeout()) .WillRepeatedly(Return(QuicTime::Zero())); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_START)); if (connection_.version().KnowsWhichDecrypterToUse()) { connection_.InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); } else { connection_.SetAlternativeDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE), false); } peer_creator_.SetDefaultPeerAddress(kSelfAddress); } QuicConnectionTest(const QuicConnectionTest&) = delete; QuicConnectionTest& operator=(const QuicConnectionTest&) = delete; ParsedQuicVersion version() { return GetParam().version; } void SetClientConnectionId(const QuicConnectionId& client_connection_id) { connection_.set_client_connection_id(client_connection_id); writer_->framer()->framer()->SetExpectedClientConnectionIdLength( client_connection_id.length()); } void SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { if (connection_.version().KnowsWhichDecrypterToUse()) { connection_.InstallDecrypter(level, std::move(decrypter)); } else { connection_.SetAlternativeDecrypter(level, std::move(decrypter), false); } } void ProcessPacket(uint64_t number) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(number); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } } void ProcessReceivedPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { connection_.ProcessUdpPacket(self_address, peer_address, packet); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } } QuicFrame MakeCryptoFrame() const { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return QuicFrame(new QuicCryptoFrame(crypto_frame_)); } return QuicFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u, absl::string_view())); } void ProcessFramePacket(QuicFrame frame) { ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); } void ProcessFramePacketWithAddresses(QuicFrame frame, QuicSocketAddress self_address, QuicSocketAddress peer_address, EncryptionLevel level) { QuicFrames frames; frames.push_back(QuicFrame(frame)); return ProcessFramesPacketWithAddresses(frames, self_address, peer_address, level); } std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames, EncryptionLevel level, char* buffer, size_t buffer_len) { QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level)); peer_creator_.set_encryption_level(level); QuicPacketCreatorPeer::SetSendVersionInPacket( &peer_creator_, level < ENCRYPTION_FORWARD_SECURE && connection_.perspective() == Perspective::IS_SERVER); SerializedPacket serialized_packet = QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames, buffer, buffer_len); return std::make_unique<QuicReceivedPacket>( serialized_packet.encrypted_buffer, serialized_packet.encrypted_length, clock_.Now()); } void ProcessFramesPacketWithAddresses(QuicFrames frames,
275
cpp
google/quiche
quic_generic_session
quiche/quic/core/quic_generic_session.cc
quiche/quic/core/quic_generic_session_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_GENERIC_CLIENT_SESSION_H_ #define QUICHE_QUIC_CORE_QUIC_GENERIC_CLIENT_SESSION_H_ #include <cstdint> #include <memory> #include "absl/algorithm/container.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_datagram_queue.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/web_transport_stats.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/web_transport/web_transport.h" namespace quic { class QuicGenericStream; QUICHE_EXPORT ParsedQuicVersionVector GetQuicVersionsForGenericSession(); using CreateWebTransportSessionVisitorCallback = quiche::UnretainedCallback<std::unique_ptr<webtransport::SessionVisitor>( webtransport::Session& session)>; class QUICHE_EXPORT QuicGenericSessionBase : public QuicSession, public webtransport::Session { public: QuicGenericSessionBase( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer); ~QuicGenericSessionBase(); std::vector<std::string> GetAlpnsToOffer() const override { return std::vector<std::string>({alpn_}); } std::vector<absl::string_view>::const_iterator SelectAlpn( const std::vector<absl::string_view>& alpns) const override { return absl::c_find(alpns, alpn_); } void OnAlpnSelected(absl::string_view alpn) override { QUICHE_DCHECK_EQ(alpn, alpn_); } void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) override; bool ShouldKeepConnectionAlive() const override { return true; } QuicStream* CreateIncomingStream(QuicStreamId id) override; QuicStream* CreateIncomingStream(PendingStream* ) override { QUIC_BUG(QuicGenericSessionBase_PendingStream) << "QuicGenericSessionBase::CreateIncomingStream(PendingStream) not " "implemented"; return nullptr; } void OnTlsHandshakeComplete() override; void OnMessageReceived(absl::string_view message) override; webtransport::Stream* AcceptIncomingBidirectionalStream() override; webtransport::Stream* AcceptIncomingUnidirectionalStream() override; bool CanOpenNextOutgoingBidirectionalStream() override { return QuicSession::CanOpenNextOutgoingBidirectionalStream(); } bool CanOpenNextOutgoingUnidirectionalStream() override { return QuicSession::CanOpenNextOutgoingUnidirectionalStream(); } webtransport::Stream* OpenOutgoingBidirectionalStream() override; webtransport::Stream* OpenOutgoingUnidirectionalStream() override; webtransport::Stream* GetStreamById(webtransport::StreamId id) override; webtransport::DatagramStatus SendOrQueueDatagram( absl::string_view datagram) override; void SetDatagramMaxTimeInQueue(absl::Duration max_time_in_queue) override { datagram_queue()->SetMaxTimeInQueue(QuicTimeDelta(max_time_in_queue)); } webtransport::DatagramStats GetDatagramStats() override { return WebTransportDatagramStatsForQuicSession(*this); } webtransport::SessionStats GetSessionStats() override { return WebTransportStatsForQuicSession(*this); } void NotifySessionDraining() override {} void SetOnDraining(quiche::SingleUseCallback<void()>) override {} void CloseSession(webtransport::SessionErrorCode error_code, absl::string_view error_message) override { connection()->CloseConnection( QUIC_NO_ERROR, static_cast<QuicIetfTransportErrorCodes>(error_code), std::string(error_message), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } QuicByteCount GetMaxDatagramSize() const override { return GetGuaranteedLargestMessagePayload(); } private: QuicGenericStream* CreateStream(QuicStreamId id); void OnCanCreateNewOutgoingStream(bool unidirectional) override; std::string alpn_; webtransport::SessionVisitor* visitor_; bool owns_connection_; bool owns_visitor_; quiche::QuicheCircularDeque<QuicStreamId> incoming_bidirectional_streams_; quiche::QuicheCircularDeque<QuicStreamId> incoming_unidirectional_streams_; }; class QUICHE_EXPORT QuicGenericClientSession final : public QuicGenericSessionBase { public: QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config); QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config); void CryptoConnect() { crypto_stream_->CryptoConnect(); } QuicCryptoStream* GetMutableCryptoStream() override { return crypto_stream_.get(); } const QuicCryptoStream* GetCryptoStream() const override { return crypto_stream_.get(); } private: std::unique_ptr<QuicCryptoClientStream> crypto_stream_; }; class QUICHE_EXPORT QuicGenericServerSession final : public QuicGenericSessionBase { public: QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache); QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache); QuicCryptoStream* GetMutableCryptoStream() override { return crypto_stream_.get(); } const QuicCryptoStream* GetCryptoStream() const override { return crypto_stream_.get(); } private: std::unique_ptr<QuicCryptoServerStreamBase> crypto_stream_; }; } #endif #include "quiche/quic/core/quic_generic_session.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/web_transport_stream_adapter.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/web_transport/web_transport.h" namespace quic { namespace { class NoOpProofHandler : public QuicCryptoClientStream::ProofHandler { public: void OnProofValid(const QuicCryptoClientConfig::CachedState&) override {} void OnProofVerifyDetailsAvailable(const ProofVerifyDetails&) override {} }; class NoOpServerCryptoHelper : public QuicCryptoServerStreamBase::Helper { public: bool CanAcceptClientHello(const CryptoHandshakeMessage& , const QuicSocketAddress& , const QuicSocketAddress& , const QuicSocketAddress& , std::string* ) const override { return true; } }; } ParsedQuicVersionVector GetQuicVersionsForGenericSession() { return {ParsedQuicVersion::RFCv1()}; } class QUICHE_EXPORT QuicGenericStream : public QuicStream { public: QuicGenericStream(QuicStreamId id, QuicSession* session) : QuicStream(id, session, false, QuicUtils::GetStreamType( id, session->connection()->perspective(), session->IsIncomingStream(id), session->version())), adapter_(session, this, sequencer(), std::nullopt) { adapter_.SetPriority(webtransport::StreamPriority{0, 0}); } WebTransportStreamAdapter* adapter() { return &adapter_; } void OnDataAvailable() override { adapter_.OnDataAvailable(); } void OnCanWriteNewData() override { adapter_.OnCanWriteNewData(); } private: WebTransportStreamAdapter adapter_; }; QuicGenericSessionBase::QuicGenericSessionBase( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, WebTransportVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer) : QuicSession(connection, owner, config, GetQuicVersionsForGenericSession(), 0, std::move(datagram_observer), QuicPriorityType::kWebTransport), alpn_(std::move(alpn)), visitor_(visitor), owns_connection_(owns_connection), owns_visitor_(owns_visitor) {} QuicGenericSessionBase::~QuicGenericSessionBase() { if (owns_connection_) { DeleteConnection(); } if (owns_visitor_) { delete visitor_; visitor_ = nullptr; } } QuicStream* QuicGenericSessionBase::CreateIncomingStream(QuicStreamId id) { QUIC_DVLOG(1) << "Creating incoming QuicGenricStream " << id; QuicGenericStream* stream = CreateStream(id); if (stream->type() == BIDIRECTIONAL) { incoming_bidirectional_streams_.push_back(id); visitor_->OnIncomingBidirectionalStreamAvailable(); } else { incoming_unidirectional_streams_.push_back(id); visitor_->OnIncomingUnidirectionalStreamAvailable(); } return stream; } void QuicGenericSessionBase::OnTlsHandshakeComplete() { QuicSession::OnTlsHandshakeComplete(); visitor_->OnSessionReady(); } webtransport::Stream* QuicGenericSessionBase::AcceptIncomingBidirectionalStream() { while (!incoming_bidirectional_streams_.empty()) { webtransport::Stream* stream = GetStreamById(incoming_bidirectional_streams_.front()); incoming_bidirectional_streams_.pop_front(); if (stream != nullptr) { return stream; } } return nullptr; } webtransport::Stream* QuicGenericSessionBase::AcceptIncomingUnidirectionalStream() { while (!incoming_unidirectional_streams_.empty()) { webtransport::Stream* stream = GetStreamById(incoming_unidirectional_streams_.front()); incoming_unidirectional_streams_.pop_front(); if (stream != nullptr) { return stream; } } return nullptr; } webtransport::Stream* QuicGenericSessionBase::OpenOutgoingBidirectionalStream() { if (!CanOpenNextOutgoingBidirectionalStream()) { QUIC_BUG(QuicGenericSessionBase_flow_control_violation_bidi) << "Attempted to open a stream in violation of flow control"; return nullptr; } return CreateStream(GetNextOutgoingBidirectionalStreamId())->adapter(); } webtransport::Stream* QuicGenericSessionBase::OpenOutgoingUnidirectionalStream() { if (!CanOpenNextOutgoingUnidirectionalStream()) { QUIC_BUG(QuicGenericSessionBase_flow_control_violation_unidi) << "Attempted to open a stream in violation of flow control"; return nullptr; } return CreateStream(GetNextOutgoingUnidirectionalStreamId())->adapter(); } QuicGenericStream* QuicGenericSessionBase::CreateStream(QuicStreamId id) { auto stream = std::make_unique<QuicGenericStream>(id, this); QuicGenericStream* stream_ptr = stream.get(); ActivateStream(std::move(stream)); return stream_ptr; } void QuicGenericSessionBase::OnMessageReceived(absl::string_view message) { visitor_->OnDatagramReceived(message); } void QuicGenericSessionBase::OnCanCreateNewOutgoingStream(bool unidirectional) { if (unidirectional) { visitor_->OnCanCreateNewOutgoingUnidirectionalStream(); } else { visitor_->OnCanCreateNewOutgoingBidirectionalStream(); } } webtransport::Stream* QuicGenericSessionBase::GetStreamById( webtransport::StreamId id) { QuicStream* stream = GetActiveStream(id); if (stream == nullptr) { return nullptr; } return static_cast<QuicGenericStream*>(stream)->adapter(); } webtransport::DatagramStatus QuicGenericSessionBase::SendOrQueueDatagram( absl::string_view datagram) { quiche::QuicheBuffer buffer = quiche::QuicheBuffer::Copy( quiche::SimpleBufferAllocator::Get(), datagram); return MessageStatusToWebTransportStatus( datagram_queue()->SendOrQueueDatagram( quiche::QuicheMemSlice(std::move(buffer)))); } void QuicGenericSessionBase::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { QuicSession::OnConnectionClosed(frame, source); visitor_->OnSessionClosed(static_cast<webtransport::SessionErrorCode>( frame.transport_close_frame_type), frame.error_details); } QuicGenericClientSession::QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config) : QuicGenericSessionBase(connection, owns_connection, owner, config, std::move(alpn), visitor, owns_visitor, std::move(datagram_observer)) { static NoOpProofHandler* handler = new NoOpProofHandler(); crypto_stream_ = std::make_unique<QuicCryptoClientStream>( QuicServerId(std::move(host), port), this, crypto_config->proof_verifier()->CreateDefaultContext(), crypto_config, handler, false); } QuicGenericClientSession::QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config) : QuicGenericClientSession( connection, owns_connection, owner, config, std::move(host), port, std::move(alpn), std::move(create_visitor_callback)(*this).release(), true, std::move(datagram_observer), crypto_config) {} QuicGenericServerSession::QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicGenericSessionBase(connection, owns_connection, owner, config, std::move(alpn), visitor, owns_visitor, std::move(datagram_observer)) { static NoOpServerCryptoHelper* helper = new NoOpServerCryptoHelper(); crypto_stream_ = CreateCryptoServerStream( crypto_config, compressed_certs_cache, this, helper); } QuicGenericServerSession::QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicGenericServerSession( connection, owns_connection, owner, config, std::move(alpn), std::move(create_visitor_callback)(*this).release(), true, std::move(datagram_observer), crypto_config, compressed_certs_cache) {} }
#include "quiche/quic/core/quic_generic_session.h" #include <cstddef> #include <cstring> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_datagram_queue.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/web_transport_interface.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/test_harness.h" #include "quiche/quic/test_tools/web_transport_test_tools.h" #include "quiche/quic/tools/web_transport_test_visitors.h" #include "quiche/common/quiche_stream.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/web_transport.h" namespace quic::test { namespace { enum ServerType { kDiscardServer, kEchoServer }; using quiche::test::StatusIs; using simulator::Simulator; using testing::_; using testing::Assign; using testing::AtMost; using testing::Eq; class CountingDatagramObserver : public QuicDatagramQueue::Observer { public: CountingDatagramObserver(int& total) : total_(total) {} void OnDatagramProcessed(std::optional<MessageStatus>) { ++total_; } private: int& total_; }; class ClientEndpoint : public simulator::QuicEndpointWithConnection { public: ClientEndpoint(Simulator* simulator, const std::string& name, const std::string& peer_name, const QuicConfig& config) : QuicEndpointWithConnection(simulator, name, peer_name, Perspective::IS_CLIENT, GetQuicVersionsForGenericSession()), crypto_config_(crypto_test_utils::ProofVerifierForTesting()), session_(connection_.get(), false, nullptr, config, "test.example.com", 443, "example_alpn", &visitor_, false, std::make_unique<CountingDatagramObserver>( total_datagrams_processed_), &crypto_config_) { session_.Initialize(); session_.connection()->sent_packet_manager().SetSendAlgorithm( CongestionControlType::kBBRv2); EXPECT_CALL(visitor_, OnSessionReady()) .Times(AtMost(1)) .WillOnce(Assign(&session_ready_, true)); } QuicGenericClientSession* session() { return &session_; } MockWebTransportSessionVisitor* visitor() { return &visitor_; } bool session_ready() const { return session_ready_; } int total_datagrams_processed() const { return total_datagrams_processed_; } private: QuicCryptoClientConfig crypto_config_; MockWebTransportSessionVisitor visitor_; QuicGenericClientSession session_; bool session_ready_ = false; int total_datagrams_processed_ = 0; }; class ServerEndpoint : public simulator::QuicEndpointWithConnection { public: ServerEndpoint(Simulator* simulator, const std::string& name, const std::string& peer_name, const QuicConfig& config, ServerType type) : QuicEndpointWithConnection(simulator, name, peer_name, Perspective::IS_SERVER, GetQuicVersionsForGenericSession()), crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), session_(connection_.get(), false, nullptr, config, "example_alpn", type == kEchoServer ? static_cast<webtransport::SessionVisitor*>( new EchoWebTransportSessionVisitor( &session_, false)) : static_cast<webtransport::SessionVisitor*>( new DiscardWebTransportSessionVisitor(&session_)), true, nullptr, &crypto_config_, &compressed_certs_cache_) { session_.Initialize(); session_.connection()->sent_packet_manager().SetSendAlgorithm( CongestionControlType::kBBRv2); } QuicGenericServerSession* session() { return &session_; } private: QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicGenericServerSession session_; }; class QuicGenericSessionTest : public QuicTest { public: void CreateDefaultEndpoints(ServerType server_type) { client_ = std::make_unique<ClientEndpoint>( &test_harness_.simulator(), "Client", "Server", client_config_); server_ = std::make_unique<ServerEndpoint>(&test_harness_.simulator(), "Server", "Client", server_config_, server_type); test_harness_.set_client(client_.get()); test_harness_.set_server(server_.get()); } void WireUpEndpoints() { test_harness_.WireUpEndpoints(); } void RunHandshake() { client_->session()->CryptoConnect(); bool result = test_harness_.RunUntilWithDefaultTimeout([this]() { return client_->session_ready() || client_->session()->error() != QUIC_NO_ERROR; }); EXPECT_TRUE(result); } protected: QuicConfig client_config_ = DefaultQuicConfig(); QuicConfig server_config_ = DefaultQuicConfig(); simulator::TestHarness test_harness_; std::unique_ptr<ClientEndpoint> client_; std::unique_ptr<ServerEndpoint> server_; }; TEST_F(QuicGenericSessionTest, SuccessfulHandshake) { CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); EXPECT_TRUE(client_->session_ready()); } TEST_F(QuicGenericSessionTest, SendOutgoingStreams) { CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); std::vector<webtransport::Stream*> streams; for (int i = 0; i < 10; i++) { webtransport::Stream* stream = client_->session()->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream->Write("test")); streams.push_back(stream); } ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 10; })); for (webtransport::Stream* stream : streams) { ASSERT_TRUE(stream->SendFin()); } ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 0; })); } TEST_F(QuicGenericSessionTest, EchoBidirectionalStreams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream = client_->session()->OpenOutgoingBidirectionalStream(); EXPECT_TRUE(stream->Write("Hello!")); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [stream]() { return stream->ReadableBytes() == strlen("Hello!"); })); std::string received; WebTransportStream::ReadResult result = stream->Read(&received); EXPECT_EQ(result.bytes_read, strlen("Hello!")); EXPECT_FALSE(result.fin); EXPECT_EQ(received, "Hello!"); EXPECT_TRUE(stream->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 0; })); } TEST_F(QuicGenericSessionTest, EchoUnidirectionalStreams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream1 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream1->Write("Stream One")); webtransport::Stream* stream2 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream2->Write("Stream Two")); EXPECT_TRUE(stream2->SendFin()); bool stream_received = false; EXPECT_CALL(*client_->visitor(), OnIncomingUnidirectionalStreamAvailable()) .Times(2) .WillRepeatedly(Assign(&stream_received, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&stream_received]() { return stream_received; })); webtransport::Stream* reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); std::string buffer; WebTransportStream::ReadResult result = reply->Read(&buffer); EXPECT_GT(result.bytes_read, 0u); EXPECT_TRUE(result.fin); EXPECT_EQ(buffer, "Stream Two"); stream_received = false; buffer = ""; EXPECT_TRUE(stream1->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&stream_received]() { return stream_received; })); reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); result = reply->Read(&buffer); EXPECT_GT(result.bytes_read, 0u); EXPECT_TRUE(result.fin); EXPECT_EQ(buffer, "Stream One"); } TEST_F(QuicGenericSessionTest, EchoStreamsUsingPeekApi) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream1 = client_->session()->OpenOutgoingBidirectionalStream(); EXPECT_TRUE(stream1->Write("Stream One")); webtransport::Stream* stream2 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream2->Write("Stream Two")); EXPECT_TRUE(stream2->SendFin()); bool stream_received_unidi = false; EXPECT_CALL(*client_->visitor(), OnIncomingUnidirectionalStreamAvailable()) .WillOnce(Assign(&stream_received_unidi, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream_received_unidi; })); webtransport::Stream* reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); std::string buffer; quiche::ReadStream::PeekResult peek_result = reply->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, "Stream Two"); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, true); bool fin_received = quiche::ProcessAllReadableRegions(*reply, [&](absl::string_view chunk) { buffer.append(chunk.data(), chunk.size()); return true; }); EXPECT_TRUE(fin_received); EXPECT_EQ(buffer, "Stream Two"); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream1->PeekNextReadableRegion().has_data(); })); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, "Stream One"); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, false); fin_received = stream1->SkipBytes(strlen("Stream One")); EXPECT_FALSE(fin_received); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, ""); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, false); EXPECT_TRUE(stream1->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream1->PeekNextReadableRegion().all_data_received; })); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, ""); EXPECT_EQ(peek_result.fin_next, true); EXPECT_EQ(peek_result.all_data_received, true); webtransport::StreamId id = stream1->GetStreamId(); EXPECT_TRUE(client_->session()->GetStreamById(id) != nullptr); fin_received = stream1->SkipBytes(0); EXPECT_TRUE(fin_received); EXPECT_TRUE(client_->session()->GetStreamById(id) == nullptr); } TEST_F(QuicGenericSessionTest, EchoDatagram) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SendOrQueueDatagram("test"); bool datagram_received = false; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(Eq("test"))) .WillOnce(Assign(&datagram_received, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&datagram_received]() { return datagram_received; })); } TEST_F(QuicGenericSessionTest, EchoALotOfDatagrams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (10000 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 3 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(2 * simulator::TestHarness::kRtt); EXPECT_GT(received, 500u); EXPECT_LT(received, 1000u); } TEST_F(QuicGenericSessionTest, OutgoingStreamFlowControlBlocked) { server_config_.SetMaxUnidirectionalStreamsToSend(4); CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream; for (int i = 0; i <= 3; i++) { ASSERT_TRUE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); stream = client_->session()->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); ASSERT_TRUE(stream->SendFin()); } EXPECT_FALSE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); bool can_create_new_stream = false; EXPECT_CALL(*client_->visitor(), OnCanCreateNewOutgoingUnidirectionalStream()) .WillOnce(Assign(&can_create_new_stream, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&can_create_new_stream]() { return can_create_new_stream; })); EXPECT_TRUE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); } TEST_F(QuicGenericSessionTest, ExpireDatagrams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (0.2 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 3 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(2 * simulator::TestHarness::kRtt); EXPECT_LT(received, 500); EXPECT_EQ(received + client_->session()->GetDatagramStats().expired_outgoing, 1000); } TEST_F(QuicGenericSessionTest, LoseDatagrams) { CreateDefaultEndpoints(kEchoServer); test_harness_.WireUpEndpointsWithLoss(4); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (10000 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 4 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(16 * simulator::TestHarness::kRtt); QuicPacketCount client_lost = client_->session()->GetDatagramStats().lost_outgoing; QuicPacketCount server_lost = server_->session()->GetDatagramStats().lost_outgoing; EXPECT_LT(received, 800u); EXPECT_GT(client_lost, 100u); EXPECT_GT(server_lost, 100u); EXPECT_EQ(received + client_lost + server_lost, 1000u); } TEST_F(QuicGenericSessionTest, WriteWhenBufferFull) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); const std::string buffer(64 * 1024 + 1, 'q'); webtransport::Stream* stream = client_->session()->OpenOutgoingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); ASSERT_TRUE(stream->CanWrite()); absl::Status status = quiche::WriteIntoStream(*stream, buffer); QUICHE_EXPECT_OK(status); EXPECT_FALSE(stream->CanWrite()); status = quiche::WriteIntoStream(*stream, buffer); EXPECT_THAT(status, StatusIs(absl::StatusCode::kUnavailable)); quiche::StreamWriteOptions options; options.set_buffer_unconditionally(true); options.set_send_fin(true); status = quiche::WriteIntoStream(*stream, buffer, options); QUICHE_EXPECT_OK(status); EXPECT_FALSE(stream->CanWrite()); QuicByteCount total_received = 0; for (;;) { test_harness_.RunUntilWithDefaultTimeout( [&] { return stream->PeekNextReadableRegion().has_data(); }); quiche::ReadStream::PeekResult result = stream->PeekNextReadableRegion(); total_received += result.peeked_data.size(); bool fin_consumed = stream->SkipBytes(result.peeked_data.size()); if (fin_consumed) { break; } } EXPECT_EQ(total_received, 128u * 1024u + 2); } } }
276
cpp
google/quiche
quic_write_blocked_list
quiche/quic/core/quic_write_blocked_list.cc
quiche/quic/core/quic_write_blocked_list_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_WRITE_BLOCKED_LIST_H_ #define QUICHE_QUIC_CORE_QUIC_WRITE_BLOCKED_LIST_H_ #include <cstddef> #include <cstdint> #include <utility> #include "absl/container/inlined_vector.h" #include "quiche/http2/core/priority_write_scheduler.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/spdy/core/spdy_protocol.h" namespace quic { class QUICHE_EXPORT QuicWriteBlockedListInterface { public: virtual ~QuicWriteBlockedListInterface() = default; virtual bool HasWriteBlockedDataStreams() const = 0; virtual size_t NumBlockedSpecialStreams() const = 0; virtual size_t NumBlockedStreams() const = 0; bool HasWriteBlockedSpecialStream() const { return NumBlockedSpecialStreams() > 0; } virtual bool ShouldYield(QuicStreamId id) const = 0; virtual QuicStreamPriority GetPriorityOfStream(QuicStreamId id) const = 0; virtual QuicStreamId PopFront() = 0; virtual void RegisterStream(QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& priority) = 0; virtual void UnregisterStream(QuicStreamId stream_id) = 0; virtual void UpdateStreamPriority(QuicStreamId stream_id, const QuicStreamPriority& new_priority) = 0; virtual void UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) = 0; virtual void AddStream(QuicStreamId stream_id) = 0; virtual bool IsStreamBlocked(QuicStreamId stream_id) const = 0; }; class QUICHE_EXPORT QuicWriteBlockedList : public QuicWriteBlockedListInterface { public: explicit QuicWriteBlockedList(); QuicWriteBlockedList(const QuicWriteBlockedList&) = delete; QuicWriteBlockedList& operator=(const QuicWriteBlockedList&) = delete; bool HasWriteBlockedDataStreams() const override { return priority_write_scheduler_.HasReadyStreams(); } size_t NumBlockedSpecialStreams() const override { return static_stream_collection_.num_blocked(); } size_t NumBlockedStreams() const override { return NumBlockedSpecialStreams() + priority_write_scheduler_.NumReadyStreams(); } bool ShouldYield(QuicStreamId id) const override; QuicStreamPriority GetPriorityOfStream(QuicStreamId id) const override { return QuicStreamPriority(priority_write_scheduler_.GetStreamPriority(id)); } QuicStreamId PopFront() override; void RegisterStream(QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& priority) override; void UnregisterStream(QuicStreamId stream_id) override; void UpdateStreamPriority(QuicStreamId stream_id, const QuicStreamPriority& new_priority) override; void UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) override; void AddStream(QuicStreamId stream_id) override; bool IsStreamBlocked(QuicStreamId stream_id) const override; private: struct QUICHE_EXPORT HttpStreamPriorityToInt { int operator()(const HttpStreamPriority& priority) { return priority.urgency; } }; struct QUICHE_EXPORT IntToHttpStreamPriority { HttpStreamPriority operator()(int urgency) { return HttpStreamPriority{urgency}; } }; http2::PriorityWriteScheduler<QuicStreamId, HttpStreamPriority, HttpStreamPriorityToInt, IntToHttpStreamPriority> priority_write_scheduler_; QuicStreamId batch_write_stream_id_[spdy::kV3LowestPriority + 1]; size_t bytes_left_for_batch_write_[spdy::kV3LowestPriority + 1]; spdy::SpdyPriority last_priority_popped_; class QUICHE_EXPORT StaticStreamCollection { public: struct QUICHE_EXPORT StreamIdBlockedPair { QuicStreamId id; bool is_blocked; }; using StreamsVector = absl::InlinedVector<StreamIdBlockedPair, 2>; StreamsVector::const_iterator begin() const { return streams_.cbegin(); } StreamsVector::const_iterator end() const { return streams_.cend(); } size_t num_blocked() const { return num_blocked_; } void Register(QuicStreamId id); bool IsRegistered(QuicStreamId id) const; bool Unregister(QuicStreamId id); bool SetBlocked(QuicStreamId id); bool UnblockFirstBlocked(QuicStreamId* id); private: size_t num_blocked_ = 0; StreamsVector streams_; }; StaticStreamCollection static_stream_collection_; const bool respect_incremental_; const bool disable_batch_write_; }; } #endif #include "quiche/quic/core/quic_write_blocked_list.h" #include <algorithm> #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicWriteBlockedList::QuicWriteBlockedList() : last_priority_popped_(0), respect_incremental_( GetQuicReloadableFlag(quic_priority_respect_incremental)), disable_batch_write_(GetQuicReloadableFlag(quic_disable_batch_write)) { memset(batch_write_stream_id_, 0, sizeof(batch_write_stream_id_)); memset(bytes_left_for_batch_write_, 0, sizeof(bytes_left_for_batch_write_)); } bool QuicWriteBlockedList::ShouldYield(QuicStreamId id) const { for (const auto& stream : static_stream_collection_) { if (stream.id == id) { return false; } if (stream.is_blocked) { return true; } } return priority_write_scheduler_.ShouldYield(id); } QuicStreamId QuicWriteBlockedList::PopFront() { QuicStreamId static_stream_id; if (static_stream_collection_.UnblockFirstBlocked(&static_stream_id)) { return static_stream_id; } const auto [id, priority] = priority_write_scheduler_.PopNextReadyStreamAndPriority(); const spdy::SpdyPriority urgency = priority.urgency; const bool incremental = priority.incremental; last_priority_popped_ = urgency; if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 1, 3); if (!respect_incremental_ || !incremental) { batch_write_stream_id_[urgency] = id; } return id; } if (!priority_write_scheduler_.HasReadyStreams()) { batch_write_stream_id_[urgency] = 0; } else if (batch_write_stream_id_[urgency] != id) { batch_write_stream_id_[urgency] = id; bytes_left_for_batch_write_[urgency] = 16000; } return id; } void QuicWriteBlockedList::RegisterStream(QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& priority) { QUICHE_DCHECK(!priority_write_scheduler_.StreamRegistered(stream_id)) << "stream " << stream_id << " already registered"; if (is_static_stream) { static_stream_collection_.Register(stream_id); return; } priority_write_scheduler_.RegisterStream(stream_id, priority.http()); } void QuicWriteBlockedList::UnregisterStream(QuicStreamId stream_id) { if (static_stream_collection_.Unregister(stream_id)) { return; } priority_write_scheduler_.UnregisterStream(stream_id); } void QuicWriteBlockedList::UpdateStreamPriority( QuicStreamId stream_id, const QuicStreamPriority& new_priority) { QUICHE_DCHECK(!static_stream_collection_.IsRegistered(stream_id)); priority_write_scheduler_.UpdateStreamPriority(stream_id, new_priority.http()); } void QuicWriteBlockedList::UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) { if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 2, 3); return; } if (batch_write_stream_id_[last_priority_popped_] == stream_id) { bytes_left_for_batch_write_[last_priority_popped_] -= std::min(bytes_left_for_batch_write_[last_priority_popped_], bytes); } } void QuicWriteBlockedList::AddStream(QuicStreamId stream_id) { if (static_stream_collection_.SetBlocked(stream_id)) { return; } if (respect_incremental_) { QUIC_RELOADABLE_FLAG_COUNT(quic_priority_respect_incremental); if (!priority_write_scheduler_.GetStreamPriority(stream_id).incremental) { const bool push_front = stream_id == batch_write_stream_id_[last_priority_popped_]; priority_write_scheduler_.MarkStreamReady(stream_id, push_front); return; } } if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 3, 3); priority_write_scheduler_.MarkStreamReady(stream_id, false); return; } const bool push_front = stream_id == batch_write_stream_id_[last_priority_popped_] && bytes_left_for_batch_write_[last_priority_popped_] > 0; priority_write_scheduler_.MarkStreamReady(stream_id, push_front); } bool QuicWriteBlockedList::IsStreamBlocked(QuicStreamId stream_id) const { for (const auto& stream : static_stream_collection_) { if (stream.id == stream_id) { return stream.is_blocked; } } return priority_write_scheduler_.IsStreamReady(stream_id); } void QuicWriteBlockedList::StaticStreamCollection::Register(QuicStreamId id) { QUICHE_DCHECK(!IsRegistered(id)); streams_.push_back({id, false}); } bool QuicWriteBlockedList::StaticStreamCollection::IsRegistered( QuicStreamId id) const { for (const auto& stream : streams_) { if (stream.id == id) { return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::Unregister(QuicStreamId id) { for (auto it = streams_.begin(); it != streams_.end(); ++it) { if (it->id == id) { if (it->is_blocked) { --num_blocked_; } streams_.erase(it); return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::SetBlocked(QuicStreamId id) { for (auto& stream : streams_) { if (stream.id == id) { if (!stream.is_blocked) { stream.is_blocked = true; ++num_blocked_; } return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::UnblockFirstBlocked( QuicStreamId* id) { for (auto& stream : streams_) { if (stream.is_blocked) { --num_blocked_; stream.is_blocked = false; *id = stream.id; return true; } } return false; } }
#include "quiche/quic/core/quic_write_blocked_list.h" #include <optional> #include <tuple> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" using spdy::kV3HighestPriority; using spdy::kV3LowestPriority; namespace quic { namespace test { namespace { constexpr bool kStatic = true; constexpr bool kNotStatic = false; constexpr bool kIncremental = true; constexpr bool kNotIncremental = false; class QuicWriteBlockedListTest : public QuicTest { protected: void SetUp() override { write_blocked_list_.emplace(); } bool HasWriteBlockedDataStreams() const { return write_blocked_list_->HasWriteBlockedDataStreams(); } bool HasWriteBlockedSpecialStream() const { return write_blocked_list_->HasWriteBlockedSpecialStream(); } size_t NumBlockedSpecialStreams() const { return write_blocked_list_->NumBlockedSpecialStreams(); } size_t NumBlockedStreams() const { return write_blocked_list_->NumBlockedStreams(); } bool ShouldYield(QuicStreamId id) const { return write_blocked_list_->ShouldYield(id); } QuicStreamPriority GetPriorityOfStream(QuicStreamId id) const { return write_blocked_list_->GetPriorityOfStream(id); } QuicStreamId PopFront() { return write_blocked_list_->PopFront(); } void RegisterStream(QuicStreamId stream_id, bool is_static_stream, const HttpStreamPriority& priority) { write_blocked_list_->RegisterStream(stream_id, is_static_stream, QuicStreamPriority(priority)); } void UnregisterStream(QuicStreamId stream_id) { write_blocked_list_->UnregisterStream(stream_id); } void UpdateStreamPriority(QuicStreamId stream_id, const HttpStreamPriority& new_priority) { write_blocked_list_->UpdateStreamPriority(stream_id, QuicStreamPriority(new_priority)); } void UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) { write_blocked_list_->UpdateBytesForStream(stream_id, bytes); } void AddStream(QuicStreamId stream_id) { write_blocked_list_->AddStream(stream_id); } bool IsStreamBlocked(QuicStreamId stream_id) const { return write_blocked_list_->IsStreamBlocked(stream_id); } private: std::optional<QuicWriteBlockedList> write_blocked_list_; }; TEST_F(QuicWriteBlockedListTest, PriorityOrder) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {kV3HighestPriority, kIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_EQ(kV3LowestPriority, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); AddStream(40); EXPECT_TRUE(IsStreamBlocked(40)); AddStream(23); EXPECT_TRUE(IsStreamBlocked(23)); AddStream(17); EXPECT_TRUE(IsStreamBlocked(17)); AddStream(3); EXPECT_TRUE(IsStreamBlocked(3)); AddStream(1); EXPECT_TRUE(IsStreamBlocked(1)); EXPECT_EQ(5u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_EQ(2u, NumBlockedSpecialStreams()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(1u, NumBlockedSpecialStreams()); EXPECT_FALSE(IsStreamBlocked(1)); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(0u, NumBlockedSpecialStreams()); EXPECT_FALSE(IsStreamBlocked(3)); EXPECT_EQ(23u, PopFront()); EXPECT_FALSE(IsStreamBlocked(23)); EXPECT_EQ(17u, PopFront()); EXPECT_FALSE(IsStreamBlocked(17)); EXPECT_EQ(40u, PopFront()); EXPECT_FALSE(IsStreamBlocked(40)); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, SingleStaticStream) { RegisterStream(5, kStatic, {kV3HighestPriority, kNotIncremental}); AddStream(5); EXPECT_EQ(1u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); } TEST_F(QuicWriteBlockedListTest, StaticStreamsComeFirst) { RegisterStream(5, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3LowestPriority, kNotIncremental}); AddStream(5); AddStream(3); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, NoDuplicateEntries) { const QuicStreamId kBlockedId = 5; RegisterStream(kBlockedId, kNotStatic, {kV3HighestPriority, kNotIncremental}); AddStream(kBlockedId); AddStream(kBlockedId); AddStream(kBlockedId); EXPECT_EQ(1u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(kBlockedId, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, IncrementalStreamsRoundRobin) { const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, kLargeWriteSize); AddStream(id3); AddStream(id2); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, kLargeWriteSize); AddStream(id3); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); } class QuicWriteBlockedListParameterizedTest : public QuicWriteBlockedListTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: QuicWriteBlockedListParameterizedTest() : priority_respect_incremental_(std::get<0>(GetParam())), disable_batch_write_(std::get<1>(GetParam())) { SetQuicReloadableFlag(quic_priority_respect_incremental, priority_respect_incremental_); SetQuicReloadableFlag(quic_disable_batch_write, disable_batch_write_); } const bool priority_respect_incremental_; const bool disable_batch_write_; }; INSTANTIATE_TEST_SUITE_P( BatchWrite, QuicWriteBlockedListParameterizedTest, ::testing::Combine(::testing::Bool(), ::testing::Bool()), [](const testing::TestParamInfo< QuicWriteBlockedListParameterizedTest::ParamType>& info) { return absl::StrCat(std::get<0>(info.param) ? "RespectIncrementalTrue" : "RespectIncrementalFalse", std::get<1>(info.param) ? "DisableBatchWriteTrue" : "DisableBatchWriteFalse"); }); TEST_P(QuicWriteBlockedListParameterizedTest, BatchingWrites) { if (disable_batch_write_) { return; } const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3HighestPriority, kIncremental}); AddStream(id1); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, 15999); AddStream(id1); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, 1); AddStream(id1); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, 15999); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); AddStream(id3); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, 20000); AddStream(id3); EXPECT_EQ(id3, PopFront()); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, 1); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); } TEST_P(QuicWriteBlockedListParameterizedTest, RoundRobin) { if (!disable_batch_write_) { return; } const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); AddStream(id1); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); AddStream(id3); AddStream(id2); EXPECT_EQ(id1, PopFront()); EXPECT_EQ(id3, PopFront()); AddStream(id3); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); } TEST_P(QuicWriteBlockedListParameterizedTest, NonIncrementalStreamsKeepWriting) { if (!priority_respect_incremental_) { return; } const QuicStreamId id1 = 1; const QuicStreamId id2 = 2; const QuicStreamId id3 = 3; const QuicStreamId id4 = 4; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id4, kNotStatic, {kV3HighestPriority, kNotIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); AddStream(id4); EXPECT_EQ(id4, PopFront()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); AddStream(id1); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id3); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); } TEST_P(QuicWriteBlockedListParameterizedTest, IncrementalAndNonIncrementalStreams) { if (!priority_respect_incremental_) { return; } const QuicStreamId id1 = 1; const QuicStreamId id2 = 2; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); EXPECT_EQ(id1, PopFront()); const size_t kSmallWriteSize = 1000; UpdateBytesForStream(id1, kSmallWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kSmallWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kSmallWriteSize); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); AddStream(id2); AddStream(id1); if (!disable_batch_write_) { EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); AddStream(id2); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); } EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id2); AddStream(id1); if (!disable_batch_write_) { EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); } EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); } TEST_F(QuicWriteBlockedListTest, Ceding) { RegisterStream(15, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(16, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(5, kNotStatic, {5, kNotIncremental}); RegisterStream(4, kNotStatic, {5, kNotIncremental}); RegisterStream(7, kNotStatic, {7, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_FALSE(ShouldYield(5)); AddStream(5); EXPECT_FALSE(ShouldYield(5)); EXPECT_TRUE(ShouldYield(4)); EXPECT_TRUE(ShouldYield(7)); EXPECT_FALSE(ShouldYield(15)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(15); EXPECT_TRUE(ShouldYield(16)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(3); EXPECT_TRUE(ShouldYield(16)); EXPECT_TRUE(ShouldYield(15)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(1); EXPECT_TRUE(ShouldYield(16)); EXPECT_TRUE(ShouldYield(15)); EXPECT_TRUE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); } TEST_F(QuicWriteBlockedListTest, UnregisterStream) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {6, kNotIncremental}); RegisterStream(12, kNotStatic, {3, kNotIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); AddStream(40); AddStream(23); AddStream(12); AddStream(17); AddStream(1); AddStream(3); UnregisterStream(23); UnregisterStream(1); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(17u, PopFront()); EXPECT_EQ(12u, PopFront()); EXPECT_EQ(40, PopFront()); } TEST_F(QuicWriteBlockedListTest, UnregisterNotRegisteredStream) { EXPECT_QUICHE_BUG(UnregisterStream(1), "Stream 1 not registered"); RegisterStream(2, kNotStatic, {kV3HighestPriority, kIncremental}); UnregisterStream(2); EXPECT_QUICHE_BUG(UnregisterStream(2), "Stream 2 not registered"); } TEST_F(QuicWriteBlockedListTest, UpdateStreamPriority) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {6, kIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {2, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_EQ(kV3LowestPriority, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(6, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); UpdateStreamPriority(40, {3, kIncremental}); UpdateStreamPriority(23, {kV3HighestPriority, kNotIncremental}); UpdateStreamPriority(17, {5, kNotIncremental}); EXPECT_EQ(3, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(5, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); AddStream(40); AddStream(23); AddStream(17); AddStream(1); AddStream(3); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(23u, PopFront()); EXPECT_EQ(40u, PopFront()); EXPECT_EQ(17u, PopFront()); } TEST_F(QuicWriteBlockedListTest, UpdateStaticStreamPriority) { RegisterStream(2, kStatic, {kV3LowestPriority, kNotIncremental}); EXPECT_QUICHE_DEBUG_DEATH( UpdateStreamPriority(2, {kV3HighestPriority, kNotIncremental}), "IsRegistered"); } TEST_F(QuicWriteBlockedListTest, UpdateStreamPrioritySameUrgency) { RegisterStream(1, kNotStatic, {6, kNotIncremental}); RegisterStream(2, kNotStatic, {6, kNotIncremental}); AddStream(1); AddStream(2); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(2u, PopFront()); RegisterStream(3, kNotStatic, {6, kNotIncremental}); RegisterStream(4, kNotStatic, {6, kNotIncremental}); EXPECT_EQ(6, GetPriorityOfStream(3).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(3).http().incremental); UpdateStreamPriority(3, {6, kIncremental}); EXPECT_EQ(6, GetPriorityOfStream(3).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(3).http().incremental); AddStream(3); AddStream(4); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(4u, PopFront()); RegisterStream(5, kNotStatic, {6, kIncremental}); RegisterStream(6, kNotStatic, {6, kIncremental}); EXPECT_EQ(6, GetPriorityOfStream(6).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(6).http().incremental); UpdateStreamPriority(6, {6, kNotIncremental}); EXPECT_EQ(6, GetPriorityOfStream(6).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(6).http().incremental); AddStream(5); AddStream(6); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(6u, PopFront()); } } } }
277
cpp
google/quiche
quic_datagram_queue
quiche/quic/core/quic_datagram_queue.cc
quiche/quic/core/quic_datagram_queue_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_DATAGRAM_QUEUE_H_ #define QUICHE_QUIC_CORE_QUIC_DATAGRAM_QUEUE_H_ #include <cstdint> #include <memory> #include <optional> #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { class QuicSession; class QUICHE_EXPORT QuicDatagramQueue { public: class QUICHE_EXPORT Observer { public: virtual ~Observer() = default; virtual void OnDatagramProcessed(std::optional<MessageStatus> status) = 0; }; explicit QuicDatagramQueue(QuicSession* session); QuicDatagramQueue(QuicSession* session, std::unique_ptr<Observer> observer); MessageStatus SendOrQueueDatagram(quiche::QuicheMemSlice datagram); std::optional<MessageStatus> TrySendingNextDatagram(); size_t SendDatagrams(); QuicTime::Delta GetMaxTimeInQueue() const; void SetMaxTimeInQueue(QuicTime::Delta max_time_in_queue) { max_time_in_queue_ = max_time_in_queue; } void SetForceFlush(bool force_flush) { force_flush_ = force_flush; } size_t queue_size() { return queue_.size(); } bool empty() { return queue_.empty(); } uint64_t expired_datagram_count() const { return expired_datagram_count_; } private: struct QUICHE_EXPORT Datagram { quiche::QuicheMemSlice datagram; QuicTime expiry; }; void RemoveExpiredDatagrams(); QuicSession* session_; const QuicClock* clock_; QuicTime::Delta max_time_in_queue_ = QuicTime::Delta::Zero(); quiche::QuicheCircularDeque<Datagram> queue_; std::unique_ptr<Observer> observer_; uint64_t expired_datagram_count_ = 0; bool force_flush_ = false; }; } #endif #include "quiche/quic/core/quic_datagram_queue.h" #include <algorithm> #include <memory> #include <optional> #include <utility> #include "absl/types/span.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" namespace quic { constexpr float kExpiryInMinRtts = 1.25; constexpr float kMinPacingWindows = 4; QuicDatagramQueue::QuicDatagramQueue(QuicSession* session) : QuicDatagramQueue(session, nullptr) {} QuicDatagramQueue::QuicDatagramQueue(QuicSession* session, std::unique_ptr<Observer> observer) : session_(session), clock_(session->connection()->clock()), observer_(std::move(observer)) {} MessageStatus QuicDatagramQueue::SendOrQueueDatagram( quiche::QuicheMemSlice datagram) { if (queue_.empty()) { MessageResult result = session_->SendMessage(absl::MakeSpan(&datagram, 1), force_flush_); if (result.status != MESSAGE_STATUS_BLOCKED) { if (observer_) { observer_->OnDatagramProcessed(result.status); } return result.status; } } queue_.emplace_back(Datagram{std::move(datagram), clock_->ApproximateNow() + GetMaxTimeInQueue()}); return MESSAGE_STATUS_BLOCKED; } std::optional<MessageStatus> QuicDatagramQueue::TrySendingNextDatagram() { RemoveExpiredDatagrams(); if (queue_.empty()) { return std::nullopt; } MessageResult result = session_->SendMessage(absl::MakeSpan(&queue_.front().datagram, 1)); if (result.status != MESSAGE_STATUS_BLOCKED) { queue_.pop_front(); if (observer_) { observer_->OnDatagramProcessed(result.status); } } return result.status; } size_t QuicDatagramQueue::SendDatagrams() { size_t num_datagrams = 0; for (;;) { std::optional<MessageStatus> status = TrySendingNextDatagram(); if (!status.has_value()) { break; } if (*status == MESSAGE_STATUS_BLOCKED) { break; } num_datagrams++; } return num_datagrams; } QuicTime::Delta QuicDatagramQueue::GetMaxTimeInQueue() const { if (!max_time_in_queue_.IsZero()) { return max_time_in_queue_; } const QuicTime::Delta min_rtt = session_->connection()->sent_packet_manager().GetRttStats()->min_rtt(); return std::max(kExpiryInMinRtts * min_rtt, kMinPacingWindows * kAlarmGranularity); } void QuicDatagramQueue::RemoveExpiredDatagrams() { QuicTime now = clock_->ApproximateNow(); while (!queue_.empty() && queue_.front().expiry <= now) { ++expired_datagram_count_; queue_.pop_front(); if (observer_) { observer_->OnDatagramProcessed(std::nullopt); } } } }
#include "quiche/quic/core/quic_datagram_queue.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_reference_counted.h" #include "quiche/common/quiche_buffer_allocator.h" namespace quic { namespace test { namespace { using testing::_; using testing::ElementsAre; using testing::Return; class EstablishedCryptoStream : public MockQuicCryptoStream { public: using MockQuicCryptoStream::MockQuicCryptoStream; bool encryption_established() const override { return true; } }; class QuicDatagramQueueObserver final : public QuicDatagramQueue::Observer { public: class Context : public quiche::QuicheReferenceCounted { public: std::vector<std::optional<MessageStatus>> statuses; }; QuicDatagramQueueObserver() : context_(new Context()) {} QuicDatagramQueueObserver(const QuicDatagramQueueObserver&) = delete; QuicDatagramQueueObserver& operator=(const QuicDatagramQueueObserver&) = delete; void OnDatagramProcessed(std::optional<MessageStatus> status) override { context_->statuses.push_back(std::move(status)); } const quiche::QuicheReferenceCountedPointer<Context>& context() { return context_; } private: quiche::QuicheReferenceCountedPointer<Context> context_; }; class QuicDatagramQueueTestBase : public QuicTest { protected: QuicDatagramQueueTestBase() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT)), session_(connection_) { session_.SetCryptoStream(new EstablishedCryptoStream(&session_)); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); } ~QuicDatagramQueueTestBase() = default; quiche::QuicheMemSlice CreateMemSlice(absl::string_view data) { return quiche::QuicheMemSlice(quiche::QuicheBuffer::Copy( helper_.GetStreamSendBufferAllocator(), data)); } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; MockQuicSession session_; }; class QuicDatagramQueueTest : public QuicDatagramQueueTestBase { public: QuicDatagramQueueTest() : queue_(&session_) {} protected: QuicDatagramQueue queue_; }; TEST_F(QuicDatagramQueueTest, SendDatagramImmediately) { EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); MessageStatus status = queue_.SendOrQueueDatagram(CreateMemSlice("test")); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, status); EXPECT_EQ(0u, queue_.queue_size()); } TEST_F(QuicDatagramQueueTest, SendDatagramAfterBuffering) { EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); MessageStatus initial_status = queue_.SendOrQueueDatagram(CreateMemSlice("test")); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, initial_status); EXPECT_EQ(1u, queue_.queue_size()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); std::optional<MessageStatus> status = queue_.TrySendingNextDatagram(); ASSERT_TRUE(status.has_value()); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, *status); EXPECT_EQ(1u, queue_.queue_size()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); status = queue_.TrySendingNextDatagram(); ASSERT_TRUE(status.has_value()); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, *status); EXPECT_EQ(0u, queue_.queue_size()); } TEST_F(QuicDatagramQueueTest, EmptyBuffer) { std::optional<MessageStatus> status = queue_.TrySendingNextDatagram(); EXPECT_FALSE(status.has_value()); size_t num_messages = queue_.SendDatagrams(); EXPECT_EQ(0u, num_messages); } TEST_F(QuicDatagramQueueTest, MultipleDatagrams) { EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); queue_.SendOrQueueDatagram(CreateMemSlice("a")); queue_.SendOrQueueDatagram(CreateMemSlice("b")); queue_.SendOrQueueDatagram(CreateMemSlice("c")); queue_.SendOrQueueDatagram(CreateMemSlice("d")); queue_.SendOrQueueDatagram(CreateMemSlice("e")); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .Times(5) .WillRepeatedly(Return(MESSAGE_STATUS_SUCCESS)); size_t num_messages = queue_.SendDatagrams(); EXPECT_EQ(5u, num_messages); } TEST_F(QuicDatagramQueueTest, DefaultMaxTimeInQueue) { EXPECT_EQ(QuicTime::Delta::Zero(), connection_->sent_packet_manager().GetRttStats()->min_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(4), queue_.GetMaxTimeInQueue()); RttStats* stats = const_cast<RttStats*>(connection_->sent_packet_manager().GetRttStats()); stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), helper_.GetClock()->Now()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(125), queue_.GetMaxTimeInQueue()); } TEST_F(QuicDatagramQueueTest, Expiry) { constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100); queue_.SetMaxTimeInQueue(expiry); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); queue_.SendOrQueueDatagram(CreateMemSlice("a")); helper_.AdvanceTime(0.6 * expiry); queue_.SendOrQueueDatagram(CreateMemSlice("b")); helper_.AdvanceTime(0.6 * expiry); queue_.SendOrQueueDatagram(CreateMemSlice("c")); std::vector<std::string> messages; EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillRepeatedly([&messages](QuicMessageId , absl::Span<quiche::QuicheMemSlice> message, bool ) { messages.push_back(std::string(message[0].AsStringView())); return MESSAGE_STATUS_SUCCESS; }); EXPECT_EQ(2u, queue_.SendDatagrams()); EXPECT_THAT(messages, ElementsAre("b", "c")); } TEST_F(QuicDatagramQueueTest, ExpireAll) { constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100); queue_.SetMaxTimeInQueue(expiry); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); queue_.SendOrQueueDatagram(CreateMemSlice("a")); queue_.SendOrQueueDatagram(CreateMemSlice("b")); queue_.SendOrQueueDatagram(CreateMemSlice("c")); helper_.AdvanceTime(100 * expiry); EXPECT_CALL(*connection_, SendMessage(_, _, _)).Times(0); EXPECT_EQ(0u, queue_.SendDatagrams()); } class QuicDatagramQueueWithObserverTest : public QuicDatagramQueueTestBase { public: QuicDatagramQueueWithObserverTest() : observer_(std::make_unique<QuicDatagramQueueObserver>()), context_(observer_->context()), queue_(&session_, std::move(observer_)) {} protected: std::unique_ptr<QuicDatagramQueueObserver> observer_; quiche::QuicheReferenceCountedPointer<QuicDatagramQueueObserver::Context> context_; QuicDatagramQueue queue_; }; TEST_F(QuicDatagramQueueWithObserverTest, ObserveSuccessImmediately) { EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, queue_.SendOrQueueDatagram(CreateMemSlice("a"))); EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_SUCCESS)); } TEST_F(QuicDatagramQueueWithObserverTest, ObserveFailureImmediately) { EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_TOO_LARGE)); EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE, queue_.SendOrQueueDatagram(CreateMemSlice("a"))); EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_TOO_LARGE)); } TEST_F(QuicDatagramQueueWithObserverTest, BlockingShouldNotBeObserved) { EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillRepeatedly(Return(MESSAGE_STATUS_BLOCKED)); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, queue_.SendOrQueueDatagram(CreateMemSlice("a"))); EXPECT_EQ(0u, queue_.SendDatagrams()); EXPECT_TRUE(context_->statuses.empty()); } TEST_F(QuicDatagramQueueWithObserverTest, ObserveSuccessAfterBuffering) { EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, queue_.SendOrQueueDatagram(CreateMemSlice("a"))); EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); EXPECT_EQ(1u, queue_.SendDatagrams()); EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_SUCCESS)); } TEST_F(QuicDatagramQueueWithObserverTest, ObserveExpiry) { constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100); queue_.SetMaxTimeInQueue(expiry); EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)) .WillOnce(Return(MESSAGE_STATUS_BLOCKED)); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, queue_.SendOrQueueDatagram(CreateMemSlice("a"))); EXPECT_TRUE(context_->statuses.empty()); EXPECT_CALL(*connection_, SendMessage(_, _, _)).Times(0); helper_.AdvanceTime(100 * expiry); EXPECT_TRUE(context_->statuses.empty()); EXPECT_EQ(0u, queue_.SendDatagrams()); EXPECT_THAT(context_->statuses, ElementsAre(std::nullopt)); } } } }
278
cpp
google/quiche
quic_ping_manager
quiche/quic/core/quic_ping_manager.cc
quiche/quic/core/quic_ping_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_PING_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_PING_MANAGER_H_ #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicConnectionPeer; class QuicPingManagerPeer; } class QUICHE_EXPORT QuicPingManager { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() {} virtual void OnKeepAliveTimeout() = 0; virtual void OnRetransmittableOnWireTimeout() = 0; }; QuicPingManager(Perspective perspective, Delegate* delegate, QuicAlarm* alarm); void SetAlarm(QuicTime now, bool should_keep_alive, bool has_in_flight_packets); void OnAlarm(); void Stop(); void set_keep_alive_timeout(QuicTime::Delta keep_alive_timeout) { QUICHE_DCHECK(!alarm_.IsSet()); keep_alive_timeout_ = keep_alive_timeout; } void set_initial_retransmittable_on_wire_timeout( QuicTime::Delta retransmittable_on_wire_timeout) { QUICHE_DCHECK(!alarm_.IsSet()); initial_retransmittable_on_wire_timeout_ = retransmittable_on_wire_timeout; } void reset_consecutive_retransmittable_on_wire_count() { consecutive_retransmittable_on_wire_count_ = 0; } private: friend class test::QuicConnectionPeer; friend class test::QuicPingManagerPeer; void UpdateDeadlines(QuicTime now, bool should_keep_alive, bool has_in_flight_packets); QuicTime GetEarliestDeadline() const; Perspective perspective_; Delegate* delegate_; QuicTime::Delta initial_retransmittable_on_wire_timeout_ = QuicTime::Delta::Infinite(); int consecutive_retransmittable_on_wire_count_ = 0; int retransmittable_on_wire_count_ = 0; QuicTime::Delta keep_alive_timeout_ = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); QuicTime retransmittable_on_wire_deadline_ = QuicTime::Zero(); QuicTime keep_alive_deadline_ = QuicTime::Zero(); QuicAlarm& alarm_; }; } #endif #include "quiche/quic/core/quic_ping_manager.h" #include <algorithm> #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const int kMaxRetransmittableOnWireDelayShift = 10; } QuicPingManager::QuicPingManager(Perspective perspective, Delegate* delegate, QuicAlarm* alarm) : perspective_(perspective), delegate_(delegate), alarm_(*alarm) {} void QuicPingManager::SetAlarm(QuicTime now, bool should_keep_alive, bool has_in_flight_packets) { UpdateDeadlines(now, should_keep_alive, has_in_flight_packets); const QuicTime earliest_deadline = GetEarliestDeadline(); if (!earliest_deadline.IsInitialized()) { alarm_.Cancel(); return; } if (earliest_deadline == keep_alive_deadline_) { alarm_.Update(earliest_deadline, QuicTime::Delta::FromSeconds(1)); return; } alarm_.Update(earliest_deadline, kAlarmGranularity); } void QuicPingManager::OnAlarm() { const QuicTime earliest_deadline = GetEarliestDeadline(); if (!earliest_deadline.IsInitialized()) { QUIC_BUG(quic_ping_manager_alarm_fires_unexpectedly) << "QuicPingManager alarm fires unexpectedly."; return; } if (earliest_deadline == retransmittable_on_wire_deadline_) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); if (GetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count) != 0) { ++consecutive_retransmittable_on_wire_count_; } ++retransmittable_on_wire_count_; delegate_->OnRetransmittableOnWireTimeout(); return; } if (earliest_deadline == keep_alive_deadline_) { keep_alive_deadline_ = QuicTime::Zero(); delegate_->OnKeepAliveTimeout(); } } void QuicPingManager::Stop() { alarm_.PermanentCancel(); retransmittable_on_wire_deadline_ = QuicTime::Zero(); keep_alive_deadline_ = QuicTime::Zero(); } void QuicPingManager::UpdateDeadlines(QuicTime now, bool should_keep_alive, bool has_in_flight_packets) { keep_alive_deadline_ = QuicTime::Zero(); if (perspective_ == Perspective::IS_SERVER && initial_retransmittable_on_wire_timeout_.IsInfinite()) { QUICHE_DCHECK(!retransmittable_on_wire_deadline_.IsInitialized()); return; } if (!should_keep_alive) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); return; } if (perspective_ == Perspective::IS_CLIENT) { keep_alive_deadline_ = now + keep_alive_timeout_; } if (initial_retransmittable_on_wire_timeout_.IsInfinite() || has_in_flight_packets || retransmittable_on_wire_count_ > GetQuicFlag(quic_max_retransmittable_on_wire_ping_count)) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); return; } QUICHE_DCHECK_LT(initial_retransmittable_on_wire_timeout_, keep_alive_timeout_); QuicTime::Delta retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout_; const int max_aggressive_retransmittable_on_wire_count = GetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count); QUICHE_DCHECK_LE(0, max_aggressive_retransmittable_on_wire_count); if (consecutive_retransmittable_on_wire_count_ > max_aggressive_retransmittable_on_wire_count) { int shift = std::min(consecutive_retransmittable_on_wire_count_ - max_aggressive_retransmittable_on_wire_count, kMaxRetransmittableOnWireDelayShift); retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout_ * (1 << shift); } if (retransmittable_on_wire_deadline_.IsInitialized() && retransmittable_on_wire_deadline_ < now + retransmittable_on_wire_timeout) { return; } retransmittable_on_wire_deadline_ = now + retransmittable_on_wire_timeout; } QuicTime QuicPingManager::GetEarliestDeadline() const { QuicTime earliest_deadline = QuicTime::Zero(); for (QuicTime t : {retransmittable_on_wire_deadline_, keep_alive_deadline_}) { if (!t.IsInitialized()) { continue; } if (!earliest_deadline.IsInitialized() || t < earliest_deadline) { earliest_deadline = t; } } return earliest_deadline; } }
#include "quiche/quic/core/quic_ping_manager.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicPingManagerPeer { public: static QuicAlarm* GetAlarm(QuicPingManager* manager) { return &manager->alarm_; } static void SetPerspective(QuicPingManager* manager, Perspective perspective) { manager->perspective_ = perspective; } }; namespace { const bool kShouldKeepAlive = true; const bool kHasInflightPackets = true; class MockDelegate : public QuicPingManager::Delegate { public: MOCK_METHOD(void, OnKeepAliveTimeout, (), (override)); MOCK_METHOD(void, OnRetransmittableOnWireTimeout, (), (override)); }; class QuicPingManagerTest : public QuicTest { public: QuicPingManagerTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), manager_(Perspective::IS_CLIENT, &delegate_, &alarms_.ping_alarm()), alarm_(static_cast<MockAlarmFactory::TestAlarm*>( QuicPingManagerPeer::GetAlarm(&manager_))) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); ON_CALL(connection_alarms_delegate_, OnPingAlarm()).WillByDefault([&] { manager_.OnAlarm(); }); } protected: testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; MockClock clock_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; QuicPingManager manager_; MockAlarmFactory::TestAlarm* alarm_; }; TEST_F(QuicPingManagerTest, KeepAliveTimeout) { EXPECT_FALSE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), !kShouldKeepAlive, kHasInflightPackets); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, CustomizedKeepAliveTimeout) { EXPECT_FALSE(alarm_->IsSet()); manager_.set_keep_alive_timeout(QuicTime::Delta::FromSeconds(10)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(10), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ( QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), !kShouldKeepAlive, kHasInflightPackets); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireTimeout) { const QuicTime::Delta kRtransmittableOnWireTimeout = QuicTime::Delta::FromMilliseconds(50); manager_.set_initial_retransmittable_on_wire_timeout( kRtransmittableOnWireTimeout); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(kRtransmittableOnWireTimeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(kRtransmittableOnWireTimeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); ASSERT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireTimeoutExponentiallyBackOff) { const int kMaxAggressiveRetransmittableOnWireCount = 5; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); for (int i = 0; i <= kMaxAggressiveRetransmittableOnWireCount; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } QuicTime::Delta retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout; while (retransmittable_on_wire_timeout * 2 < QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) { retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, ResetRetransmitableOnWireTimeoutExponentiallyBackOff) { const int kMaxAggressiveRetransmittableOnWireCount = 3; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); alarm_->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); manager_.reset_consecutive_retransmittable_on_wire_count(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); alarm_->Fire(); for (int i = 0; i < kMaxAggressiveRetransmittableOnWireCount; i++) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); } manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.reset_consecutive_retransmittable_on_wire_count(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireLimit) { static constexpr int kMaxRetransmittableOnWirePingCount = 3; SetQuicFlag(quic_max_retransmittable_on_wire_ping_count, kMaxRetransmittableOnWirePingCount); static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); static constexpr QuicTime::Delta kShortDelay = QuicTime::Delta::FromMilliseconds(5); ASSERT_LT(kShortDelay * 10, initial_retransmittable_on_wire_timeout); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(kShortDelay); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) { clock_.AdvanceTime(kShortDelay); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, MaxRetransmittableOnWireDelayShift) { QuicPingManagerPeer::SetPerspective(&manager_, Perspective::IS_SERVER); const int kMaxAggressiveRetransmittableOnWireCount = 3; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); for (int i = 0; i <= kMaxAggressiveRetransmittableOnWireCount; i++) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } for (int i = 1; i <= 20; ++i) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); if (i <= 10) { EXPECT_EQ(initial_retransmittable_on_wire_timeout * (1 << i), alarm_->deadline() - clock_.ApproximateNow()); } else { EXPECT_EQ(initial_retransmittable_on_wire_timeout * (1 << 10), alarm_->deadline() - clock_.ApproximateNow()); } clock_.AdvanceTime(alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); } } } } }
279
cpp
google/quiche
internet_checksum
quiche/quic/core/internet_checksum.cc
quiche/quic/core/internet_checksum_test.cc
#ifndef QUICHE_QUIC_CORE_INTERNET_CHECKSUM_H_ #define QUICHE_QUIC_CORE_INTERNET_CHECKSUM_H_ #include <cstddef> #include <cstdint> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_export.h" namespace quic { class QUICHE_EXPORT InternetChecksum { public: void Update(const char* data, size_t size); void Update(const uint8_t* data, size_t size); void Update(absl::string_view data); void Update(absl::Span<const uint8_t> data); uint16_t Value() const; private: uint32_t accumulator_ = 0; }; } #endif #include "quiche/quic/core/internet_checksum.h" #include <stdint.h> #include <string.h> #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace quic { void InternetChecksum::Update(const char* data, size_t size) { const char* current; for (current = data; current + 1 < data + size; current += 2) { uint16_t v; memcpy(&v, current, sizeof(v)); accumulator_ += v; } if (current < data + size) { accumulator_ += *reinterpret_cast<const unsigned char*>(current); } } void InternetChecksum::Update(const uint8_t* data, size_t size) { Update(reinterpret_cast<const char*>(data), size); } void InternetChecksum::Update(absl::string_view data) { Update(data.data(), data.size()); } void InternetChecksum::Update(absl::Span<const uint8_t> data) { Update(reinterpret_cast<const char*>(data.data()), data.size()); } uint16_t InternetChecksum::Value() const { uint32_t total = accumulator_; while (total & 0xffff0000u) { total = (total >> 16u) + (total & 0xffffu); } return ~static_cast<uint16_t>(total); } }
#include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(InternetChecksumTest, MatchesRFC1071Example) { uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6, 0xf7}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x22, result_bytes[0]); ASSERT_EQ(0x0d, result_bytes[1]); } TEST(InternetChecksumTest, MatchesRFC1071ExampleWithOddByteCount) { uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6}; InternetChecksum checksum; checksum.Update(data, 7); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x23, result_bytes[0]); ASSERT_EQ(0x04, result_bytes[1]); } TEST(InternetChecksumTest, MatchesBerkleyExample) { uint8_t data[] = {0xe3, 0x4f, 0x23, 0x96, 0x44, 0x27, 0x99, 0xf3}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x1a, result_bytes[0]); ASSERT_EQ(0xff, result_bytes[1]); } TEST(InternetChecksumTest, ChecksumRequiringMultipleCarriesInLittleEndian) { uint8_t data[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); EXPECT_EQ(0xfd, result_bytes[0]); EXPECT_EQ(0xff, result_bytes[1]); } } }
280
cpp
google/quiche
quic_connection_id
quiche/quic/core/quic_connection_id.cc
quiche/quic/core/quic_connection_id_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_ID_H_ #define QUICHE_QUIC_CORE_QUIC_CONNECTION_ID_H_ #include <cstdint> #include <string> #include <vector> #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { enum QuicConnectionIdIncluded : uint8_t { CONNECTION_ID_PRESENT = 1, CONNECTION_ID_ABSENT = 2, }; inline constexpr uint8_t kQuicMaxConnectionIdWithLengthPrefixLength = 20; inline constexpr uint8_t kQuicMaxConnectionId4BitLength = 18; inline constexpr uint8_t kQuicDefaultConnectionIdLength = 8; inline constexpr uint8_t kQuicMinimumInitialConnectionIdLength = 8; class QUICHE_EXPORT QuicConnectionId { public: QuicConnectionId(); QuicConnectionId(const char* data, uint8_t length); QuicConnectionId(const absl::Span<const uint8_t> data); QuicConnectionId(const QuicConnectionId& other); QuicConnectionId& operator=(const QuicConnectionId& other); ~QuicConnectionId(); uint8_t length() const; void set_length(uint8_t length); const char* data() const; char* mutable_data(); bool IsEmpty() const; size_t Hash() const; template <typename H> friend H AbslHashValue(H h, const QuicConnectionId& c) { return H::combine(std::move(h), c.Hash()); } std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v); bool operator==(const QuicConnectionId& v) const; bool operator!=(const QuicConnectionId& v) const; bool operator<(const QuicConnectionId& v) const; private: union { struct { uint8_t padding_; char data_short_[11]; }; struct { uint8_t length_; char* data_long_; }; }; }; QUICHE_EXPORT QuicConnectionId EmptyQuicConnectionId(); class QUICHE_EXPORT QuicConnectionIdHash { public: size_t operator()(QuicConnectionId const& connection_id) const noexcept { return connection_id.Hash(); } }; } #endif #include "quiche/quic/core/quic_connection_id.h" #include <cstddef> #include <cstdint> #include <cstring> #include <iomanip> #include <ostream> #include <string> #include "absl/strings/escaping.h" #include "openssl/siphash.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { class QuicConnectionIdHasher { public: inline QuicConnectionIdHasher() : QuicConnectionIdHasher(QuicRandom::GetInstance()) {} explicit inline QuicConnectionIdHasher(QuicRandom* random) { random->RandBytes(&sip_hash_key_, sizeof(sip_hash_key_)); } inline size_t Hash(const char* input, size_t input_len) const { return static_cast<size_t>(SIPHASH_24( sip_hash_key_, reinterpret_cast<const uint8_t*>(input), input_len)); } private: uint64_t sip_hash_key_[2]; }; } QuicConnectionId::QuicConnectionId() : QuicConnectionId(nullptr, 0) { static_assert(offsetof(QuicConnectionId, padding_) == offsetof(QuicConnectionId, length_), "bad offset"); static_assert(sizeof(QuicConnectionId) <= 16, "bad size"); } QuicConnectionId::QuicConnectionId(const char* data, uint8_t length) { length_ = length; if (length_ == 0) { return; } if (length_ <= sizeof(data_short_)) { memcpy(data_short_, data, length_); return; } data_long_ = reinterpret_cast<char*>(malloc(length_)); QUICHE_CHECK_NE(nullptr, data_long_); memcpy(data_long_, data, length_); } QuicConnectionId::QuicConnectionId(const absl::Span<const uint8_t> data) : QuicConnectionId(reinterpret_cast<const char*>(data.data()), data.length()) {} QuicConnectionId::~QuicConnectionId() { if (length_ > sizeof(data_short_)) { free(data_long_); data_long_ = nullptr; } } QuicConnectionId::QuicConnectionId(const QuicConnectionId& other) : QuicConnectionId(other.data(), other.length()) {} QuicConnectionId& QuicConnectionId::operator=(const QuicConnectionId& other) { set_length(other.length()); memcpy(mutable_data(), other.data(), length_); return *this; } const char* QuicConnectionId::data() const { if (length_ <= sizeof(data_short_)) { return data_short_; } return data_long_; } char* QuicConnectionId::mutable_data() { if (length_ <= sizeof(data_short_)) { return data_short_; } return data_long_; } uint8_t QuicConnectionId::length() const { return length_; } void QuicConnectionId::set_length(uint8_t length) { char temporary_data[sizeof(data_short_)]; if (length > sizeof(data_short_)) { if (length_ <= sizeof(data_short_)) { memcpy(temporary_data, data_short_, length_); data_long_ = reinterpret_cast<char*>(malloc(length)); QUICHE_CHECK_NE(nullptr, data_long_); memcpy(data_long_, temporary_data, length_); } else { char* realloc_result = reinterpret_cast<char*>(realloc(data_long_, length)); QUICHE_CHECK_NE(nullptr, realloc_result); data_long_ = realloc_result; } } else if (length_ > sizeof(data_short_)) { memcpy(temporary_data, data_long_, length); free(data_long_); data_long_ = nullptr; memcpy(data_short_, temporary_data, length); } length_ = length; } bool QuicConnectionId::IsEmpty() const { return length_ == 0; } size_t QuicConnectionId::Hash() const { static const QuicConnectionIdHasher hasher = QuicConnectionIdHasher(); return hasher.Hash(data(), length_); } std::string QuicConnectionId::ToString() const { if (IsEmpty()) { return std::string("0"); } return absl::BytesToHexString(absl::string_view(data(), length_)); } std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v) { os << v.ToString(); return os; } bool QuicConnectionId::operator==(const QuicConnectionId& v) const { return length_ == v.length_ && memcmp(data(), v.data(), length_) == 0; } bool QuicConnectionId::operator!=(const QuicConnectionId& v) const { return !(v == *this); } bool QuicConnectionId::operator<(const QuicConnectionId& v) const { if (length_ < v.length_) { return true; } if (length_ > v.length_) { return false; } return memcmp(data(), v.data(), length_) < 0; } QuicConnectionId EmptyQuicConnectionId() { return QuicConnectionId(); } static_assert(kQuicDefaultConnectionIdLength == sizeof(uint64_t), "kQuicDefaultConnectionIdLength changed"); static_assert(kQuicDefaultConnectionIdLength == 8, "kQuicDefaultConnectionIdLength changed"); }
#include "quiche/quic/core/quic_connection_id.h" #include <cstdint> #include <cstring> #include <string> #include "absl/base/macros.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic::test { namespace { class QuicConnectionIdTest : public QuicTest {}; TEST_F(QuicConnectionIdTest, Empty) { QuicConnectionId connection_id_empty = EmptyQuicConnectionId(); EXPECT_TRUE(connection_id_empty.IsEmpty()); } TEST_F(QuicConnectionIdTest, DefaultIsEmpty) { QuicConnectionId connection_id_empty = QuicConnectionId(); EXPECT_TRUE(connection_id_empty.IsEmpty()); } TEST_F(QuicConnectionIdTest, NotEmpty) { QuicConnectionId connection_id = test::TestConnectionId(1); EXPECT_FALSE(connection_id.IsEmpty()); } TEST_F(QuicConnectionIdTest, ZeroIsNotEmpty) { QuicConnectionId connection_id = test::TestConnectionId(0); EXPECT_FALSE(connection_id.IsEmpty()); } TEST_F(QuicConnectionIdTest, Data) { char connection_id_data[kQuicDefaultConnectionIdLength]; memset(connection_id_data, 0x42, sizeof(connection_id_data)); QuicConnectionId connection_id1 = QuicConnectionId(connection_id_data, sizeof(connection_id_data)); QuicConnectionId connection_id2 = QuicConnectionId(connection_id_data, sizeof(connection_id_data)); EXPECT_EQ(connection_id1, connection_id2); EXPECT_EQ(connection_id1.length(), kQuicDefaultConnectionIdLength); EXPECT_EQ(connection_id1.data(), connection_id1.mutable_data()); EXPECT_EQ(0, memcmp(connection_id1.data(), connection_id2.data(), sizeof(connection_id_data))); EXPECT_EQ(0, memcmp(connection_id1.data(), connection_id_data, sizeof(connection_id_data))); connection_id2.mutable_data()[0] = 0x33; EXPECT_NE(connection_id1, connection_id2); static const uint8_t kNewLength = 4; connection_id2.set_length(kNewLength); EXPECT_EQ(kNewLength, connection_id2.length()); } TEST_F(QuicConnectionIdTest, SpanData) { QuicConnectionId connection_id = QuicConnectionId({0x01, 0x02, 0x03}); EXPECT_EQ(connection_id.length(), 3); QuicConnectionId empty_connection_id = QuicConnectionId(absl::Span<uint8_t>()); EXPECT_EQ(empty_connection_id.length(), 0); QuicConnectionId connection_id2 = QuicConnectionId({ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, }); EXPECT_EQ(connection_id2.length(), 16); } TEST_F(QuicConnectionIdTest, DoubleConvert) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(42); QuicConnectionId connection_id64_3 = test::TestConnectionId(UINT64_C(0xfedcba9876543210)); EXPECT_EQ(connection_id64_1, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_1))); EXPECT_EQ(connection_id64_2, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_2))); EXPECT_EQ(connection_id64_3, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_3))); EXPECT_NE(connection_id64_1, connection_id64_2); EXPECT_NE(connection_id64_1, connection_id64_3); EXPECT_NE(connection_id64_2, connection_id64_3); } TEST_F(QuicConnectionIdTest, Hash) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_1b = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(42); QuicConnectionId connection_id64_3 = test::TestConnectionId(UINT64_C(0xfedcba9876543210)); EXPECT_EQ(connection_id64_1.Hash(), connection_id64_1b.Hash()); EXPECT_NE(connection_id64_1.Hash(), connection_id64_2.Hash()); EXPECT_NE(connection_id64_1.Hash(), connection_id64_3.Hash()); EXPECT_NE(connection_id64_2.Hash(), connection_id64_3.Hash()); const char connection_id_bytes[255] = {}; for (uint8_t i = 0; i < sizeof(connection_id_bytes) - 1; ++i) { QuicConnectionId connection_id_i(connection_id_bytes, i); for (uint8_t j = i + 1; j < sizeof(connection_id_bytes); ++j) { QuicConnectionId connection_id_j(connection_id_bytes, j); EXPECT_NE(connection_id_i.Hash(), connection_id_j.Hash()); } } } TEST_F(QuicConnectionIdTest, AssignAndCopy) { QuicConnectionId connection_id = test::TestConnectionId(1); QuicConnectionId connection_id2 = test::TestConnectionId(2); connection_id = connection_id2; EXPECT_EQ(connection_id, test::TestConnectionId(2)); EXPECT_NE(connection_id, test::TestConnectionId(1)); connection_id = QuicConnectionId(test::TestConnectionId(1)); EXPECT_EQ(connection_id, test::TestConnectionId(1)); EXPECT_NE(connection_id, test::TestConnectionId(2)); } TEST_F(QuicConnectionIdTest, ChangeLength) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(2); QuicConnectionId connection_id136_2 = test::TestConnectionId(2); connection_id136_2.set_length(17); memset(connection_id136_2.mutable_data() + 8, 0, 9); char connection_id136_2_bytes[17] = {0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}; QuicConnectionId connection_id136_2b(connection_id136_2_bytes, sizeof(connection_id136_2_bytes)); EXPECT_EQ(connection_id136_2, connection_id136_2b); QuicConnectionId connection_id = connection_id64_1; connection_id.set_length(17); EXPECT_NE(connection_id64_1, connection_id); connection_id.set_length(8); EXPECT_EQ(connection_id64_1, connection_id); connection_id.set_length(17); memset(connection_id.mutable_data(), 0, connection_id.length()); memcpy(connection_id.mutable_data(), connection_id64_2.data(), connection_id64_2.length()); EXPECT_EQ(connection_id136_2, connection_id); EXPECT_EQ(connection_id136_2b, connection_id); QuicConnectionId connection_id120(connection_id136_2_bytes, 15); connection_id.set_length(15); EXPECT_EQ(connection_id120, connection_id); QuicConnectionId connection_id2 = connection_id120; connection_id2.set_length(17); connection_id2.mutable_data()[15] = 0; connection_id2.mutable_data()[16] = 0; EXPECT_EQ(connection_id136_2, connection_id2); EXPECT_EQ(connection_id136_2b, connection_id2); } } }
281
cpp
google/quiche
tls_server_handshaker
quiche/quic/core/tls_server_handshaker.cc
quiche/quic/core/tls_server_handshaker_test.cc
#ifndef QUICHE_QUIC_CORE_TLS_SERVER_HANDSHAKER_H_ #define QUICHE_QUIC_CORE_TLS_SERVER_HANDSHAKER_H_ #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "openssl/base.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_message_parser.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/tls_connection.h" #include "quiche/quic/core/crypto/tls_server_connection.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_accumulator.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/tls_handshaker.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { class QUICHE_EXPORT TlsServerHandshaker : public TlsHandshaker, public TlsServerConnection::Delegate, public ProofSourceHandleCallback, public QuicCryptoServerStreamBase { public: TlsServerHandshaker(QuicSession* session, const QuicCryptoServerConfig* crypto_config); TlsServerHandshaker(const TlsServerHandshaker&) = delete; TlsServerHandshaker& operator=(const TlsServerHandshaker&) = delete; ~TlsServerHandshaker() override; void CancelOutstandingCallbacks() override; bool GetBase64SHA256ClientChannelID(std::string* output) const override; void SendServerConfigUpdate( const CachedNetworkParameters* cached_network_params) override; bool DisableResumption() override; bool IsZeroRtt() const override; bool IsResumption() const override; bool ResumptionAttempted() const override; bool EarlyDataAttempted() const override; int NumServerConfigUpdateMessagesSent() const override; const CachedNetworkParameters* PreviousCachedNetworkParams() const override; void SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) override; void OnPacketDecrypted(EncryptionLevel level) override; void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) override; void OnHandshakeDoneReceived() override; std::string GetAddressToken( const CachedNetworkParameters* cached_network_params) const override; bool ValidateAddressToken(absl::string_view token) const override; void OnNewTokenReceived(absl::string_view token) override; bool ShouldSendExpectCTHeader() const override; bool DidCertMatchSni() const override; const ProofSource::Details* ProofSourceDetails() const override; bool ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) override; SSL* GetSsl() const override; bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override; EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override; ssl_early_data_reason_t EarlyDataReason() const override; bool encryption_established() const override; bool one_rtt_keys_available() const override; const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override; CryptoMessageParser* crypto_message_parser() override; HandshakeState GetHandshakeState() const override; void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> state) override; size_t BufferSizeLimitForLevel(EncryptionLevel level) const override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void SetWriteSecret(EncryptionLevel level, const SSL_CIPHER* cipher, absl::Span<const uint8_t> write_secret) override; virtual std::string GetAcceptChValueForHostname( const std::string& hostname) const; bool UseAlpsNewCodepoint() const; ClientCertMode client_cert_mode() const { return tls_connection_.ssl_config().client_cert_mode; } protected: void InfoCallback(int type, int value) override; virtual std::unique_ptr<ProofSourceHandle> MaybeCreateProofSourceHandle(); virtual void OverrideQuicConfigDefaults(QuicConfig* config); virtual bool ValidateHostname(const std::string& hostname) const; const TlsConnection* tls_connection() const override { return &tls_connection_; } virtual bool ProcessAdditionalTransportParameters( const TransportParameters& ) { return true; } void AdvanceHandshakeFromCallback(); void FinishHandshake() override; void ProcessPostHandshakeMessage() override {} QuicAsyncStatus VerifyCertChain( const std::vector<std::string>& certs, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) override; void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) override; ssl_select_cert_result_t EarlySelectCertCallback( const SSL_CLIENT_HELLO* client_hello) override; int TlsExtServernameCallback(int* out_alert) override; int SelectAlpn(const uint8_t** out, uint8_t* out_len, const uint8_t* in, unsigned in_len) override; ssl_private_key_result_t PrivateKeySign(uint8_t* out, size_t* out_len, size_t max_out, uint16_t sig_alg, absl::string_view in) override; ssl_private_key_result_t PrivateKeyComplete(uint8_t* out, size_t* out_len, size_t max_out) override; size_t SessionTicketMaxOverhead() override; int SessionTicketSeal(uint8_t* out, size_t* out_len, size_t max_out_len, absl::string_view in) override; ssl_ticket_aead_result_t SessionTicketOpen(uint8_t* out, size_t* out_len, size_t max_out_len, absl::string_view in) override; ssl_ticket_aead_result_t FinalizeSessionTicketOpen(uint8_t* out, size_t* out_len, size_t max_out_len); TlsConnection::Delegate* ConnectionDelegate() override { return this; } const std::optional<QuicAsyncStatus>& select_cert_status() const { return select_cert_status_; } bool HasValidSignature(size_t max_signature_size) const; void OnSelectCertificateDone(bool ok, bool is_sync, SSLConfig ssl_config, absl::string_view ticket_encryption_key, bool cert_matched_sni) override; void OnComputeSignatureDone( bool ok, bool is_sync, std::string signature, std::unique_ptr<ProofSource::Details> details) override; void set_encryption_established(bool encryption_established) { encryption_established_ = encryption_established; } bool WillNotCallComputeSignature() const override; void SetIgnoreTicketOpen(bool value) { ignore_ticket_open_ = value; } private: class QUICHE_EXPORT DecryptCallback : public ProofSource::DecryptCallback { public: explicit DecryptCallback(TlsServerHandshaker* handshaker); void Run(std::vector<uint8_t> plaintext) override; void Cancel(); bool IsDone() const { return handshaker_ == nullptr; } private: TlsServerHandshaker* handshaker_; }; class QUICHE_EXPORT DefaultProofSourceHandle : public ProofSourceHandle { public: DefaultProofSourceHandle(TlsServerHandshaker* handshaker, ProofSource* proof_source); ~DefaultProofSourceHandle() override; void CloseHandle() override; QuicAsyncStatus SelectCertificate( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const QuicConnectionId& original_connection_id, absl::string_view ssl_capabilities, const std::string& hostname, absl::string_view client_hello, const std::string& alpn, std::optional<std::string> alps, const std::vector<uint8_t>& quic_transport_params, const std::optional<std::vector<uint8_t>>& early_data_context, const QuicSSLConfig& ssl_config) override; QuicAsyncStatus ComputeSignature(const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, uint16_t signature_algorithm, absl::string_view in, size_t max_signature_size) override; protected: ProofSourceHandleCallback* callback() override { return handshaker_; } private: class QUICHE_EXPORT DefaultSignatureCallback : public ProofSource::SignatureCallback { public: explicit DefaultSignatureCallback(DefaultProofSourceHandle* handle) : handle_(handle) {} void Run(bool ok, std::string signature, std::unique_ptr<ProofSource::Details> details) override { if (handle_ == nullptr) { return; } DefaultProofSourceHandle* handle = handle_; handle_ = nullptr; handle->signature_callback_ = nullptr; if (handle->handshaker_ != nullptr) { handle->handshaker_->OnComputeSignatureDone( ok, is_sync_, std::move(signature), std::move(details)); } } void Cancel() { handle_ = nullptr; } void set_is_sync(bool is_sync) { is_sync_ = is_sync; } private: DefaultProofSourceHandle* handle_; bool is_sync_ = true; }; TlsServerHandshaker* handshaker_; ProofSource* proof_source_; DefaultSignatureCallback* signature_callback_ = nullptr; }; struct QUICHE_EXPORT SetTransportParametersResult { bool success = false; std::vector<uint8_t> quic_transport_params; std::optional<std::vector<uint8_t>> early_data_context; }; SetTransportParametersResult SetTransportParameters(); bool ProcessTransportParameters(const SSL_CLIENT_HELLO* client_hello, std::string* error_details); bool TransportParametersMatch( absl::Span<const uint8_t> serialized_params) const; struct QUICHE_EXPORT SetApplicationSettingsResult { bool success = false; std::string alps_buffer; }; SetApplicationSettingsResult SetApplicationSettings(absl::string_view alpn); QuicConnectionStats& connection_stats() { return session()->connection()->mutable_stats(); } QuicTime now() const { return session()->GetClock()->Now(); } QuicConnectionContext* connection_context() { return session()->connection()->context(); } std::unique_ptr<ProofSourceHandle> proof_source_handle_; ProofSource* proof_source_; std::shared_ptr<DecryptCallback> ticket_decryption_callback_; std::vector<uint8_t> decrypted_session_ticket_; bool ticket_received_ = false; bool early_data_attempted_ = false; bool ignore_ticket_open_ = false; bool alps_new_codepoint_received_ = false; std::optional<QuicAsyncStatus> select_cert_status_; std::string cert_verify_sig_; std::unique_ptr<ProofSource::Details> proof_source_details_; std::optional<QuicTimeAccumulator> async_op_timer_; std::unique_ptr<ApplicationState> application_state_; std::string pre_shared_key_; std::string ticket_encryption_key_; HandshakeState state_ = HANDSHAKE_START; bool encryption_established_ = false; bool valid_alpn_received_ = false; bool can_disable_resumption_ = true; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> crypto_negotiated_params_; TlsServerConnection tls_connection_; const QuicCryptoServerConfig* crypto_config_; mutable std::unique_ptr<CachedNetworkParameters> last_received_cached_network_params_; bool cert_matched_sni_ = false; TransportParameters server_params_; }; } #endif #include "quiche/quic/core/tls_server_handshaker.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "openssl/base.h" #include "openssl/bytestring.h" #include "openssl/ssl.h" #include "openssl/tls1.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_message_parser.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_accumulator.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_handshaker.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_hostname_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_server_stats.h" #include "quiche/quic/platform/api/quic_socket_address.h" #define RECORD_LATENCY_IN_US(stat_name, latency, comment) \ do { \ const int64_t latency_in_us = (latency).ToMicroseconds(); \ QUIC_DVLOG(1) << "Recording " stat_name ": " << latency_in_us; \ QUIC_SERVER_HISTOGRAM_COUNTS(stat_name, latency_in_us, 1, 10000000, 50, \ comment); \ } while (0) namespace quic { namespace { uint16_t kDefaultPort = 443; } TlsServerHandshaker::DefaultProofSourceHandle::DefaultProofSourceHandle( TlsServerHandshaker* handshaker, ProofSource* proof_source) : handshaker_(handshaker), proof_source_(proof_source) {} TlsServerHandshaker::DefaultProofSourceHandle::~DefaultProofSourceHandle() { CloseHandle(); } void TlsServerHandshaker::DefaultProofSourceHandle::CloseHandle() { QUIC_DVLOG(1) << "CloseHandle. is_signature_pending=" << (signature_callback_ != nullptr); if (signature_callback_) { signature_callback_->Cancel(); signature_callback_ = nullptr; } } QuicAsyncStatus TlsServerHandshaker::DefaultProofSourceHandle::SelectCertificate( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const QuicConnectionId& , absl::string_view , const std::string& hostname, absl::string_view , const std::string& , std::optional<std::string> , const std::vector<uint8_t>& , const std::optional<std::vector<uint8_t>>& , const QuicSSLConfig& ) { if (!handshaker_ || !proof_source_) { QUIC_BUG(quic_bug_10341_1) << "SelectCertificate called on a detached handle"; return QUIC_FAILURE; } bool cert_matched_sni; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain = proof_source_->GetCertChain(server_address, client_address, hostname, &cert_matched_sni); handshaker_->OnSelectCertificateDone( true, true, ProofSourceHandleCallback::LocalSSLConfig{chain.get(), QuicDelayedSSLConfig()}, absl::string_view(), cert_matched_sni); if (!handshaker_->select_cert_status().has_value()) { QUIC_BUG(quic_bug_12423_1) << "select_cert_status() has no value after a synchronous select cert"; return QUIC_SUCCESS; } return *handshaker_->select_cert_status(); } QuicAsyncStatus TlsServerHandshaker::DefaultProofSourceHandle::ComputeSignature( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, uint16_t signature_algorithm, absl::string_view in, size_t max_signature_size) { if (!handshaker_ || !proof_source_) { QUIC_BUG(quic_bug_10341_2) << "ComputeSignature called on a detached handle"; return QUIC_FAILURE; } if (signature_callback_) { QUIC_BUG(quic_bug_10341_3) << "ComputeSignature called while pending"; return QUIC_FAILURE; } signature_callback_ = new DefaultSignatureCallback(this); proof_source_->ComputeTlsSignature( server_address, client_address, hostname, signature_algorithm, in, std::unique_ptr<DefaultSignatureCallback>(signature_callback_)); if (signature_callback_) { QUIC_DVLOG(1) << "ComputeTlsSignature is pending"; signature_callback_->set_is_sync(false); return QUIC_PENDING; } bool success = handshaker_->HasValidSignature(max_signature_size); QUIC_DVLOG(1) << "ComputeTlsSignature completed synchronously. success:" << success; return success ? QUIC_SUCCESS : QUIC_FAILURE; } TlsServerHandshaker::DecryptCallback::DecryptCallback( TlsServerHandshaker* handshaker) : handshaker_(handshaker) {} void TlsServerHandshaker::DecryptCallback::Run(std::vector<uint8_t> plaintext) { if (handshaker_ == nullptr) { return; } TlsServerHandshaker* handshaker = handshaker_; handshaker_ = nullptr; handshaker->decrypted_session_ticket_ = std::move(plaintext); const bool is_async = (handshaker->expected_ssl_error() == SSL_ERROR_PENDING_TICKET); std::optional<QuicConnectionContextSwitcher> context_switcher; if (is_async) { context_switcher.emplace(handshaker->connection_context()); } QUIC_TRACESTRING( absl::StrCat("TLS ticket decryption done. len(decrypted_ticket):", handshaker->decrypted_session_ticket_.size())); if (is_async) { handshaker->AdvanceHandshakeFromCallback(); } handshaker->ticket_decryption_callback_ = nullptr; } void TlsServerHandshaker::DecryptCallback::Cancel() { QUICHE_DCHECK(handshaker_); handshaker_ = nullptr; } TlsServerHandshaker::TlsServerHandshaker( QuicSession* session, const QuicCryptoServerConfig* crypto_config) : TlsHandshaker(this, session), QuicCryptoServerStreamBase(session), proof_source_(crypto_config->proof_source()), pre_shared_key_(crypto_config->pre_shared_key()), crypto_negotiated_params_(new QuicCryptoNegotiatedParameters), tls_connection_(crypto_config->ssl_ctx(), this, session->GetSSLConfig()), crypto_config_(crypto_config) { QUIC_DVLOG(1) << "TlsServerHandshaker: client_cert_mode initial value: " << client_cert_mode(); QUICHE_DCHECK_EQ(PROTOCOL_TLS1_3, session->connection()->version().handshake_protocol); SSL_set_accept_state(ssl()); int use_legacy_extension = 0; if (session->version().UsesLegacyTlsExtension()) { use_legacy_extension = 1; } SSL_set_quic_use_legacy_codepoint(ssl(), use_legacy_extension); if (session->connection()->context()->tracer) { tls_connection_.EnableInfoCallback(); } #if BORINGSSL_API_VERSION >= 22 if (!crypto_config->preferred_groups().empty()) { SSL_set1_group_ids(ssl(), crypto_config->preferred_groups().data(), crypto_config->preferred_groups().size()); } #endif } TlsServerHandshaker::~TlsServerHandshaker() { CancelOutstandingCallbacks(); } void TlsServerHandshaker::CancelOutstandingCallbacks() { if (proof_source_handle_) { proof_source_handle_->CloseHandle(); } if (ticket_decryption_callback_) { ticket_decryption_callback_->Cancel(); ticket_decryption_callback_ = nullptr; } } void TlsServerHandshaker::InfoCallback(int type, int value) { QuicConnectionTracer* tracer = session()->connection()->context()->tracer.get(); if (tracer == nullptr) { return; } if (type & SSL_CB_LOOP) { tracer->PrintString( absl::StrCat("SSL:ACCEPT_LOOP:", SSL_state_string_long(ssl()))); } else if (type & SSL_CB_ALERT) { const char* prefix = (type & SSL_CB_READ) ? "SSL:READ_ALERT:" : "SSL:WRITE_ALERT:"; tracer->PrintString(absl::StrCat(prefix, SSL_alert_type_string_long(value), ":", SSL_alert_desc_string_long(value))); } else if (type & SSL_CB_EXIT) { const char* prefix = (value == 1) ? "SSL:ACCEPT_EXIT_OK:" : "SSL:ACCEPT_EXIT_FAIL:"; tracer->PrintString(absl::StrCat(prefix, SSL_state_string_long(ssl()))); } else if (type & SSL_CB_HANDSHAKE_START) { tracer->PrintString( absl::StrCat("SSL:HANDSHAKE_START:", SSL_state_string_long(ssl()))); } else if (type & SSL_CB_HANDSHAKE_DONE) { tracer->PrintString( absl::StrCat("SSL:HANDSHAKE_DONE:", SSL_state_string_long(ssl()))); } else { QUIC_DLOG(INFO) << "Unknown event type " << type << ": " << SSL_state_string_long(ssl()); tracer->PrintString( absl::StrCat("SSL:unknown:", value, ":", SSL_state_string_long(ssl()))); } } std::unique_ptr<ProofSourceHandle> TlsServerHandshaker::MaybeCreateProofSourceHandle() { return std::make_unique<DefaultProofSourceHandle>(this, proof_source_); } bool TlsServerHandshaker::GetBase64SHA256ClientChannelID( std::string* ) const { return false; } void TlsServerHandshaker::SendServerConfigUpdate( const CachedNetworkParameters* ) { } bool TlsServerHandshaker::DisableResumption() { if (!can_disable_resumption_ || !session()->connection()->connected()) { return false; } tls_connection_.DisableTicketSupport(); return true; } bool TlsServerHandshaker::IsZeroRtt() const { return SSL_early_data_accepted(ssl()); } bool TlsServerHandshaker::IsResumption() const { return SSL_session_reused(ssl()); } bool TlsServerHandshaker::ResumptionAttempted() const { return ticket_received_; } bool TlsServerHandshaker::EarlyDataAttempted() const { QUIC_BUG_IF(quic_tls_early_data_attempted_too_early, !select_cert_status_.has_value()) << "EarlyDataAttempted must be called after EarlySelectCertCallback is " "started"; return early_data_attempted_; } int TlsServerHandshaker::NumServerConfigUpdateMessagesSent() const { return 0; } const CachedNetworkParameters* TlsServerHandshaker::PreviousCachedNetworkParams() const { return last_received_cached_network_params_.get(); } void TlsServerHandshaker::SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) { last_received_cached_network_params_ = std::make_unique<CachedNetworkParameters>(cached_network_params); } void TlsServerHandshaker::OnPacketDecrypted(EncryptionLevel level) { if (level == ENCRYPTION_HANDSHAKE && state_ < HANDSHAKE_PROCESSED) { state_ = HANDSHAKE_PROCESSED; handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_INITIAL); } } void TlsServerHandshaker::OnHandshakeDoneReceived() { QUICHE_DCHECK(false); } void TlsServerHandshaker::OnNewTokenReceived(absl::string_view ) { QUICHE_DCHECK(false); } std::string TlsServerHandshaker::GetAddressToken( const CachedNetworkParameters* cached_network_params) const { SourceAddressTokens empty_previous_tokens; const QuicConnection* connection = session()->connection(); return crypto_config_->NewSourceAddressToken( crypto_config_->source_address_token_boxer(), empty_previous_tokens, connection->effective_peer_address().host(), connection->random_generator(), connection->clock()->WallNow(), cached_network_params); } bool TlsServerHandshaker::ValidateAddressToken(absl::string_view token) const { SourceAddressTokens tokens; HandshakeFailureReason reason = crypto_config_->ParseSourceAddressToken( crypto_config_->source_address_token_boxer(), token, tokens); if (reason != HANDSHAKE_OK) { QUIC_DLOG(WARNING) << "Failed to parse source address token: " << CryptoUtils::HandshakeFailureReasonToString(reason); return false; } auto cached_network_params = std::make_unique<CachedNetworkParameters>(); reason = crypto_config_->ValidateSourceAddressTokens( tokens, session()->connection()->effective_peer_address().host(), session()->connection()->clock()->WallNow(), cached_network_params.get()); if (reason != HANDSHAKE_OK) { QUIC_DLOG(WARNING) << "Failed to validate source address token: " << CryptoUtils::HandshakeFailureReasonToString(reason); return false; } last_received_cached_network_params_ = std::move(cached_network_params); return true; } bool TlsServerHandshaker::ShouldSendExpectCTHeader() const { return false; } bool TlsServerHandshaker::DidCertMatchSni() const { return cert_matched_sni_; } const ProofSource::Details* TlsServerHandshaker::ProofSourceDetails() const { return proof_sou
#include "quiche/quic/core/tls_server_handshaker.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/certificate_util.h" #include "quiche/quic/core/crypto/client_proof_source.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_client_handshaker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/failing_proof_source.h" #include "quiche/quic/test_tools/fake_proof_source.h" #include "quiche/quic/test_tools/fake_proof_source_handle.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/quic/test_tools/test_ticket_crypter.h" namespace quic { class QuicConnection; class QuicStream; } using testing::_; using testing::NiceMock; using testing::Return; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kServerPort = 443; struct TestParams { ParsedQuicVersion version; bool disable_resumption; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.disable_resumption ? "ResumptionDisabled" : "ResumptionEnabled")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (const auto& version : AllSupportedVersionsWithTls()) { for (bool disable_resumption : {false, true}) { params.push_back(TestParams{version, disable_resumption}); } } return params; } class TestTlsServerHandshaker : public TlsServerHandshaker { public: static constexpr TransportParameters::TransportParameterId kFailHandshakeParam{0xFFEACA}; TestTlsServerHandshaker(QuicSession* session, const QuicCryptoServerConfig* crypto_config) : TlsServerHandshaker(session, crypto_config), proof_source_(crypto_config->proof_source()) { ON_CALL(*this, MaybeCreateProofSourceHandle()) .WillByDefault(testing::Invoke( this, &TestTlsServerHandshaker::RealMaybeCreateProofSourceHandle)); ON_CALL(*this, OverrideQuicConfigDefaults(_)) .WillByDefault(testing::Invoke( this, &TestTlsServerHandshaker::RealOverrideQuicConfigDefaults)); } MOCK_METHOD(std::unique_ptr<ProofSourceHandle>, MaybeCreateProofSourceHandle, (), (override)); MOCK_METHOD(void, OverrideQuicConfigDefaults, (QuicConfig * config), (override)); void SetupProofSourceHandle( FakeProofSourceHandle::Action select_cert_action, FakeProofSourceHandle::Action compute_signature_action, QuicDelayedSSLConfig dealyed_ssl_config = QuicDelayedSSLConfig()) { EXPECT_CALL(*this, MaybeCreateProofSourceHandle()) .WillOnce( testing::Invoke([this, select_cert_action, compute_signature_action, dealyed_ssl_config]() { auto handle = std::make_unique<FakeProofSourceHandle>( proof_source_, this, select_cert_action, compute_signature_action, dealyed_ssl_config); fake_proof_source_handle_ = handle.get(); return handle; })); } FakeProofSourceHandle* fake_proof_source_handle() { return fake_proof_source_handle_; } bool received_client_cert() const { return received_client_cert_; } using TlsServerHandshaker::AdvanceHandshake; using TlsServerHandshaker::expected_ssl_error; protected: QuicAsyncStatus VerifyCertChain( const std::vector<std::string>& certs, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) override { received_client_cert_ = true; return TlsServerHandshaker::VerifyCertChain(certs, error_details, details, out_alert, std::move(callback)); } bool ProcessAdditionalTransportParameters( const TransportParameters& params) override { return !params.custom_parameters.contains(kFailHandshakeParam); } private: std::unique_ptr<ProofSourceHandle> RealMaybeCreateProofSourceHandle() { return TlsServerHandshaker::MaybeCreateProofSourceHandle(); } void RealOverrideQuicConfigDefaults(QuicConfig* config) { return TlsServerHandshaker::OverrideQuicConfigDefaults(config); } FakeProofSourceHandle* fake_proof_source_handle_ = nullptr; ProofSource* proof_source_ = nullptr; bool received_client_cert_ = false; }; class TlsServerHandshakerTestSession : public TestQuicSpdyServerSession { public: using TestQuicSpdyServerSession::TestQuicSpdyServerSession; std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* ) override { if (connection()->version().handshake_protocol == PROTOCOL_TLS1_3) { return std::make_unique<NiceMock<TestTlsServerHandshaker>>(this, crypto_config); } QUICHE_CHECK(false) << "Unsupported handshake protocol: " << connection()->version().handshake_protocol; return nullptr; } }; class TlsServerHandshakerTest : public QuicTestWithParam<TestParams> { public: TlsServerHandshakerTest() : server_compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), server_id_(kServerHostname, kServerPort, false), supported_versions_({GetParam().version}) { SetQuicFlag(quic_disable_server_tls_resumption, GetParam().disable_resumption); client_crypto_config_ = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<test::SimpleSessionCache>()); InitializeServerConfig(); InitializeServer(); InitializeFakeClient(); } ~TlsServerHandshakerTest() override { server_session_.reset(); client_session_.reset(); helpers_.clear(); alarm_factories_.clear(); } void InitializeServerConfig() { auto ticket_crypter = std::make_unique<TestTicketCrypter>(); ticket_crypter_ = ticket_crypter.get(); auto proof_source = std::make_unique<FakeProofSource>(); proof_source_ = proof_source.get(); proof_source_->SetTicketCrypter(std::move(ticket_crypter)); server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()); } void InitializeServerConfigWithFailingProofSource() { server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::make_unique<FailingProofSource>(), KeyExchangeSource::Default()); } void CreateTlsServerHandshakerTestSession(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory) { server_connection_ = new PacketSavingConnection( helper, alarm_factory, Perspective::IS_SERVER, ParsedVersionOfIndex(supported_versions_, 0)); TlsServerHandshakerTestSession* server_session = new TlsServerHandshakerTestSession( server_connection_, DefaultQuicConfig(), supported_versions_, server_crypto_config_.get(), &server_compressed_certs_cache_); server_session->set_client_cert_mode(initial_client_cert_mode_); server_session->Initialize(); server_connection_->AdvanceTime(QuicTime::Delta::FromSeconds(100000)); QUICHE_CHECK(server_session); server_session_.reset(server_session); } void InitializeServerWithFakeProofSourceHandle() { helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateTlsServerHandshakerTestSession(helpers_.back().get(), alarm_factories_.back().get()); server_handshaker_ = static_cast<NiceMock<TestTlsServerHandshaker>*>( server_session_->GetMutableCryptoStream()); EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .Times(testing::AnyNumber()); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillRepeatedly([this](const std::vector<absl::string_view>& alpns) { return std::find( alpns.cbegin(), alpns.cend(), AlpnForVersion(server_session_->connection()->version())); }); crypto_test_utils::SetupCryptoServerConfigForTest( server_connection_->clock(), server_connection_->random_generator(), server_crypto_config_.get()); } void InitializeServer() { TestQuicSpdyServerSession* server_session = nullptr; helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateServerSessionForTest( server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_, helpers_.back().get(), alarm_factories_.back().get(), server_crypto_config_.get(), &server_compressed_certs_cache_, &server_connection_, &server_session); QUICHE_CHECK(server_session); server_session_.reset(server_session); server_handshaker_ = nullptr; EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .Times(testing::AnyNumber()); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillRepeatedly([this](const std::vector<absl::string_view>& alpns) { return std::find( alpns.cbegin(), alpns.cend(), AlpnForVersion(server_session_->connection()->version())); }); crypto_test_utils::SetupCryptoServerConfigForTest( server_connection_->clock(), server_connection_->random_generator(), server_crypto_config_.get()); } QuicCryptoServerStreamBase* server_stream() { return server_session_->GetMutableCryptoStream(); } QuicCryptoClientStream* client_stream() { return client_session_->GetMutableCryptoStream(); } void InitializeFakeClient() { TestQuicSpdyClientSession* client_session = nullptr; helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateClientSessionForTest( server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_, helpers_.back().get(), alarm_factories_.back().get(), client_crypto_config_.get(), &client_connection_, &client_session); const std::string default_alpn = AlpnForVersion(client_connection_->version()); ON_CALL(*client_session, GetAlpnsToOffer()) .WillByDefault(Return(std::vector<std::string>({default_alpn}))); QUICHE_CHECK(client_session); client_session_.reset(client_session); moved_messages_counts_ = {0, 0}; } void CompleteCryptoHandshake() { while (!client_stream()->one_rtt_keys_available() || !server_stream()->one_rtt_keys_available()) { auto previous_moved_messages_counts = moved_messages_counts_; AdvanceHandshakeWithFakeClient(); ASSERT_NE(previous_moved_messages_counts, moved_messages_counts_); } } void AdvanceHandshakeWithFakeClient() { QUICHE_CHECK(server_connection_); QUICHE_CHECK(client_session_ != nullptr); EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber()); EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*server_connection_, OnCanWrite()).Times(testing::AnyNumber()); if (moved_messages_counts_.first == 0) { client_stream()->CryptoConnect(); } moved_messages_counts_ = crypto_test_utils::AdvanceHandshake( client_connection_, client_stream(), moved_messages_counts_.first, server_connection_, server_stream(), moved_messages_counts_.second); } void ExpectHandshakeSuccessful() { EXPECT_TRUE(client_stream()->one_rtt_keys_available()); EXPECT_TRUE(client_stream()->encryption_established()); EXPECT_TRUE(server_stream()->one_rtt_keys_available()); EXPECT_TRUE(server_stream()->encryption_established()); EXPECT_EQ(HANDSHAKE_COMPLETE, client_stream()->GetHandshakeState()); EXPECT_EQ(HANDSHAKE_CONFIRMED, server_stream()->GetHandshakeState()); const auto& client_crypto_params = client_stream()->crypto_negotiated_params(); const auto& server_crypto_params = server_stream()->crypto_negotiated_params(); EXPECT_NE(0, client_crypto_params.cipher_suite); EXPECT_NE(0, client_crypto_params.key_exchange_group); EXPECT_NE(0, client_crypto_params.peer_signature_algorithm); EXPECT_EQ(client_crypto_params.cipher_suite, server_crypto_params.cipher_suite); EXPECT_EQ(client_crypto_params.key_exchange_group, server_crypto_params.key_exchange_group); EXPECT_EQ(0, server_crypto_params.peer_signature_algorithm); } FakeProofSourceHandle::SelectCertArgs last_select_cert_args() const { QUICHE_CHECK(server_handshaker_ && server_handshaker_->fake_proof_source_handle()); QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle() ->all_select_cert_args() .empty()); return server_handshaker_->fake_proof_source_handle() ->all_select_cert_args() .back(); } FakeProofSourceHandle::ComputeSignatureArgs last_compute_signature_args() const { QUICHE_CHECK(server_handshaker_ && server_handshaker_->fake_proof_source_handle()); QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .empty()); return server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .back(); } protected: bool SetupClientCert() { auto client_proof_source = std::make_unique<DefaultClientProofSource>(); CertificatePrivateKey client_cert_key( MakeKeyPairForSelfSignedCertificate()); CertificateOptions options; options.subject = "CN=subject"; options.serial_number = 0x12345678; options.validity_start = {2020, 1, 1, 0, 0, 0}; options.validity_end = {2049, 12, 31, 0, 0, 0}; std::string der_cert = CreateSelfSignedCertificate(*client_cert_key.private_key(), options); quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> client_cert_chain(new ClientProofSource::Chain({der_cert})); if (!client_proof_source->AddCertAndKey({"*"}, client_cert_chain, std::move(client_cert_key))) { return false; } client_crypto_config_->set_proof_source(std::move(client_proof_source)); return true; } std::vector<std::unique_ptr<MockQuicConnectionHelper>> helpers_; std::vector<std::unique_ptr<MockAlarmFactory>> alarm_factories_; PacketSavingConnection* server_connection_; std::unique_ptr<TestQuicSpdyServerSession> server_session_; NiceMock<TestTlsServerHandshaker>* server_handshaker_ = nullptr; TestTicketCrypter* ticket_crypter_; FakeProofSource* proof_source_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; QuicCompressedCertsCache server_compressed_certs_cache_; QuicServerId server_id_; ClientCertMode initial_client_cert_mode_ = ClientCertMode::kNone; PacketSavingConnection* client_connection_; std::unique_ptr<QuicCryptoClientConfig> client_crypto_config_; std::unique_ptr<TestQuicSpdyClientSession> client_session_; crypto_test_utils::FakeClientOptions client_options_; std::pair<size_t, size_t> moved_messages_counts_ = {0, 0}; ParsedQuicVersionVector supported_versions_; }; INSTANTIATE_TEST_SUITE_P(TlsServerHandshakerTests, TlsServerHandshakerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(TlsServerHandshakerTest, NotInitiallyConected) { EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, ConnectedAfterTlsHandshake) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol()); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertSuccess) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertFailure) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::FAIL_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); EXPECT_EQ(moved_messages_counts_.second, 0u); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertAndSignature) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_ASYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); EXPECT_EQ(server_handshaker_->expected_ssl_error(), SSL_ERROR_PENDING_CERTIFICATE); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); EXPECT_EQ(server_handshaker_->expected_ssl_error(), SSL_ERROR_WANT_PRIVATE_KEY_OPERATION); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSignature) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); proof_source_->Activate(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1); proof_source_->InvokePendingCallback(0); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, CancelPendingSelectCert) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->CancelOutstandingCallbacks(); ASSERT_FALSE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); } TEST_P(TlsServerHandshakerTest, CancelPendingSignature) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); proof_source_->Activate(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1); server_session_ = nullptr; proof_source_->InvokePendingCallback(0); } TEST_P(TlsServerHandshakerTest, ExtractSNI) { CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "test.example.com"); } TEST_P(TlsServerHandshakerTest, ServerConnectionIdPassedToSelectCert) { InitializeServerWithFakeProofSourceHandle(); server_session_->set_early_data_enabled(false); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(last_select_cert_args().original_connection_id, TestConnectionId()); } TEST_P(TlsServerHandshakerTest, HostnameForCertSelectionAndComputeSignature) { server_id_ = QuicServerId("tEsT.EXAMPLE.CoM", kServerPort, false); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "test.example.com"); EXPECT_EQ(last_select_cert_args().hostname, "test.example.com"); EXPECT_EQ(last_compute_signature_args().hostname, "test.example.com"); } TEST_P(TlsServerHandshakerTest, SSLConfigForCertSelection) { InitializeServerWithFakeProofSourceHandle(); server_session_->set_early_data_enabled(false); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(last_select_cert_args().ssl_config.early_data_enabled); } TEST_P(TlsServerHandshakerTest, ConnectionClosedOnTlsError) { EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _)); char bogus_handshake_message[] = { 1, 0, 0, 0, }; QuicConnection::ScopedPacketFlusher flusher(server_connection_); server_stream()->crypto_message_parser()->ProcessInput( absl::string_view(bogus_handshake_message, ABSL_ARRAYSIZE(bogus_handshake_message)), ENCRYPTION_INITIAL); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, ClientSendingBadALPN) { const std::string kTestBadClientAlpn = "bad-client-alpn"; EXPECT_CALL(*client_session_, GetAlpnsToOffer()) .WillOnce(Return(std::vector<std::string>({kTestBadClientAlpn}))); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, static_cast<QuicIetfTransportErrorCodes>( CRYPTO_ERROR_FIRST + 120), "TLS handshake failure (ENCRYPTION_INITIAL) 120: " "no application protocol", _)); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(client_stream()->one_rtt_keys_available()); EXPECT_FALSE(client_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); EXPECT_FALSE(server_stream()->encryption_established()); } TEST_P(TlsServerHandshakerTest, CustomALPNNegotiation) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); const std::string kTestAlpn = "A Custom ALPN Value"; const std::vector<std::string> kTestAlpns( {"foo", "bar", kTestAlpn, "something else"}); EXPECT_CALL(*client_session_, GetAlpnsToOffer()) .WillRepeatedly(Return(kTestAlpns)); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillOnce( [kTestAlpn, kTestAlpns](const std::vector<absl::string_view>& alpns) { EXPECT_THAT(alpns, testing::ElementsAreArray(kTestAlpns)); return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn); }); EXPECT_CALL(*client_session_, OnAlpnSelected(absl::string_view(kTestAlpn))); EXPECT_CALL(*server_session_, OnAlpnSelected(absl::string_view(kTestAlpn))); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, RejectInvalidSNI) { server_id_ = QuicServerId("invalid!.example.com", kServerPort, false); InitializeFakeClient(); static_cast<TlsClientHandshaker*>( QuicCryptoClientStreamPeer::GetHandshaker(client_stream())) ->AllowInvalidSNIForTests(); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, Resumption) { InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_FALSE(server_stream()->ResumptionAttempted()); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_NE(server_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_NE(server_stream()->ResumptionAttempted(), GetParam().disable_resumption); } TEST_P(TlsServerHandshakerTest, ResumptionWithAsyncDecryptCallback) { InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->SetRunCallbacksAsync(true); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); if (GetParam().disable_resumption) { ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 0u); return; } ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u); ticket_crypter_->RunPendingCallback(0); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(client_stream()->IsResumption()); EXPECT_TRUE(server_stream()->IsResumption()); EXPECT_TRUE(server_stream()->ResumptionAttempted()); } TEST_P(TlsServerHandshakerTest, ResumptionWithPlaceholderTicket) { InitializeFakeClient(); ticket_crypter_->set_fail_encrypt(true); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_FALSE(server_stream()->ResumptionAttempted()); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_NE(server_stream()->ResumptionAttempted(), GetParam().disable_resumption); } TEST_P(TlsServerHandshakerTest, AdvanceHandshakeDuringAsyncDecryptCallback) { if (GetParam().disable_resumption) { return; } InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->SetRunCallbacksAsync(true); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSou
282
cpp
google/quiche
quic_crypto_server_stream
quiche/quic/core/quic_crypto_server_stream.cc
quiche/quic/core/quic_crypto_server_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CRYPTO_SERVER_STREAM_H_ #define QUICHE_QUIC_CORE_QUIC_CRYPTO_SERVER_STREAM_H_ #include <string> #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/proto/source_address_token_proto.h" #include "quiche/quic/core/quic_crypto_handshaker.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicCryptoServerStreamPeer; } class QUICHE_EXPORT QuicCryptoServerStream : public QuicCryptoServerStreamBase, public QuicCryptoHandshaker { public: QuicCryptoServerStream(const QuicCryptoServerStream&) = delete; QuicCryptoServerStream& operator=(const QuicCryptoServerStream&) = delete; ~QuicCryptoServerStream() override; void CancelOutstandingCallbacks() override; bool GetBase64SHA256ClientChannelID(std::string* output) const override; void SendServerConfigUpdate( const CachedNetworkParameters* cached_network_params) override; bool DisableResumption() override; bool IsZeroRtt() const override; bool IsResumption() const override; bool ResumptionAttempted() const override; bool EarlyDataAttempted() const override; int NumServerConfigUpdateMessagesSent() const override; const CachedNetworkParameters* PreviousCachedNetworkParams() const override; void SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) override; void OnPacketDecrypted(EncryptionLevel level) override; void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) override {} void OnHandshakeDoneReceived() override; void OnNewTokenReceived(absl::string_view token) override; std::string GetAddressToken( const CachedNetworkParameters* ) const override; bool ValidateAddressToken(absl::string_view token) const override; bool ShouldSendExpectCTHeader() const override; bool DidCertMatchSni() const override; const ProofSource::Details* ProofSourceDetails() const override; ssl_early_data_reason_t EarlyDataReason() const override; bool encryption_established() const override; bool one_rtt_keys_available() const override; const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override; CryptoMessageParser* crypto_message_parser() override; HandshakeState GetHandshakeState() const override; void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> state) override; size_t BufferSizeLimitForLevel(EncryptionLevel level) const override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; SSL* GetSsl() const override; bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override; EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override; protected: QUICHE_EXPORT friend std::unique_ptr<QuicCryptoServerStreamBase> CreateCryptoServerStream(const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSession* session, QuicCryptoServerStreamBase::Helper* helper); QuicCryptoServerStream(const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSession* session, QuicCryptoServerStreamBase::Helper* helper); virtual void ProcessClientHello( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> proof_source_details, std::shared_ptr<ProcessClientHelloResultCallback> done_cb); virtual void OverrideQuicConfigDefaults(QuicConfig* config); virtual const QuicSocketAddress GetClientAddress(); QuicSession* session() const { return session_; } void set_encryption_established(bool encryption_established) { encryption_established_ = encryption_established; } void set_one_rtt_keys_available(bool one_rtt_keys_available) { one_rtt_keys_available_ = one_rtt_keys_available; } private: friend class test::QuicCryptoServerStreamPeer; class QUICHE_EXPORT ValidateCallback : public ValidateClientHelloResultCallback { public: explicit ValidateCallback(QuicCryptoServerStream* parent); ValidateCallback(const ValidateCallback&) = delete; ValidateCallback& operator=(const ValidateCallback&) = delete; void Cancel(); void Run(quiche::QuicheReferenceCountedPointer<Result> result, std::unique_ptr<ProofSource::Details> details) override; private: QuicCryptoServerStream* parent_; }; class SendServerConfigUpdateCallback : public BuildServerConfigUpdateMessageResultCallback { public: explicit SendServerConfigUpdateCallback(QuicCryptoServerStream* parent); SendServerConfigUpdateCallback(const SendServerConfigUpdateCallback&) = delete; void operator=(const SendServerConfigUpdateCallback&) = delete; void Cancel(); void Run(bool ok, const CryptoHandshakeMessage& message) override; private: QuicCryptoServerStream* parent_; }; void FinishProcessingHandshakeMessage( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> details); class ProcessClientHelloCallback; friend class ProcessClientHelloCallback; void FinishProcessingHandshakeMessageAfterProcessClientHello( const ValidateClientHelloResultCallback::Result& result, QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> reply, std::unique_ptr<DiversificationNonce> diversification_nonce, std::unique_ptr<ProofSource::Details> proof_source_details); void FinishSendServerConfigUpdate(bool ok, const CryptoHandshakeMessage& message); QuicTransportVersion transport_version() const { return session_->transport_version(); } QuicSession* session_; HandshakerDelegateInterface* delegate_; const QuicCryptoServerConfig* crypto_config_; QuicCompressedCertsCache* compressed_certs_cache_; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; std::string chlo_hash_; QuicCryptoServerStreamBase::Helper* helper_; uint8_t num_handshake_messages_; uint8_t num_handshake_messages_with_server_nonces_; SendServerConfigUpdateCallback* send_server_config_update_cb_; int num_server_config_update_messages_sent_; std::unique_ptr<CachedNetworkParameters> previous_cached_network_params_; SourceAddressTokens previous_source_address_tokens_; bool zero_rtt_attempted_; QuicByteCount chlo_packet_size_; ValidateCallback* validate_client_hello_cb_; std::weak_ptr<ProcessClientHelloCallback> process_client_hello_cb_; std::unique_ptr<ProofSource::Details> proof_source_details_; bool encryption_established_; bool one_rtt_keys_available_; bool one_rtt_packet_decrypted_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> crypto_negotiated_params_; }; } #endif #include "quiche/quic/core/quic_crypto_server_stream.h" #include <memory> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "openssl/sha.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_testvalue.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_text_utils.h" namespace quic { class QuicCryptoServerStream::ProcessClientHelloCallback : public ProcessClientHelloResultCallback { public: ProcessClientHelloCallback( QuicCryptoServerStream* parent, const quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result>& result) : parent_(parent), result_(result) {} void Run( QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> diversification_nonce, std::unique_ptr<ProofSource::Details> proof_source_details) override { if (parent_ == nullptr) { return; } parent_->FinishProcessingHandshakeMessageAfterProcessClientHello( *result_, error, error_details, std::move(message), std::move(diversification_nonce), std::move(proof_source_details)); } void Cancel() { parent_ = nullptr; } private: QuicCryptoServerStream* parent_; quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result_; }; QuicCryptoServerStream::QuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSession* session, QuicCryptoServerStreamBase::Helper* helper) : QuicCryptoServerStreamBase(session), QuicCryptoHandshaker(this, session), session_(session), delegate_(session), crypto_config_(crypto_config), compressed_certs_cache_(compressed_certs_cache), signed_config_(new QuicSignedServerConfig), helper_(helper), num_handshake_messages_(0), num_handshake_messages_with_server_nonces_(0), send_server_config_update_cb_(nullptr), num_server_config_update_messages_sent_(0), zero_rtt_attempted_(false), chlo_packet_size_(0), validate_client_hello_cb_(nullptr), encryption_established_(false), one_rtt_keys_available_(false), one_rtt_packet_decrypted_(false), crypto_negotiated_params_(new QuicCryptoNegotiatedParameters) {} QuicCryptoServerStream::~QuicCryptoServerStream() { CancelOutstandingCallbacks(); } void QuicCryptoServerStream::CancelOutstandingCallbacks() { if (validate_client_hello_cb_ != nullptr) { validate_client_hello_cb_->Cancel(); validate_client_hello_cb_ = nullptr; } if (send_server_config_update_cb_ != nullptr) { send_server_config_update_cb_->Cancel(); send_server_config_update_cb_ = nullptr; } if (std::shared_ptr<ProcessClientHelloCallback> cb = process_client_hello_cb_.lock()) { cb->Cancel(); process_client_hello_cb_.reset(); } } void QuicCryptoServerStream::OnHandshakeMessage( const CryptoHandshakeMessage& message) { QuicCryptoHandshaker::OnHandshakeMessage(message); ++num_handshake_messages_; chlo_packet_size_ = session()->connection()->GetCurrentPacket().length(); if (one_rtt_keys_available_) { OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, "Unexpected handshake message from client"); return; } if (message.tag() != kCHLO) { OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, "Handshake packet not CHLO"); return; } if (validate_client_hello_cb_ != nullptr || !process_client_hello_cb_.expired()) { OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO, "Unexpected handshake message while processing CHLO"); return; } chlo_hash_ = CryptoUtils::HashHandshakeMessage(message, Perspective::IS_SERVER); std::unique_ptr<ValidateCallback> cb(new ValidateCallback(this)); QUICHE_DCHECK(validate_client_hello_cb_ == nullptr); QUICHE_DCHECK(process_client_hello_cb_.expired()); validate_client_hello_cb_ = cb.get(); crypto_config_->ValidateClientHello( message, GetClientAddress(), session()->connection()->self_address(), transport_version(), session()->connection()->clock(), signed_config_, std::move(cb)); } void QuicCryptoServerStream::FinishProcessingHandshakeMessage( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> details) { QUICHE_DCHECK(validate_client_hello_cb_ != nullptr); QUICHE_DCHECK(process_client_hello_cb_.expired()); validate_client_hello_cb_ = nullptr; auto cb = std::make_shared<ProcessClientHelloCallback>(this, result); process_client_hello_cb_ = cb; ProcessClientHello(result, std::move(details), std::move(cb)); } void QuicCryptoServerStream:: FinishProcessingHandshakeMessageAfterProcessClientHello( const ValidateClientHelloResultCallback::Result& result, QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> reply, std::unique_ptr<DiversificationNonce> diversification_nonce, std::unique_ptr<ProofSource::Details> proof_source_details) { QUICHE_DCHECK(!process_client_hello_cb_.expired()); QUICHE_DCHECK(validate_client_hello_cb_ == nullptr); process_client_hello_cb_.reset(); proof_source_details_ = std::move(proof_source_details); AdjustTestValue("quic::QuicCryptoServerStream::after_process_client_hello", session()); if (!session()->connection()->connected()) { QUIC_CODE_COUNT(quic_crypto_disconnected_after_process_client_hello); QUIC_LOG_FIRST_N(INFO, 10) << "After processing CHLO, QUIC connection has been closed with code " << session()->error() << ", details: " << session()->error_details(); return; } const CryptoHandshakeMessage& message = result.client_hello; if (error != QUIC_NO_ERROR) { OnUnrecoverableError(error, error_details); return; } if (reply->tag() != kSHLO) { session()->connection()->set_fully_pad_crypto_handshake_packets( crypto_config_->pad_rej()); SendHandshakeMessage(*reply, ENCRYPTION_INITIAL); return; } QuicConfig* config = session()->config(); OverrideQuicConfigDefaults(config); std::string process_error_details; const QuicErrorCode process_error = config->ProcessPeerHello(message, CLIENT, &process_error_details); if (process_error != QUIC_NO_ERROR) { OnUnrecoverableError(process_error, process_error_details); return; } session()->OnConfigNegotiated(); config->ToHandshakeMessage(reply.get(), session()->transport_version()); delegate_->OnNewEncryptionKeyAvailable( ENCRYPTION_ZERO_RTT, std::move(crypto_negotiated_params_->initial_crypters.encrypter)); delegate_->OnNewDecryptionKeyAvailable( ENCRYPTION_ZERO_RTT, std::move(crypto_negotiated_params_->initial_crypters.decrypter), false, false); delegate_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); delegate_->DiscardOldDecryptionKey(ENCRYPTION_INITIAL); session()->connection()->SetDiversificationNonce(*diversification_nonce); session()->connection()->set_fully_pad_crypto_handshake_packets( crypto_config_->pad_shlo()); SendHandshakeMessage(*reply, ENCRYPTION_ZERO_RTT); delegate_->OnNewEncryptionKeyAvailable( ENCRYPTION_FORWARD_SECURE, std::move(crypto_negotiated_params_->forward_secure_crypters.encrypter)); delegate_->OnNewDecryptionKeyAvailable( ENCRYPTION_FORWARD_SECURE, std::move(crypto_negotiated_params_->forward_secure_crypters.decrypter), true, false); encryption_established_ = true; one_rtt_keys_available_ = true; delegate_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); delegate_->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); } void QuicCryptoServerStream::SendServerConfigUpdate( const CachedNetworkParameters* cached_network_params) { if (!one_rtt_keys_available_) { return; } if (send_server_config_update_cb_ != nullptr) { QUIC_DVLOG(1) << "Skipped server config update since one is already in progress"; return; } std::unique_ptr<SendServerConfigUpdateCallback> cb( new SendServerConfigUpdateCallback(this)); send_server_config_update_cb_ = cb.get(); crypto_config_->BuildServerConfigUpdateMessage( session()->transport_version(), chlo_hash_, previous_source_address_tokens_, session()->connection()->self_address(), GetClientAddress(), session()->connection()->clock(), session()->connection()->random_generator(), compressed_certs_cache_, *crypto_negotiated_params_, cached_network_params, std::move(cb)); } QuicCryptoServerStream::SendServerConfigUpdateCallback:: SendServerConfigUpdateCallback(QuicCryptoServerStream* parent) : parent_(parent) {} void QuicCryptoServerStream::SendServerConfigUpdateCallback::Cancel() { parent_ = nullptr; } void QuicCryptoServerStream::SendServerConfigUpdateCallback::Run( bool ok, const CryptoHandshakeMessage& message) { if (parent_ == nullptr) { return; } parent_->FinishSendServerConfigUpdate(ok, message); } void QuicCryptoServerStream::FinishSendServerConfigUpdate( bool ok, const CryptoHandshakeMessage& message) { QUICHE_DCHECK(send_server_config_update_cb_ != nullptr); send_server_config_update_cb_ = nullptr; if (!ok) { QUIC_DVLOG(1) << "Server: Failed to build server config update (SCUP)!"; return; } QUIC_DVLOG(1) << "Server: Sending server config update: " << message.DebugString(); SendHandshakeMessage(message, ENCRYPTION_FORWARD_SECURE); ++num_server_config_update_messages_sent_; } bool QuicCryptoServerStream::DisableResumption() { QUICHE_DCHECK(false) << "Not supported for QUIC crypto."; return false; } bool QuicCryptoServerStream::IsZeroRtt() const { return num_handshake_messages_ == 1 && num_handshake_messages_with_server_nonces_ == 0; } bool QuicCryptoServerStream::IsResumption() const { return IsZeroRtt(); } int QuicCryptoServerStream::NumServerConfigUpdateMessagesSent() const { return num_server_config_update_messages_sent_; } const CachedNetworkParameters* QuicCryptoServerStream::PreviousCachedNetworkParams() const { return previous_cached_network_params_.get(); } bool QuicCryptoServerStream::ResumptionAttempted() const { return zero_rtt_attempted_; } bool QuicCryptoServerStream::EarlyDataAttempted() const { QUICHE_DCHECK(false) << "Not supported for QUIC crypto."; return zero_rtt_attempted_; } void QuicCryptoServerStream::SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) { previous_cached_network_params_.reset( new CachedNetworkParameters(cached_network_params)); } void QuicCryptoServerStream::OnPacketDecrypted(EncryptionLevel level) { if (level == ENCRYPTION_FORWARD_SECURE) { one_rtt_packet_decrypted_ = true; delegate_->NeuterHandshakeData(); } } void QuicCryptoServerStream::OnHandshakeDoneReceived() { QUICHE_DCHECK(false); } void QuicCryptoServerStream::OnNewTokenReceived(absl::string_view ) { QUICHE_DCHECK(false); } std::string QuicCryptoServerStream::GetAddressToken( const CachedNetworkParameters* ) const { QUICHE_DCHECK(false); return ""; } bool QuicCryptoServerStream::ValidateAddressToken( absl::string_view ) const { QUICHE_DCHECK(false); return false; } bool QuicCryptoServerStream::ShouldSendExpectCTHeader() const { return signed_config_->proof.send_expect_ct_header; } bool QuicCryptoServerStream::DidCertMatchSni() const { return signed_config_->proof.cert_matched_sni; } const ProofSource::Details* QuicCryptoServerStream::ProofSourceDetails() const { return proof_source_details_.get(); } bool QuicCryptoServerStream::GetBase64SHA256ClientChannelID( std::string* output) const { if (!encryption_established() || crypto_negotiated_params_->channel_id.empty()) { return false; } const std::string& channel_id(crypto_negotiated_params_->channel_id); uint8_t digest[SHA256_DIGEST_LENGTH]; SHA256(reinterpret_cast<const uint8_t*>(channel_id.data()), channel_id.size(), digest); quiche::QuicheTextUtils::Base64Encode(digest, ABSL_ARRAYSIZE(digest), output); return true; } ssl_early_data_reason_t QuicCryptoServerStream::EarlyDataReason() const { if (IsZeroRtt()) { return ssl_early_data_accepted; } if (zero_rtt_attempted_) { return ssl_early_data_session_not_resumed; } return ssl_early_data_no_session_offered; } bool QuicCryptoServerStream::encryption_established() const { return encryption_established_; } bool QuicCryptoServerStream::one_rtt_keys_available() const { return one_rtt_keys_available_; } const QuicCryptoNegotiatedParameters& QuicCryptoServerStream::crypto_negotiated_params() const { return *crypto_negotiated_params_; } CryptoMessageParser* QuicCryptoServerStream::crypto_message_parser() { return QuicCryptoHandshaker::crypto_message_parser(); } HandshakeState QuicCryptoServerStream::GetHandshakeState() const { return one_rtt_packet_decrypted_ ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void QuicCryptoServerStream::SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) { } size_t QuicCryptoServerStream::BufferSizeLimitForLevel( EncryptionLevel level) const { return QuicCryptoHandshaker::BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> QuicCryptoServerStream::AdvanceKeysAndCreateCurrentOneRttDecrypter() { QUICHE_DCHECK(false); return nullptr; } std::unique_ptr<QuicEncrypter> QuicCryptoServerStream::CreateCurrentOneRttEncrypter() { QUICHE_DCHECK(false); return nullptr; } void QuicCryptoServerStream::ProcessClientHello( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> proof_source_details, std::shared_ptr<ProcessClientHelloResultCallback> done_cb) { proof_source_details_ = std::move(proof_source_details); const CryptoHandshakeMessage& message = result->client_hello; std::string error_details; if (!helper_->CanAcceptClientHello( message, GetClientAddress(), session()->connection()->peer_address(), session()->connection()->self_address(), &error_details)) { done_cb->Run(QUIC_HANDSHAKE_FAILED, error_details, nullptr, nullptr, nullptr); return; } absl::string_view user_agent_id; message.GetStringPiece(quic::kUAID, &user_agent_id); if (!session()->user_agent_id().has_value() && !user_agent_id.empty()) { session()->SetUserAgentId(std::string(user_agent_id)); } if (!result->info.server_nonce.empty()) { ++num_handshake_messages_with_server_nonces_; } if (num_handshake_messages_ == 1) { absl::string_view public_value; zero_rtt_attempted_ = message.GetStringPiece(kPUBS, &public_value); } if (result->cached_network_params.bandwidth_estimate_bytes_per_second() > 0) { previous_cached_network_params_.reset( new CachedNetworkParameters(result->cached_network_params)); } previous_source_address_tokens_ = result->info.source_address_tokens; QuicConnection* connection = session()->connection(); crypto_config_->ProcessClientHello( result, false, connection->connection_id(), connection->self_address(), GetClientAddress(), connection->version(), session()->supported_versions(), connection->clock(), connection->random_generator(), compressed_certs_cache_, crypto_negotiated_params_, signed_config_, QuicCryptoStream::CryptoMessageFramingOverhead( transport_version(), connection->connection_id()), chlo_packet_size_, std::move(done_cb)); } void QuicCryptoServerStream::OverrideQuicConfigDefaults( QuicConfig* ) {} QuicCryptoServerStream::ValidateCallback::ValidateCallback( QuicCryptoServerStream* parent) : parent_(parent) {} void QuicCryptoServerStream::ValidateCallback::Cancel() { parent_ = nullptr; } void QuicCryptoServerStream::ValidateCallback::Run( quiche::QuicheReferenceCountedPointer<Result> result, std::unique_ptr<ProofSource::Details> details) { if (parent_ != nullptr) { parent_->FinishProcessingHandshakeMessage(std::move(result), std::move(details)); } } const QuicSocketAddress QuicCryptoServerStream::GetClientAddress() { return session()->connection()->peer_address(); } SSL* QuicCryptoServerStream::GetSsl() const { return nullptr; } bool QuicCryptoServerStream::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel ) const { return true; } EncryptionLevel QuicCryptoServerStream::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { if (space == INITIAL_DATA) { return ENCRYPTION_INITIAL; } if (space == APPLICATION_DATA) { return ENCRYPTION_ZERO_RTT; } QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } }
#include <algorithm> #include <map> #include <memory> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/failing_proof_source.h" #include "quiche/quic/test_tools/fake_proof_source.h" #include "quiche/quic/test_tools/quic_crypto_server_config_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { class QuicConnection; class QuicStream; } using testing::_; using testing::NiceMock; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kServerPort = 443; class QuicCryptoServerStreamTest : public QuicTest { public: QuicCryptoServerStreamTest() : QuicCryptoServerStreamTest(crypto_test_utils::ProofSourceForTesting()) { } explicit QuicCryptoServerStreamTest(std::unique_ptr<ProofSource> proof_source) : server_crypto_config_( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), server_compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), server_id_(kServerHostname, kServerPort, false), client_crypto_config_(crypto_test_utils::ProofVerifierForTesting()) {} void Initialize() { InitializeServer(); } ~QuicCryptoServerStreamTest() override { server_session_.reset(); client_session_.reset(); helpers_.clear(); alarm_factories_.clear(); } void InitializeServer() { TestQuicSpdyServerSession* server_session = nullptr; helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateServerSessionForTest( server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_, helpers_.back().get(), alarm_factories_.back().get(), &server_crypto_config_, &server_compressed_certs_cache_, &server_connection_, &server_session); QUICHE_CHECK(server_session); server_session_.reset(server_session); EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .Times(testing::AnyNumber()); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillRepeatedly([this](const std::vector<absl::string_view>& alpns) { return std::find( alpns.cbegin(), alpns.cend(), AlpnForVersion(server_session_->connection()->version())); }); crypto_test_utils::SetupCryptoServerConfigForTest( server_connection_->clock(), server_connection_->random_generator(), &server_crypto_config_); } QuicCryptoServerStreamBase* server_stream() { return server_session_->GetMutableCryptoStream(); } QuicCryptoClientStream* client_stream() { return client_session_->GetMutableCryptoStream(); } void InitializeFakeClient() { TestQuicSpdyClientSession* client_session = nullptr; helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateClientSessionForTest( server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_, helpers_.back().get(), alarm_factories_.back().get(), &client_crypto_config_, &client_connection_, &client_session); QUICHE_CHECK(client_session); client_session_.reset(client_session); } int CompleteCryptoHandshake() { QUICHE_CHECK(server_connection_); QUICHE_CHECK(server_session_ != nullptr); return crypto_test_utils::HandshakeWithFakeClient( helpers_.back().get(), alarm_factories_.back().get(), server_connection_, server_stream(), server_id_, client_options_, ""); } void AdvanceHandshakeWithFakeClient() { QUICHE_CHECK(server_connection_); QUICHE_CHECK(client_session_ != nullptr); EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber()); EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*server_connection_, OnCanWrite()).Times(testing::AnyNumber()); client_stream()->CryptoConnect(); crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0, server_connection_, server_stream(), 0); } protected: std::vector<std::unique_ptr<MockQuicConnectionHelper>> helpers_; std::vector<std::unique_ptr<MockAlarmFactory>> alarm_factories_; PacketSavingConnection* server_connection_; std::unique_ptr<TestQuicSpdyServerSession> server_session_; QuicCryptoServerConfig server_crypto_config_; QuicCompressedCertsCache server_compressed_certs_cache_; QuicServerId server_id_; PacketSavingConnection* client_connection_; QuicCryptoClientConfig client_crypto_config_; std::unique_ptr<TestQuicSpdyClientSession> client_session_; CryptoHandshakeMessage message_; crypto_test_utils::FakeClientOptions client_options_; ParsedQuicVersionVector supported_versions_ = AllSupportedVersionsWithQuicCrypto(); }; TEST_F(QuicCryptoServerStreamTest, NotInitiallyConected) { Initialize(); EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_F(QuicCryptoServerStreamTest, ConnectedAfterCHLO) { Initialize(); EXPECT_EQ(2, CompleteCryptoHandshake()); EXPECT_TRUE(server_stream()->encryption_established()); EXPECT_TRUE(server_stream()->one_rtt_keys_available()); } TEST_F(QuicCryptoServerStreamTest, ForwardSecureAfterCHLO) { Initialize(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); if (GetQuicReloadableFlag(quic_require_handshake_confirmation)) { crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0, server_connection_, server_stream(), 0); } EXPECT_TRUE(server_stream()->encryption_established()); EXPECT_TRUE(server_stream()->one_rtt_keys_available()); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, server_session_->connection()->encryption_level()); } TEST_F(QuicCryptoServerStreamTest, ZeroRTT) { Initialize(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_stream()->ResumptionAttempted()); QUIC_LOG(INFO) << "Resetting for 0-RTT handshake attempt"; InitializeFakeClient(); InitializeServer(); EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber()); EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber()); client_stream()->CryptoConnect(); EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber()); EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber()); crypto_test_utils::CommunicateHandshakeMessages( client_connection_, client_stream(), server_connection_, server_stream()); EXPECT_EQ( (GetQuicReloadableFlag(quic_require_handshake_confirmation) ? 2 : 1), client_stream()->num_sent_client_hellos()); EXPECT_TRUE(server_stream()->ResumptionAttempted()); } TEST_F(QuicCryptoServerStreamTest, FailByPolicy) { Initialize(); InitializeFakeClient(); EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .WillOnce(testing::Return(false)); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _)); AdvanceHandshakeWithFakeClient(); } TEST_F(QuicCryptoServerStreamTest, MessageAfterHandshake) { Initialize(); CompleteCryptoHandshake(); EXPECT_CALL( *server_connection_, CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, _, _)); message_.set_tag(kCHLO); crypto_test_utils::SendHandshakeMessageToStream(server_stream(), message_, Perspective::IS_CLIENT); } TEST_F(QuicCryptoServerStreamTest, BadMessageType) { Initialize(); message_.set_tag(kSHLO); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, _, _)); crypto_test_utils::SendHandshakeMessageToStream(server_stream(), message_, Perspective::IS_SERVER); } TEST_F(QuicCryptoServerStreamTest, OnlySendSCUPAfterHandshakeComplete) { Initialize(); server_stream()->SendServerConfigUpdate(nullptr); EXPECT_EQ(0, server_stream()->NumServerConfigUpdateMessagesSent()); } TEST_F(QuicCryptoServerStreamTest, SendSCUPAfterHandshakeComplete) { Initialize(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); if (GetQuicReloadableFlag(quic_require_handshake_confirmation)) { crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0, server_connection_, server_stream(), 0); } EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); server_stream()->SendServerConfigUpdate(nullptr); crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 1, server_connection_, server_stream(), 1); EXPECT_EQ(1, server_stream()->NumServerConfigUpdateMessagesSent()); EXPECT_EQ(1, client_stream()->num_scup_messages_received()); } class QuicCryptoServerStreamTestWithFailingProofSource : public QuicCryptoServerStreamTest { public: QuicCryptoServerStreamTestWithFailingProofSource() : QuicCryptoServerStreamTest( std::unique_ptr<FailingProofSource>(new FailingProofSource)) {} }; TEST_F(QuicCryptoServerStreamTestWithFailingProofSource, Test) { Initialize(); InitializeFakeClient(); EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .WillOnce(testing::Return(true)); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, "Failed to get proof", _)); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } class QuicCryptoServerStreamTestWithFakeProofSource : public QuicCryptoServerStreamTest { public: QuicCryptoServerStreamTestWithFakeProofSource() : QuicCryptoServerStreamTest( std::unique_ptr<FakeProofSource>(new FakeProofSource)), crypto_config_peer_(&server_crypto_config_) {} FakeProofSource* GetFakeProofSource() const { return static_cast<FakeProofSource*>(crypto_config_peer_.GetProofSource()); } protected: QuicCryptoServerConfigPeer crypto_config_peer_; }; TEST_F(QuicCryptoServerStreamTestWithFakeProofSource, MultipleChlo) { Initialize(); GetFakeProofSource()->Activate(); EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _)) .WillOnce(testing::Return(true)); QuicTransportVersion transport_version = QUIC_VERSION_UNSUPPORTED; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { transport_version = version.transport_version; break; } } ASSERT_NE(QUIC_VERSION_UNSUPPORTED, transport_version); MockClock clock; CryptoHandshakeMessage chlo = crypto_test_utils::GenerateDefaultInchoateCHLO( &clock, transport_version, &server_crypto_config_); crypto_test_utils::SendHandshakeMessageToStream(server_stream(), chlo, Perspective::IS_CLIENT); EXPECT_EQ(GetFakeProofSource()->NumPendingCallbacks(), 1); EXPECT_CALL( *server_connection_, CloseConnection(QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO, "Unexpected handshake message while processing CHLO", _)); crypto_test_utils::SendHandshakeMessageToStream(server_stream(), chlo, Perspective::IS_CLIENT); } } } }
283
cpp
google/quiche
quic_config
quiche/quic/core/quic_config.cc
quiche/quic/core/quic_config_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_CONFIG_H_ #define QUICHE_QUIC_CORE_QUIC_CONFIG_H_ #include <cstddef> #include <cstdint> #include <optional> #include <string> #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicConfigPeer; } class CryptoHandshakeMessage; enum QuicConfigPresence : uint8_t { PRESENCE_OPTIONAL, PRESENCE_REQUIRED, }; enum HelloType { CLIENT, SERVER, }; class QUICHE_EXPORT QuicConfigValue { public: QuicConfigValue(QuicTag tag, QuicConfigPresence presence); virtual ~QuicConfigValue(); virtual void ToHandshakeMessage(CryptoHandshakeMessage* out) const = 0; virtual QuicErrorCode ProcessPeerHello( const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) = 0; protected: const QuicTag tag_; const QuicConfigPresence presence_; }; class QUICHE_EXPORT QuicFixedUint32 : public QuicConfigValue { public: QuicFixedUint32(QuicTag tag, QuicConfigPresence presence); ~QuicFixedUint32() override; bool HasSendValue() const; uint32_t GetSendValue() const; void SetSendValue(uint32_t value); bool HasReceivedValue() const; uint32_t GetReceivedValue() const; void SetReceivedValue(uint32_t value); void ToHandshakeMessage(CryptoHandshakeMessage* out) const override; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) override; private: bool has_send_value_; bool has_receive_value_; uint32_t send_value_; uint32_t receive_value_; }; class QUICHE_EXPORT QuicFixedUint62 : public QuicConfigValue { public: QuicFixedUint62(QuicTag name, QuicConfigPresence presence); ~QuicFixedUint62() override; bool HasSendValue() const; uint64_t GetSendValue() const; void SetSendValue(uint64_t value); bool HasReceivedValue() const; uint64_t GetReceivedValue() const; void SetReceivedValue(uint64_t value); void ToHandshakeMessage(CryptoHandshakeMessage* out) const override; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) override; private: bool has_send_value_; bool has_receive_value_; uint64_t send_value_; uint64_t receive_value_; }; class QUICHE_EXPORT QuicFixedStatelessResetToken : public QuicConfigValue { public: QuicFixedStatelessResetToken(QuicTag tag, QuicConfigPresence presence); ~QuicFixedStatelessResetToken() override; bool HasSendValue() const; const StatelessResetToken& GetSendValue() const; void SetSendValue(const StatelessResetToken& value); bool HasReceivedValue() const; const StatelessResetToken& GetReceivedValue() const; void SetReceivedValue(const StatelessResetToken& value); void ToHandshakeMessage(CryptoHandshakeMessage* out) const override; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) override; private: bool has_send_value_; bool has_receive_value_; StatelessResetToken send_value_; StatelessResetToken receive_value_; }; class QUICHE_EXPORT QuicFixedTagVector : public QuicConfigValue { public: QuicFixedTagVector(QuicTag name, QuicConfigPresence presence); QuicFixedTagVector(const QuicFixedTagVector& other); ~QuicFixedTagVector() override; bool HasSendValues() const; const QuicTagVector& GetSendValues() const; void SetSendValues(const QuicTagVector& values); bool HasReceivedValues() const; const QuicTagVector& GetReceivedValues() const; void SetReceivedValues(const QuicTagVector& values); void ToHandshakeMessage(CryptoHandshakeMessage* out) const override; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) override; private: bool has_send_values_; bool has_receive_values_; QuicTagVector send_values_; QuicTagVector receive_values_; }; class QUICHE_EXPORT QuicFixedSocketAddress : public QuicConfigValue { public: QuicFixedSocketAddress(QuicTag tag, QuicConfigPresence presence); ~QuicFixedSocketAddress() override; bool HasSendValue() const; const QuicSocketAddress& GetSendValue() const; void SetSendValue(const QuicSocketAddress& value); void ClearSendValue(); bool HasReceivedValue() const; const QuicSocketAddress& GetReceivedValue() const; void SetReceivedValue(const QuicSocketAddress& value); void ToHandshakeMessage(CryptoHandshakeMessage* out) const override; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details) override; private: bool has_send_value_; bool has_receive_value_; QuicSocketAddress send_value_; QuicSocketAddress receive_value_; }; class QUICHE_EXPORT QuicConfig { public: QuicConfig(); QuicConfig(const QuicConfig& other); ~QuicConfig(); void SetConnectionOptionsToSend(const QuicTagVector& connection_options); bool HasReceivedConnectionOptions() const; void SetGoogleHandshakeMessageToSend(std::string message); const std::optional<std::string>& GetReceivedGoogleHandshakeMessage() const; bool SetInitialReceivedConnectionOptions(const QuicTagVector& tags); const QuicTagVector& ReceivedConnectionOptions() const; bool HasSendConnectionOptions() const; const QuicTagVector& SendConnectionOptions() const; bool HasClientSentConnectionOption(QuicTag tag, Perspective perspective) const; void SetClientConnectionOptions( const QuicTagVector& client_connection_options); bool HasClientRequestedIndependentOption(QuicTag tag, Perspective perspective) const; const QuicTagVector& ClientRequestedIndependentOptions( Perspective perspective) const; void SetIdleNetworkTimeout(QuicTime::Delta idle_network_timeout); QuicTime::Delta IdleNetworkTimeout() const; void SetMaxBidirectionalStreamsToSend(uint32_t max_streams); uint32_t GetMaxBidirectionalStreamsToSend() const; bool HasReceivedMaxBidirectionalStreams() const; uint32_t ReceivedMaxBidirectionalStreams() const; void SetMaxUnidirectionalStreamsToSend(uint32_t max_streams); uint32_t GetMaxUnidirectionalStreamsToSend() const; bool HasReceivedMaxUnidirectionalStreams() const; uint32_t ReceivedMaxUnidirectionalStreams() const; void set_max_time_before_crypto_handshake( QuicTime::Delta max_time_before_crypto_handshake) { max_time_before_crypto_handshake_ = max_time_before_crypto_handshake; } QuicTime::Delta max_time_before_crypto_handshake() const { return max_time_before_crypto_handshake_; } void set_max_idle_time_before_crypto_handshake( QuicTime::Delta max_idle_time_before_crypto_handshake) { max_idle_time_before_crypto_handshake_ = max_idle_time_before_crypto_handshake; } QuicTime::Delta max_idle_time_before_crypto_handshake() const { return max_idle_time_before_crypto_handshake_; } void set_max_undecryptable_packets(size_t max_undecryptable_packets) { max_undecryptable_packets_ = max_undecryptable_packets; } size_t max_undecryptable_packets() const { return max_undecryptable_packets_; } bool HasSetBytesForConnectionIdToSend() const; void SetBytesForConnectionIdToSend(uint32_t bytes); bool HasReceivedBytesForConnectionId() const; uint32_t ReceivedBytesForConnectionId() const; void SetInitialRoundTripTimeUsToSend(uint64_t rtt_us); bool HasReceivedInitialRoundTripTimeUs() const; uint64_t ReceivedInitialRoundTripTimeUs() const; bool HasInitialRoundTripTimeUsToSend() const; uint64_t GetInitialRoundTripTimeUsToSend() const; void SetInitialStreamFlowControlWindowToSend(uint64_t window_bytes); uint64_t GetInitialStreamFlowControlWindowToSend() const; bool HasReceivedInitialStreamFlowControlWindowBytes() const; uint64_t ReceivedInitialStreamFlowControlWindowBytes() const; void SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( uint64_t window_bytes); uint64_t GetInitialMaxStreamDataBytesIncomingBidirectionalToSend() const; bool HasReceivedInitialMaxStreamDataBytesIncomingBidirectional() const; uint64_t ReceivedInitialMaxStreamDataBytesIncomingBidirectional() const; void SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend( uint64_t window_bytes); uint64_t GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend() const; bool HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional() const; uint64_t ReceivedInitialMaxStreamDataBytesOutgoingBidirectional() const; void SetInitialMaxStreamDataBytesUnidirectionalToSend(uint64_t window_bytes); uint64_t GetInitialMaxStreamDataBytesUnidirectionalToSend() const; bool HasReceivedInitialMaxStreamDataBytesUnidirectional() const; uint64_t ReceivedInitialMaxStreamDataBytesUnidirectional() const; void SetInitialSessionFlowControlWindowToSend(uint64_t window_bytes); uint64_t GetInitialSessionFlowControlWindowToSend() const; bool HasReceivedInitialSessionFlowControlWindowBytes() const; uint64_t ReceivedInitialSessionFlowControlWindowBytes() const; void SetDisableConnectionMigration(); bool DisableConnectionMigration() const; void SetIPv6AlternateServerAddressToSend( const QuicSocketAddress& alternate_server_address_ipv6); bool HasReceivedIPv6AlternateServerAddress() const; const QuicSocketAddress& ReceivedIPv6AlternateServerAddress() const; void SetIPv4AlternateServerAddressToSend( const QuicSocketAddress& alternate_server_address_ipv4); bool HasReceivedIPv4AlternateServerAddress() const; const QuicSocketAddress& ReceivedIPv4AlternateServerAddress() const; void SetPreferredAddressConnectionIdAndTokenToSend( const QuicConnectionId& connection_id, const StatelessResetToken& stateless_reset_token); bool HasReceivedPreferredAddressConnectionIdAndToken() const; const std::pair<QuicConnectionId, StatelessResetToken>& ReceivedPreferredAddressConnectionIdAndToken() const; std::optional<QuicSocketAddress> GetPreferredAddressToSend( quiche::IpAddressFamily address_family) const; void ClearAlternateServerAddressToSend( quiche::IpAddressFamily address_family); void SetIPv4AlternateServerAddressForDNat( const QuicSocketAddress& alternate_server_address_ipv4_to_send, const QuicSocketAddress& mapped_alternate_server_address_ipv4); void SetIPv6AlternateServerAddressForDNat( const QuicSocketAddress& alternate_server_address_ipv6_to_send, const QuicSocketAddress& mapped_alternate_server_address_ipv6); std::optional<QuicSocketAddress> GetMappedAlternativeServerAddress( quiche::IpAddressFamily address_family) const; bool SupportsServerPreferredAddress(Perspective perspective) const; void SetOriginalConnectionIdToSend( const QuicConnectionId& original_destination_connection_id); bool HasReceivedOriginalConnectionId() const; QuicConnectionId ReceivedOriginalConnectionId() const; void SetStatelessResetTokenToSend( const StatelessResetToken& stateless_reset_token); bool HasStatelessResetTokenToSend() const; bool HasReceivedStatelessResetToken() const; const StatelessResetToken& ReceivedStatelessResetToken() const; void SetMaxAckDelayToSendMs(uint32_t max_ack_delay_ms); uint32_t GetMaxAckDelayToSendMs() const; bool HasReceivedMaxAckDelayMs() const; uint32_t ReceivedMaxAckDelayMs() const; void SetMinAckDelayMs(uint32_t min_ack_delay_ms); uint32_t GetMinAckDelayToSendMs() const; bool HasReceivedMinAckDelayMs() const; uint32_t ReceivedMinAckDelayMs() const; void SetAckDelayExponentToSend(uint32_t exponent); uint32_t GetAckDelayExponentToSend() const; bool HasReceivedAckDelayExponent() const; uint32_t ReceivedAckDelayExponent() const; void SetMaxPacketSizeToSend(uint64_t max_udp_payload_size); uint64_t GetMaxPacketSizeToSend() const; bool HasReceivedMaxPacketSize() const; uint64_t ReceivedMaxPacketSize() const; void SetMaxDatagramFrameSizeToSend(uint64_t max_datagram_frame_size); uint64_t GetMaxDatagramFrameSizeToSend() const; bool HasReceivedMaxDatagramFrameSize() const; uint64_t ReceivedMaxDatagramFrameSize() const; void SetActiveConnectionIdLimitToSend(uint64_t active_connection_id_limit); uint64_t GetActiveConnectionIdLimitToSend() const; bool HasReceivedActiveConnectionIdLimit() const; uint64_t ReceivedActiveConnectionIdLimit() const; void SetInitialSourceConnectionIdToSend( const QuicConnectionId& initial_source_connection_id); bool HasReceivedInitialSourceConnectionId() const; QuicConnectionId ReceivedInitialSourceConnectionId() const; void SetRetrySourceConnectionIdToSend( const QuicConnectionId& retry_source_connection_id); bool HasReceivedRetrySourceConnectionId() const; QuicConnectionId ReceivedRetrySourceConnectionId() const; bool negotiated() const; void SetCreateSessionTagIndicators(QuicTagVector tags); const QuicTagVector& create_session_tag_indicators() const; void ToHandshakeMessage(CryptoHandshakeMessage* out, QuicTransportVersion transport_version) const; QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello, HelloType hello_type, std::string* error_details); bool FillTransportParameters(TransportParameters* params) const; QuicErrorCode ProcessTransportParameters(const TransportParameters& params, bool is_resumption, std::string* error_details); TransportParameters::ParameterMap& custom_transport_parameters_to_send() { return custom_transport_parameters_to_send_; } const TransportParameters::ParameterMap& received_custom_transport_parameters() const { return received_custom_transport_parameters_; } void ClearGoogleHandshakeMessage(); private: friend class test::QuicConfigPeer; void SetDefaults(); bool negotiated_; QuicTime::Delta max_time_before_crypto_handshake_; QuicTime::Delta max_idle_time_before_crypto_handshake_; size_t max_undecryptable_packets_; QuicFixedTagVector connection_options_; QuicFixedTagVector client_connection_options_; QuicTime::Delta max_idle_timeout_to_send_; std::optional<QuicTime::Delta> received_max_idle_timeout_; QuicFixedUint32 max_bidirectional_streams_; QuicFixedUint32 max_unidirectional_streams_; QuicFixedUint32 bytes_for_connection_id_; QuicFixedUint62 initial_round_trip_time_us_; QuicFixedUint62 initial_max_stream_data_bytes_incoming_bidirectional_; QuicFixedUint62 initial_max_stream_data_bytes_outgoing_bidirectional_; QuicFixedUint62 initial_max_stream_data_bytes_unidirectional_; QuicFixedUint62 initial_stream_flow_control_window_bytes_; QuicFixedUint62 initial_session_flow_control_window_bytes_; QuicFixedUint32 connection_migration_disabled_; QuicFixedSocketAddress alternate_server_address_ipv6_; QuicFixedSocketAddress alternate_server_address_ipv4_; std::optional<QuicSocketAddress> mapped_alternate_server_address_ipv6_; std::optional<QuicSocketAddress> mapped_alternate_server_address_ipv4_; std::optional<std::pair<QuicConnectionId, StatelessResetToken>> preferred_address_connection_id_and_token_; QuicFixedStatelessResetToken stateless_reset_token_; QuicTagVector create_session_tag_indicators_; QuicFixedUint32 max_ack_delay_ms_; QuicFixedUint32 min_ack_delay_ms_; QuicFixedUint32 ack_delay_exponent_; QuicFixedUint62 max_udp_payload_size_; QuicFixedUint62 max_datagram_frame_size_; QuicFixedUint62 active_connection_id_limit_; std::optional<QuicConnectionId> original_destination_connection_id_to_send_; std::optional<QuicConnectionId> received_original_destination_connection_id_; std::optional<QuicConnectionId> initial_source_connection_id_to_send_; std::optional<QuicConnectionId> received_initial_source_connection_id_; std::optional<QuicConnectionId> retry_source_connection_id_to_send_; std::optional<QuicConnectionId> received_retry_source_connection_id_; TransportParameters::ParameterMap custom_transport_parameters_to_send_; TransportParameters::ParameterMap received_custom_transport_parameters_; std::optional<std::string> google_handshake_message_to_send_; std::optional<std::string> received_google_handshake_message_; }; } #endif #include "quiche/quic/core/quic_config.h" #include <algorithm> #include <cstring> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_socket_address_coder.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { QuicErrorCode ReadUint32(const CryptoHandshakeMessage& msg, QuicTag tag, QuicConfigPresence presence, uint32_t default_value, uint32_t* out, std::string* error_details) { QUICHE_DCHECK(error_details != nullptr); QuicErrorCode error = msg.GetUint32(tag, out); switch (error) { case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND: if (presence == PRESENCE_REQUIRED) { *error_details = "Missing " + QuicTagToString(tag); break; } error = QUIC_NO_ERROR; *out = default_value; break; case QUIC_NO_ERROR: break; default: *error_details = "Bad " + QuicTagToString(tag); break; } return error; } QuicConfigValue::QuicConfigValue(QuicTag tag, QuicConfigPresence presence) : tag_(tag), presence_(presence) {} QuicConfigValue::~QuicConfigValue() {} QuicFixedUint32::QuicFixedUint32(QuicTag tag, QuicConfigPresence presence) : QuicConfigValue(tag, presence), has_send_value_(false), has_receive_value_(false) {} QuicFixedUint32::~QuicFixedUint32() {} bool QuicFixedUint32::HasSendValue() const { return has_send_value_; } uint32_t QuicFixedUint32::GetSendValue() const { QUIC_BUG_IF(quic_bug_12743_1, !has_send_value_) << "No send value to get for tag:" << QuicTagToString(tag_); return send_value_; } void QuicFixedUint32::SetSendValue(uint32_t value) { has_send_value_ = true; send_value_ = value; } bool QuicFixedUint32::HasReceivedValue() const { return has_receive_value_; } uint32_t QuicFixedUint32::GetReceivedValue() const { QUIC_BUG_IF(quic_bug_12743_2, !has_receive_value_) << "No receive value to get for tag:" << QuicTagToString(tag_); return receive_value_; } void QuicFixedUint32::SetReceivedValue(uint32_t value) { has_receive_value_ = true; receive_value_ = value; } void QuicFixedUint32::ToHandshakeMessage(CryptoHandshakeMessage* out) const { if (tag_ == 0) { QUIC_BUG(quic_b
#include "quiche/quic/core/quic_config.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class QuicConfigTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicConfigTest() : version_(GetParam()) {} protected: ParsedQuicVersion version_; QuicConfig config_; }; INSTANTIATE_TEST_SUITE_P(QuicConfigTests, QuicConfigTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicConfigTest, SetDefaults) { EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialStreamFlowControlWindowToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesUnidirectionalToSend()); EXPECT_FALSE(config_.HasReceivedInitialStreamFlowControlWindowBytes()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()); EXPECT_EQ(kMaxIncomingPacketSize, config_.GetMaxPacketSizeToSend()); EXPECT_FALSE(config_.HasReceivedMaxPacketSize()); } TEST_P(QuicConfigTest, AutoSetIetfFlowControl) { EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialStreamFlowControlWindowToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend()); EXPECT_EQ(kMinimumFlowControlSendWindow, config_.GetInitialMaxStreamDataBytesUnidirectionalToSend()); static const uint32_t kTestWindowSize = 1234567; config_.SetInitialStreamFlowControlWindowToSend(kTestWindowSize); EXPECT_EQ(kTestWindowSize, config_.GetInitialStreamFlowControlWindowToSend()); EXPECT_EQ(kTestWindowSize, config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend()); EXPECT_EQ(kTestWindowSize, config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend()); EXPECT_EQ(kTestWindowSize, config_.GetInitialMaxStreamDataBytesUnidirectionalToSend()); static const uint32_t kTestWindowSizeTwo = 2345678; config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( kTestWindowSizeTwo); EXPECT_EQ(kTestWindowSize, config_.GetInitialStreamFlowControlWindowToSend()); EXPECT_EQ(kTestWindowSizeTwo, config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend()); EXPECT_EQ(kTestWindowSize, config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend()); EXPECT_EQ(kTestWindowSize, config_.GetInitialMaxStreamDataBytesUnidirectionalToSend()); } TEST_P(QuicConfigTest, ToHandshakeMessage) { if (version_.UsesTls()) { return; } config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); config_.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(5)); CryptoHandshakeMessage msg; config_.ToHandshakeMessage(&msg, version_.transport_version); uint32_t value; QuicErrorCode error = msg.GetUint32(kICSL, &value); EXPECT_THAT(error, IsQuicNoError()); EXPECT_EQ(5u, value); error = msg.GetUint32(kSFCW, &value); EXPECT_THAT(error, IsQuicNoError()); EXPECT_EQ(kInitialStreamFlowControlWindowForTest, value); error = msg.GetUint32(kCFCW, &value); EXPECT_THAT(error, IsQuicNoError()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, value); } TEST_P(QuicConfigTest, ProcessClientHello) { if (version_.UsesTls()) { return; } const uint32_t kTestMaxAckDelayMs = static_cast<uint32_t>(GetDefaultDelayedAckTimeMs() + 1); QuicConfig client_config; QuicTagVector cgst; cgst.push_back(kQBIC); client_config.SetIdleNetworkTimeout( QuicTime::Delta::FromSeconds(2 * kMaximumIdleTimeoutSecs)); client_config.SetInitialRoundTripTimeUsToSend(10 * kNumMicrosPerMilli); client_config.SetInitialStreamFlowControlWindowToSend( 2 * kInitialStreamFlowControlWindowForTest); client_config.SetInitialSessionFlowControlWindowToSend( 2 * kInitialSessionFlowControlWindowForTest); QuicTagVector copt; copt.push_back(kTBBR); client_config.SetConnectionOptionsToSend(copt); client_config.SetMaxAckDelayToSendMs(kTestMaxAckDelayMs); CryptoHandshakeMessage msg; client_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; QuicTagVector initial_received_options; initial_received_options.push_back(kIW50); EXPECT_TRUE( config_.SetInitialReceivedConnectionOptions(initial_received_options)); EXPECT_FALSE( config_.SetInitialReceivedConnectionOptions(initial_received_options)) << "You can only set initial options once."; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_FALSE( config_.SetInitialReceivedConnectionOptions(initial_received_options)) << "You cannot set initial options after the hello."; EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs), config_.IdleNetworkTimeout()); EXPECT_EQ(10 * kNumMicrosPerMilli, config_.ReceivedInitialRoundTripTimeUs()); EXPECT_TRUE(config_.HasReceivedConnectionOptions()); EXPECT_EQ(2u, config_.ReceivedConnectionOptions().size()); EXPECT_EQ(config_.ReceivedConnectionOptions()[0], kIW50); EXPECT_EQ(config_.ReceivedConnectionOptions()[1], kTBBR); EXPECT_EQ(config_.ReceivedInitialStreamFlowControlWindowBytes(), 2 * kInitialStreamFlowControlWindowForTest); EXPECT_EQ(config_.ReceivedInitialSessionFlowControlWindowBytes(), 2 * kInitialSessionFlowControlWindowForTest); EXPECT_TRUE(config_.HasReceivedMaxAckDelayMs()); EXPECT_EQ(kTestMaxAckDelayMs, config_.ReceivedMaxAckDelayMs()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()); } TEST_P(QuicConfigTest, ProcessServerHello) { if (version_.UsesTls()) { return; } QuicIpAddress host; host.FromString("127.0.3.1"); const QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234); const StatelessResetToken kTestStatelessResetToken{ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}; const uint32_t kTestMaxAckDelayMs = static_cast<uint32_t>(GetDefaultDelayedAckTimeMs() + 1); QuicConfig server_config; QuicTagVector cgst; cgst.push_back(kQBIC); server_config.SetIdleNetworkTimeout( QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs / 2)); server_config.SetInitialRoundTripTimeUsToSend(10 * kNumMicrosPerMilli); server_config.SetInitialStreamFlowControlWindowToSend( 2 * kInitialStreamFlowControlWindowForTest); server_config.SetInitialSessionFlowControlWindowToSend( 2 * kInitialSessionFlowControlWindowForTest); server_config.SetIPv4AlternateServerAddressToSend(kTestServerAddress); server_config.SetStatelessResetTokenToSend(kTestStatelessResetToken); server_config.SetMaxAckDelayToSendMs(kTestMaxAckDelayMs); CryptoHandshakeMessage msg; server_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, SERVER, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs / 2), config_.IdleNetworkTimeout()); EXPECT_EQ(10 * kNumMicrosPerMilli, config_.ReceivedInitialRoundTripTimeUs()); EXPECT_EQ(config_.ReceivedInitialStreamFlowControlWindowBytes(), 2 * kInitialStreamFlowControlWindowForTest); EXPECT_EQ(config_.ReceivedInitialSessionFlowControlWindowBytes(), 2 * kInitialSessionFlowControlWindowForTest); EXPECT_TRUE(config_.HasReceivedIPv4AlternateServerAddress()); EXPECT_EQ(kTestServerAddress, config_.ReceivedIPv4AlternateServerAddress()); EXPECT_FALSE(config_.HasReceivedIPv6AlternateServerAddress()); EXPECT_TRUE(config_.HasReceivedStatelessResetToken()); EXPECT_EQ(kTestStatelessResetToken, config_.ReceivedStatelessResetToken()); EXPECT_TRUE(config_.HasReceivedMaxAckDelayMs()); EXPECT_EQ(kTestMaxAckDelayMs, config_.ReceivedMaxAckDelayMs()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()); EXPECT_FALSE( config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()); } TEST_P(QuicConfigTest, MissingOptionalValuesInCHLO) { if (version_.UsesTls()) { return; } CryptoHandshakeMessage msg; msg.SetValue(kICSL, 1); msg.SetValue(kICSL, 1); msg.SetValue(kMIBS, 1); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); } TEST_P(QuicConfigTest, MissingOptionalValuesInSHLO) { if (version_.UsesTls()) { return; } CryptoHandshakeMessage msg; msg.SetValue(kICSL, 1); msg.SetValue(kMIBS, 1); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, SERVER, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); } TEST_P(QuicConfigTest, MissingValueInCHLO) { if (version_.UsesTls()) { return; } CryptoHandshakeMessage msg; std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsError(QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND)); } TEST_P(QuicConfigTest, MissingValueInSHLO) { if (version_.UsesTls()) { return; } CryptoHandshakeMessage msg; std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, SERVER, &error_details); EXPECT_THAT(error, IsError(QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND)); } TEST_P(QuicConfigTest, OutOfBoundSHLO) { if (version_.UsesTls()) { return; } QuicConfig server_config; server_config.SetIdleNetworkTimeout( QuicTime::Delta::FromSeconds(2 * kMaximumIdleTimeoutSecs)); CryptoHandshakeMessage msg; server_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, SERVER, &error_details); EXPECT_THAT(error, IsError(QUIC_INVALID_NEGOTIATED_VALUE)); } TEST_P(QuicConfigTest, InvalidFlowControlWindow) { QuicConfig config; const uint64_t kInvalidWindow = kMinimumFlowControlSendWindow - 1; EXPECT_QUIC_BUG( config.SetInitialStreamFlowControlWindowToSend(kInvalidWindow), "Initial stream flow control receive window"); EXPECT_EQ(kMinimumFlowControlSendWindow, config.GetInitialStreamFlowControlWindowToSend()); } TEST_P(QuicConfigTest, HasClientSentConnectionOption) { if (version_.UsesTls()) { return; } QuicConfig client_config; QuicTagVector copt; copt.push_back(kTBBR); client_config.SetConnectionOptionsToSend(copt); EXPECT_TRUE(client_config.HasClientSentConnectionOption( kTBBR, Perspective::IS_CLIENT)); CryptoHandshakeMessage msg; client_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); EXPECT_TRUE(config_.HasReceivedConnectionOptions()); EXPECT_EQ(1u, config_.ReceivedConnectionOptions().size()); EXPECT_TRUE( config_.HasClientSentConnectionOption(kTBBR, Perspective::IS_SERVER)); } TEST_P(QuicConfigTest, DontSendClientConnectionOptions) { if (version_.UsesTls()) { return; } QuicConfig client_config; QuicTagVector copt; copt.push_back(kTBBR); client_config.SetClientConnectionOptions(copt); CryptoHandshakeMessage msg; client_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); EXPECT_FALSE(config_.HasReceivedConnectionOptions()); } TEST_P(QuicConfigTest, HasClientRequestedIndependentOption) { if (version_.UsesTls()) { return; } QuicConfig client_config; QuicTagVector client_opt; client_opt.push_back(kRENO); QuicTagVector copt; copt.push_back(kTBBR); client_config.SetClientConnectionOptions(client_opt); client_config.SetConnectionOptionsToSend(copt); EXPECT_TRUE(client_config.HasClientSentConnectionOption( kTBBR, Perspective::IS_CLIENT)); EXPECT_TRUE(client_config.HasClientRequestedIndependentOption( kRENO, Perspective::IS_CLIENT)); EXPECT_FALSE(client_config.HasClientRequestedIndependentOption( kTBBR, Perspective::IS_CLIENT)); CryptoHandshakeMessage msg; client_config.ToHandshakeMessage(&msg, version_.transport_version); std::string error_details; const QuicErrorCode error = config_.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); EXPECT_TRUE(config_.negotiated()); EXPECT_TRUE(config_.HasReceivedConnectionOptions()); EXPECT_EQ(1u, config_.ReceivedConnectionOptions().size()); EXPECT_FALSE(config_.HasClientRequestedIndependentOption( kRENO, Perspective::IS_SERVER)); EXPECT_TRUE(config_.HasClientRequestedIndependentOption( kTBBR, Perspective::IS_SERVER)); } TEST_P(QuicConfigTest, IncomingLargeIdleTimeoutTransportParameter) { if (!version_.UsesTls()) { return; } config_.SetIdleNetworkTimeout(quic::QuicTime::Delta::FromSeconds(60)); TransportParameters params; params.max_idle_timeout_ms.set_value(120000); std::string error_details = "foobar"; EXPECT_THAT(config_.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); EXPECT_EQ("", error_details); EXPECT_EQ(quic::QuicTime::Delta::FromSeconds(60), config_.IdleNetworkTimeout()); } TEST_P(QuicConfigTest, ReceivedInvalidMinAckDelayInTransportParameter) { if (!version_.UsesTls()) { return; } TransportParameters params; params.max_ack_delay.set_value(25 ); params.min_ack_delay_us.set_value(25 * kNumMicrosPerMilli + 1); std::string error_details = "foobar"; EXPECT_THAT(config_.ProcessTransportParameters( params, false, &error_details), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ("MinAckDelay is greater than MaxAckDelay.", error_details); params.max_ack_delay.set_value(25 ); params.min_ack_delay_us.set_value(25 * kNumMicrosPerMilli); EXPECT_THAT(config_.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); EXPECT_TRUE(error_details.empty()); } TEST_P(QuicConfigTest, FillTransportParams) { if (!version_.UsesTls()) { return; } const std::string kFakeGoogleHandshakeMessage = "Fake handshake message"; config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( 2 * kMinimumFlowControlSendWindow); config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend( 3 * kMinimumFlowControlSendWindow); config_.SetInitialMaxStreamDataBytesUnidirectionalToSend( 4 * kMinimumFlowControlSendWindow); config_.SetMaxPacketSizeToSend(kMaxPacketSizeForTest); config_.SetMaxDatagramFrameSizeToSend(kMaxDatagramFrameSizeForTest); config_.SetActiveConnectionIdLimitToSend(kActiveConnectionIdLimitForTest); config_.SetOriginalConnectionIdToSend(TestConnectionId(0x1111)); config_.SetInitialSourceConnectionIdToSend(TestConnectionId(0x2222)); config_.SetRetrySourceConnectionIdToSend(TestConnectionId(0x3333)); config_.SetMinAckDelayMs(kDefaultMinAckDelayTimeMs); config_.SetGoogleHandshakeMessageToSend(kFakeGoogleHandshakeMessage); QuicIpAddress host; host.FromString("127.0.3.1"); QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234); QuicConnectionId new_connection_id = TestConnectionId(5); StatelessResetToken new_stateless_reset_token = QuicUtils::GenerateStatelessResetToken(new_connection_id); config_.SetIPv4AlternateServerAddressToSend(kTestServerAddress); QuicSocketAddress kTestServerAddressV6 = QuicSocketAddress(QuicIpAddress::Any6(), 1234); config_.SetIPv6AlternateServerAddressToSend(kTestServerAddressV6); config_.SetPreferredAddressConnectionIdAndTokenToSend( new_connection_id, new_stateless_reset_token); config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V6); EXPECT_TRUE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4) .has_value()); EXPECT_FALSE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6) .has_value()); TransportParameters params; config_.FillTransportParameters(&params); EXPECT_EQ(2 * kMinimumFlowControlSendWindow, params.initial_max_stream_data_bidi_remote.value()); EXPECT_EQ(3 * kMinimumFlowControlSendWindow, params.initial_max_stream_data_bidi_local.value()); EXPECT_EQ(4 * kMinimumFlowControlSendWindow, params.initial_max_stream_data_uni.value()); EXPECT_EQ(static_cast<uint64_t>(kMaximumIdleTimeoutSecs * 1000), params.max_idle_timeout_ms.value()); EXPECT_EQ(kMaxPacketSizeForTest, params.max_udp_payload_size.value()); EXPECT_EQ(kMaxDatagramFrameSizeForTest, params.max_datagram_frame_size.value()); EXPECT_EQ(kActiveConnectionIdLimitForTest, params.active_connection_id_limit.value()); ASSERT_TRUE(params.original_destination_connection_id.has_value()); EXPECT_EQ(TestConnectionId(0x1111), params.original_destination_connection_id.value()); ASSERT_TRUE(params.initial_source_connection_id.has_value()); EXPECT_EQ(TestConnectionId(0x2222), params.initial_source_connection_id.value()); ASSERT_TRUE(params.retry_source_connection_id.has_value()); EXPECT_EQ(TestConnectionId(0x3333), params.retry_source_connection_id.value()); EXPECT_EQ( static_cast<uint64_t>(kDefaultMinAckDelayTimeMs) * kNumMicrosPerMilli, params.min_ack_delay_us.value()); EXPECT_EQ(params.preferred_address->ipv4_socket_address, kTestServerAddress); EXPECT_EQ(params.preferred_address->ipv6_socket_address, QuicSocketAddress(QuicIpAddress::Any6(), 0)); EXPECT_EQ(*reinterpret_cast<StatelessResetToken*>( &params.preferred_address->stateless_reset_token.front()), new_stateless_reset_token); EXPECT_EQ(kFakeGoogleHandshakeMessage, params.google_handshake_message); } TEST_P(QuicConfigTest, DNATPreferredAddress) { QuicIpAddress host_v4; host_v4.FromString("127.0.3.1"); QuicSocketAddress server_address_v4 = QuicSocketAddress(host_v4, 1234); QuicSocketAddress expected_server_address_v4 = QuicSocketAddress(host_v4, 1235); QuicIpAddress host_v6; host_v6.FromString("2001:db8:0::1"); QuicSocketAddress server_address_v6 = QuicSocketAddress(host_v6, 1234); QuicSocketAddress expected_server_address_v6 = QuicSocketAddress(host_v6, 1235); config_.SetIPv4AlternateServerAddressForDNat(server_address_v4, expected_server_address_v4); config_.SetIPv6AlternateServerAddressForDNat(server_address_v6, expected_server_address_v6); EXPECT_EQ(server_address_v4, config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)); EXPECT_EQ(server_address_v6, config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6)); EXPECT_EQ(expected_server_address_v4, config_.GetMappedAlternativeServerAddress( quiche::IpAddressFamily::IP_V4)); EXPECT_EQ(expected_server_address_v6, config_.GetMappedAlternativeServerAddress( quiche::IpAddressFamily::IP_V6)); } TEST_P(QuicConfigTest, FillTransportParamsNoV4PreferredAddress) { if (!version_.UsesTls()) { return; } QuicIpAddress host; host.FromString("127.0.3.1"); QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234); QuicConnectionId new_connection_id = TestConnectionId(5); StatelessResetToken new_stateless_reset_token = QuicUtils::GenerateStatelessResetToken(new_connection_id); config_.SetIPv4AlternateServerAddressToSend(kTestServerAddress); QuicSocketAddress kTestServerAddressV6 = QuicSocketAddress(QuicIpAddress::Any6(), 1234); config_.SetIPv6AlternateServerAddressToSend(kTestServerAddressV6); config_.SetPreferredAddressConnectionIdAndTokenToSend( new_connection_id, new_stateless_reset_token); config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V4); EXPECT_FALSE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4) .has_value()); config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V4); TransportParameters params; config_.FillTransportParameters(&params); EXPECT_EQ(params.preferred_address->ipv4_socket_address, QuicSocketAddress(QuicIpAddress::Any4(), 0)); EXPECT_EQ(params.preferred_address->ipv6_socket_address, kTestServerAddressV6); } TEST_P(QuicConfigTest, SupportsServerPreferredAddress) { SetQuicFlag(quic_always_support_server_preferred_address, true); EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT)); EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER)); SetQuicFlag(quic_always_support_server_preferred_address, false); EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT)); EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER)); QuicTagVector copt; copt.push_back(kSPAD); config_.SetConnectionOptionsToSend(copt); EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT)); EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER)); config_.SetInitialReceivedConnectionOptions(copt); EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT)); EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER)); } TEST_P(QuicConfigTest, ProcessTransportParametersServer) { if (!version_.UsesTls()) { return; } const std::string kFakeGoogleHandshakeMessage = "Fake handshake message"; TransportParameters params; params.initial_max_stream_data_bidi_local.set_value( 2 * kMinimumFlowControlSendWindow); params.initial_max_stream_data_bidi_remote.set_value( 3 * kMinimumFlowControlSendWindow); params.initial_max_stream_data_uni.set_value(4 * kMinimumFlowControlSendWindow); params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); params.max_datagram_frame_size.set_value(kMaxDatagramFrameSizeForTest); params.initial_max_streams_bidi.set_value(kDefaultMaxStreamsPerConnection); params.stateless_reset_token = CreateStatelessResetTokenForTest(); params.max_ack_delay.set_value(kMaxAckDelayForTest); params.min_ack_delay_us.set_value(kMinAckDelayUsForTest); params.ack_delay_exponent.set_value(kAckDelayExponentForTest); params.active_connection_id_limit.set_value(kActiveConnectionIdLimitForTest); params.original_destination_connection_id = TestConnectionId(0x1111); params.initial_source_connection_id = TestConnectionId(0x2222); params.retry_source_connection_id = TestConnectionId(0x3333); params.google_handshake_message = kFakeGoogleHandshakeMessage; std::string error_details; EXPECT_THAT(config_.ProcessTransportParameters( params, true, &error_details), IsQuicNoError()) << error_details; EXPECT_FALSE(config_.negotiated()); ASSERT_TRUE( config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()); EXPECT_EQ(2 * kMinimumFlowControlSendWindow, config_.ReceivedInitialMaxStreamDataBytesIncomingBidirectional()); ASSERT_TRUE( config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); EXPECT_EQ(3 * kMinimumFlowControlSendWindow, config_.ReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); ASSERT_TRUE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()); EXPECT_EQ(4 * kMinimumFlowControlSendWindow, config_.ReceivedInitialMaxStreamDataBytesUnidirectional()); ASSERT_TRUE(config_.HasReceivedMaxPacketSize()); EXPECT_EQ(kMaxPacketSizeForTest, config_.ReceivedMaxPacketSize()); ASSERT_TRUE(config_.HasReceivedMaxDatagramFrameSize()); EXPECT_EQ(kMaxDatagramFrameSizeForTest, config_.ReceivedMaxDatagramFrameSize()); ASSERT_TRUE(config_.HasReceivedMaxBidirectionalStreams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, config_.ReceivedMaxBidirectionalStreams()); EXPECT_FALSE(config_.DisableConnectionMigration()); EXPECT_FALSE(config_.HasReceivedStatelessResetToken()); EXPECT_FALSE(config_.HasReceivedMaxAckDelayMs()); EXPECT_FALSE(config_.HasReceivedAckDelayExponent()); EXPECT_FALSE(config_.HasReceivedMinAckDelayMs()); EXPECT_FALSE(config_.HasReceivedOriginalConnectionId()); EXPECT_FALSE(config_.HasReceivedInitialSourceConnectionId()); EXPECT_FALSE(config_.HasReceivedRetrySourceConnectionId()); params.initial_max_stream_data_bidi_local.set_value( 2 * kMinimumFlowControlSendWindow + 1); params.initial_max_stream_data_bidi_remote.set_value( 4 * kMinimumFlowControlSendWindow); params.initial_max_stream_data_uni.set_value(5 * kMinimumFlowControlSendWindow); params.max_udp_payload_size.set_value(2 * kMaxPacketSizeForTest); params.max_datagram_frame_size.set_value(2 * kMaxDatagramFrameSizeForTest); params.initial_max_streams_bidi.set_value(2 * kDefaultMaxStreamsPerConnection); params.disable_active_migration = true; EXPECT_THAT(config_.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()) << error_details; EXPECT_TRUE(config_.negotiated()); ASSERT_TRUE( config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()); EXPECT_EQ(2 * kMinimumFlowControlSendWindow + 1, config_.ReceivedInitialMaxStreamDataBytesIncomingBidirectional()); ASSERT_TRUE( config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); EXPECT_EQ(4 * kMinimumFlowControlSendWindow, config_.ReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); ASSERT_TRUE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()); EXPECT_EQ(5 * kMinimumFlowControlSendWindow, config_.ReceivedInitialMaxStreamDataBytesUnidirectional()); ASSERT_TRUE(config_.HasReceivedMaxPacketSize()); EXPECT_EQ(2 * kMaxPacketSizeForTest, config_.ReceivedMaxPacketSize()); ASSERT_TRUE(config_.HasReceivedMaxDatagramFrameSize()); EXPECT_EQ(2 * kMaxDatagramFrameSizeForTest, config_.ReceivedMaxDatagramFrameSize()); ASSERT_TRUE(config_.HasReceivedMaxBidirectionalStreams()); EXPECT_EQ(2 * kDefaultMaxStreamsPerConnection, config_.ReceivedMaxBidirectionalStreams()); EXPECT_TRUE(config_.DisableConnectionMigration()); ASSERT_TRUE(config_.HasReceivedStatelessResetToken()); ASSERT_TRUE(config_.HasReceivedMaxAckDelayMs()); EXPECT_EQ(config_.ReceivedMaxAckDelayMs(), kMaxAckDelayForTest); ASSERT_TRUE(config_.HasReceivedMinAckDelayMs()); EXPECT_EQ(config_.ReceivedMinAckDelayMs(), kMinAckDelayUsForTest / kNumMicrosPerMilli); ASSERT_TRUE(config_.HasReceivedAckDelayExponent()); EXPECT_EQ(config_.ReceivedAckDelayExponent(), kAckDelayExponentForTest); ASSERT_TRUE(config_.HasReceivedActiveConnectionIdLimit()); EXPECT_EQ(config_.ReceivedActiveConnectionIdLimit(), kActiveConnectionIdLimitForTest); ASSERT_TRUE(config_.HasReceivedOriginalConnectionId()); EXPECT_EQ(config_.ReceivedOriginalConnectionId(), TestConnectionId(0x1111)); ASSERT_TRUE(config_.HasReceivedInitialSourceConnectionId()); EXPECT_EQ(config_.ReceivedInitialSourceConnectionId(), TestConnectionId(0x2222)); ASSERT_TRUE(config_.HasReceivedRetrySourceConnectionId()); EXPECT_EQ(config_.ReceivedRetrySourceConnectionId(), TestConnectionId(0x3333)); EXPECT_EQ(kFakeGoogleHandshakeMessage, config_.GetReceivedGoogleHandshakeMessage()); } TEST_P(QuicConfigTest, DisableMigrationTransportParameter) { if (!version_.UsesTls()) { return; } TransportParameters params; params.disable_active_migration = true; std::string error_details; EXPECT_THAT(config_.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); EXPECT_TRUE(config_.DisableConnectionMigration()); } TEST_P(QuicConfigTest, SendPreferredIPv4Address) { if (!version_.UsesTls()) { return; } EXPECT_FALSE(config_.H
284
cpp
google/quiche
quic_socket_address_coder
quiche/quic/core/quic_socket_address_coder.cc
quiche/quic/core/quic_socket_address_coder_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_SOCKET_ADDRESS_CODER_H_ #define QUICHE_QUIC_CORE_QUIC_SOCKET_ADDRESS_CODER_H_ #include <cstdint> #include <string> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { class QUICHE_EXPORT QuicSocketAddressCoder { public: QuicSocketAddressCoder(); explicit QuicSocketAddressCoder(const QuicSocketAddress& address); QuicSocketAddressCoder(const QuicSocketAddressCoder&) = delete; QuicSocketAddressCoder& operator=(const QuicSocketAddressCoder&) = delete; ~QuicSocketAddressCoder(); std::string Encode() const; bool Decode(const char* data, size_t length); QuicIpAddress ip() const { return address_.host(); } uint16_t port() const { return address_.port(); } private: QuicSocketAddress address_; }; } #endif #include "quiche/quic/core/quic_socket_address_coder.h" #include <cstring> #include <string> #include <vector> #include "quiche/quic/platform/api/quic_ip_address_family.h" namespace quic { namespace { const uint16_t kIPv4 = 2; const uint16_t kIPv6 = 10; } QuicSocketAddressCoder::QuicSocketAddressCoder() {} QuicSocketAddressCoder::QuicSocketAddressCoder(const QuicSocketAddress& address) : address_(address) {} QuicSocketAddressCoder::~QuicSocketAddressCoder() {} std::string QuicSocketAddressCoder::Encode() const { std::string serialized; uint16_t address_family; switch (address_.host().address_family()) { case IpAddressFamily::IP_V4: address_family = kIPv4; break; case IpAddressFamily::IP_V6: address_family = kIPv6; break; default: return serialized; } serialized.append(reinterpret_cast<const char*>(&address_family), sizeof(address_family)); serialized.append(address_.host().ToPackedString()); uint16_t port = address_.port(); serialized.append(reinterpret_cast<const char*>(&port), sizeof(port)); return serialized; } bool QuicSocketAddressCoder::Decode(const char* data, size_t length) { uint16_t address_family; if (length < sizeof(address_family)) { return false; } memcpy(&address_family, data, sizeof(address_family)); data += sizeof(address_family); length -= sizeof(address_family); size_t ip_length; switch (address_family) { case kIPv4: ip_length = QuicIpAddress::kIPv4AddressSize; break; case kIPv6: ip_length = QuicIpAddress::kIPv6AddressSize; break; default: return false; } if (length < ip_length) { return false; } std::vector<uint8_t> ip(ip_length); memcpy(&ip[0], data, ip_length); data += ip_length; length -= ip_length; uint16_t port; if (length != sizeof(port)) { return false; } memcpy(&port, data, length); QuicIpAddress ip_address; ip_address.FromPackedString(reinterpret_cast<const char*>(&ip[0]), ip_length); address_ = QuicSocketAddress(ip_address, port); return true; } }
#include "quiche/quic/core/quic_socket_address_coder.h" #include <string> #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QuicSocketAddressCoderTest : public QuicTest {}; TEST_F(QuicSocketAddressCoderTest, EncodeIPv4) { QuicIpAddress ip; ip.FromString("4.31.198.44"); QuicSocketAddressCoder coder(QuicSocketAddress(ip, 0x1234)); std::string serialized = coder.Encode(); std::string expected("\x02\x00\x04\x1f\xc6\x2c\x34\x12", 8); EXPECT_EQ(expected, serialized); } TEST_F(QuicSocketAddressCoderTest, EncodeIPv6) { QuicIpAddress ip; ip.FromString("2001:700:300:1800::f"); QuicSocketAddressCoder coder(QuicSocketAddress(ip, 0x5678)); std::string serialized = coder.Encode(); std::string expected( "\x0a\x00" "\x20\x01\x07\x00\x03\x00\x18\x00" "\x00\x00\x00\x00\x00\x00\x00\x0f" "\x78\x56", 20); EXPECT_EQ(expected, serialized); } TEST_F(QuicSocketAddressCoderTest, DecodeIPv4) { std::string serialized("\x02\x00\x04\x1f\xc6\x2c\x34\x12", 8); QuicSocketAddressCoder coder; ASSERT_TRUE(coder.Decode(serialized.data(), serialized.length())); EXPECT_EQ(IpAddressFamily::IP_V4, coder.ip().address_family()); std::string expected_addr("\x04\x1f\xc6\x2c"); EXPECT_EQ(expected_addr, coder.ip().ToPackedString()); EXPECT_EQ(0x1234, coder.port()); } TEST_F(QuicSocketAddressCoderTest, DecodeIPv6) { std::string serialized( "\x0a\x00" "\x20\x01\x07\x00\x03\x00\x18\x00" "\x00\x00\x00\x00\x00\x00\x00\x0f" "\x78\x56", 20); QuicSocketAddressCoder coder; ASSERT_TRUE(coder.Decode(serialized.data(), serialized.length())); EXPECT_EQ(IpAddressFamily::IP_V6, coder.ip().address_family()); std::string expected_addr( "\x20\x01\x07\x00\x03\x00\x18\x00" "\x00\x00\x00\x00\x00\x00\x00\x0f", 16); EXPECT_EQ(expected_addr, coder.ip().ToPackedString()); EXPECT_EQ(0x5678, coder.port()); } TEST_F(QuicSocketAddressCoderTest, DecodeBad) { std::string serialized( "\x0a\x00" "\x20\x01\x07\x00\x03\x00\x18\x00" "\x00\x00\x00\x00\x00\x00\x00\x0f" "\x78\x56", 20); QuicSocketAddressCoder coder; EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length())); serialized.push_back('\0'); EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length())); serialized.resize(20); EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length())); serialized[0] = '\x03'; EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length())); serialized[0] = '\x0a'; EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length())); size_t len = serialized.length(); for (size_t i = 0; i < len; i++) { ASSERT_FALSE(serialized.empty()); serialized.erase(serialized.length() - 1); EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length())); } EXPECT_TRUE(serialized.empty()); } TEST_F(QuicSocketAddressCoderTest, EncodeAndDecode) { struct { const char* ip_literal; uint16_t port; } test_case[] = { {"93.184.216.119", 0x1234}, {"199.204.44.194", 80}, {"149.20.4.69", 443}, {"127.0.0.1", 8080}, {"2001:700:300:1800::", 0x5678}, {"::1", 65534}, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(test_case); i++) { QuicIpAddress ip; ASSERT_TRUE(ip.FromString(test_case[i].ip_literal)); QuicSocketAddressCoder encoder(QuicSocketAddress(ip, test_case[i].port)); std::string serialized = encoder.Encode(); QuicSocketAddressCoder decoder; ASSERT_TRUE(decoder.Decode(serialized.data(), serialized.length())); EXPECT_EQ(encoder.ip(), decoder.ip()); EXPECT_EQ(encoder.port(), decoder.port()); } } } }
285
cpp
google/quiche
quic_packet_creator
quiche/quic/core/quic_packet_creator.cc
quiche/quic/core/quic_packet_creator_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_ #define QUICHE_QUIC_CORE_QUIC_PACKET_CREATOR_H_ #include <cstddef> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_coalesced_packet.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class QuicPacketCreatorPeer; } class QUICHE_EXPORT QuicPacketCreator { public: class QUICHE_EXPORT DelegateInterface { public: virtual ~DelegateInterface() {} virtual QuicPacketBuffer GetPacketBuffer() = 0; virtual void OnSerializedPacket(SerializedPacket serialized_packet) = 0; virtual void OnUnrecoverableError(QuicErrorCode error, const std::string& error_details) = 0; virtual bool ShouldGeneratePacket(HasRetransmittableData retransmittable, IsHandshake handshake) = 0; virtual void MaybeBundleOpportunistically( TransmissionType transmission_type) = 0; virtual QuicByteCount GetFlowControlSendWindowSize(QuicStreamId id) = 0; virtual SerializedPacketFate GetSerializedPacketFate( bool is_mtu_discovery, EncryptionLevel encryption_level) = 0; }; class QUICHE_EXPORT DebugDelegate { public: virtual ~DebugDelegate() {} virtual void OnFrameAddedToPacket(const QuicFrame& ) {} virtual void OnStreamFrameCoalesced(const QuicStreamFrame& ) {} }; class QUICHE_EXPORT ScopedPeerAddressContext { public: ScopedPeerAddressContext(QuicPacketCreator* creator, QuicSocketAddress address, const QuicConnectionId& client_connection_id, const QuicConnectionId& server_connection_id); ~ScopedPeerAddressContext(); private: QuicPacketCreator* creator_; QuicSocketAddress old_peer_address_; QuicConnectionId old_client_connection_id_; QuicConnectionId old_server_connection_id_; }; QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer, DelegateInterface* delegate); QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer, QuicRandom* random, DelegateInterface* delegate); QuicPacketCreator(const QuicPacketCreator&) = delete; QuicPacketCreator& operator=(const QuicPacketCreator&) = delete; ~QuicPacketCreator(); void SetDiversificationNonce(const DiversificationNonce& nonce); void UpdatePacketNumberLength(QuicPacketNumber least_packet_awaited_by_peer, QuicPacketCount max_packets_in_flight); void SkipNPacketNumbers(QuicPacketCount count, QuicPacketNumber least_packet_awaited_by_peer, QuicPacketCount max_packets_in_flight); static size_t StreamFramePacketOverhead( QuicTransportVersion version, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, bool include_version, bool include_diversification_nonce, QuicPacketNumberLength packet_number_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, quiche::QuicheVariableLengthIntegerLength length_length, QuicStreamOffset offset); bool ConsumeDataToFillCurrentPacket(QuicStreamId id, size_t data_size, QuicStreamOffset offset, bool fin, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame); bool ConsumeCryptoDataToFillCurrentPacket(EncryptionLevel level, size_t write_length, QuicStreamOffset offset, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame); bool HasRoomForStreamFrame(QuicStreamId id, QuicStreamOffset offset, size_t data_size); bool HasRoomForMessageFrame(QuicByteCount length); void FlushCurrentPacket(); void CreateAndSerializeStreamFrame(QuicStreamId id, size_t write_length, QuicStreamOffset iov_offset, QuicStreamOffset stream_offset, bool fin, TransmissionType transmission_type, size_t* num_bytes_consumed); bool HasPendingFrames() const; std::string GetPendingFramesInfo() const; bool HasPendingRetransmittableFrames() const; bool HasPendingStreamFramesOfStream(QuicStreamId id) const; size_t BytesFree() const; size_t BytesFreeForPadding() const; size_t ExpansionOnNewFrame() const; static size_t ExpansionOnNewFrameWithLastFrame(const QuicFrame& last_frame, QuicTransportVersion version); size_t PacketSize() const; bool AddFrame(const QuicFrame& frame, TransmissionType transmission_type); bool AddPaddedSavedFrame(const QuicFrame& frame, TransmissionType transmission_type); std::unique_ptr<SerializedPacket> SerializeConnectivityProbingPacket(); std::unique_ptr<SerializedPacket> SerializePathChallengeConnectivityProbingPacket( const QuicPathFrameBuffer& payload); std::unique_ptr<SerializedPacket> SerializePathResponseConnectivityProbingPacket( const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads, const bool is_padded); bool AddPathResponseFrame(const QuicPathFrameBuffer& data_buffer); void AddPathChallengeFrame(const QuicPathFrameBuffer& payload); static SerializedPacket NoPacket(); const QuicConnectionId& GetServerConnectionId() const { return server_connection_id_; } const QuicConnectionId& GetClientConnectionId() const { return client_connection_id_; } QuicConnectionId GetDestinationConnectionId() const; QuicConnectionId GetSourceConnectionId() const; uint8_t GetDestinationConnectionIdLength() const; uint8_t GetSourceConnectionIdLength() const; void SetServerConnectionIdIncluded( QuicConnectionIdIncluded server_connection_id_included); void SetServerConnectionId(QuicConnectionId server_connection_id); void SetClientConnectionId(QuicConnectionId client_connection_id); void set_encryption_level(EncryptionLevel level); EncryptionLevel encryption_level() { return packet_.encryption_level; } QuicPacketNumber packet_number() const { return packet_.packet_number; } QuicByteCount max_packet_length() const { return max_packet_length_; } bool has_ack() const { return packet_.has_ack; } bool has_stop_waiting() const { return packet_.has_stop_waiting; } void SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter); bool CanSetMaxPacketLength() const; void SetMaxPacketLength(QuicByteCount length); void SetMaxDatagramFrameSize(QuicByteCount max_datagram_frame_size); void SetSoftMaxPacketLength(QuicByteCount length); void AddPendingPadding(QuicByteCount size); void SetRetryToken(absl::string_view retry_token); bool ConsumeRetransmittableControlFrame(const QuicFrame& frame); QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state); QuicConsumedData ConsumeDataFastPath(QuicStreamId id, size_t write_length, QuicStreamOffset offset, bool fin, size_t total_bytes_consumed); size_t ConsumeCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset); void GenerateMtuDiscoveryPacket(QuicByteCount target_mtu); bool FlushAckFrame(const QuicFrames& frames); void AddRandomPadding(); void AttachPacketFlusher(); void Flush(); void SendRemainingPendingPadding(); void SetServerConnectionIdLength(uint32_t length); void SetTransmissionType(TransmissionType type); MessageStatus AddMessageFrame(QuicMessageId message_id, absl::Span<quiche::QuicheMemSlice> message); QuicPacketLength GetCurrentLargestMessagePayload() const; QuicPacketLength GetGuaranteedLargestMessagePayload() const; QuicPacketNumber NextSendingPacketNumber() const; void set_debug_delegate(DebugDelegate* debug_delegate) { debug_delegate_ = debug_delegate; } QuicByteCount pending_padding_bytes() const { return pending_padding_bytes_; } ParsedQuicVersion version() const { return framer_->version(); } QuicTransportVersion transport_version() const { return framer_->transport_version(); } static size_t MinPlaintextPacketSize( const ParsedQuicVersion& version, QuicPacketNumberLength packet_number_length); bool PacketFlusherAttached() const; void set_fully_pad_crypto_handshake_packets(bool new_value) { fully_pad_crypto_handshake_packets_ = new_value; } bool fully_pad_crypto_handshake_packets() const { return fully_pad_crypto_handshake_packets_; } size_t BuildPaddedPathChallengePacket(const QuicPacketHeader& header, char* buffer, size_t packet_length, const QuicPathFrameBuffer& payload, EncryptionLevel level); size_t BuildPathResponsePacket( const QuicPacketHeader& header, char* buffer, size_t packet_length, const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads, const bool is_padded, EncryptionLevel level); size_t BuildConnectivityProbingPacket(const QuicPacketHeader& header, char* buffer, size_t packet_length, EncryptionLevel level); size_t SerializeCoalescedPacket(const QuicCoalescedPacket& coalesced, char* buffer, size_t buffer_len); bool HasSoftMaxPacketLength() const; void SetDefaultPeerAddress(QuicSocketAddress address); bool HasRetryToken() const; const QuicSocketAddress& peer_address() const { return packet_.peer_address; } private: friend class test::QuicPacketCreatorPeer; class QUICHE_EXPORT ScopedSerializationFailureHandler { public: explicit ScopedSerializationFailureHandler(QuicPacketCreator* creator); ~ScopedSerializationFailureHandler(); private: QuicPacketCreator* creator_; }; std::optional<size_t> MaybeBuildDataPacketWithChaosProtection( const QuicPacketHeader& header, char* buffer); void CreateStreamFrame(QuicStreamId id, size_t data_size, QuicStreamOffset offset, bool fin, QuicFrame* frame); bool CreateCryptoFrame(EncryptionLevel level, size_t write_length, QuicStreamOffset offset, QuicFrame* frame); void FillPacketHeader(QuicPacketHeader* header); void MaybeAddPadding(); ABSL_MUST_USE_RESULT bool SerializePacket( QuicOwnedPacketBuffer encrypted_buffer, size_t encrypted_buffer_len, bool allow_padding); void OnSerializedPacket(); void ClearPacket(); size_t ReserializeInitialPacketInCoalescedPacket( const SerializedPacket& packet, size_t padding_size, char* buffer, size_t buffer_len); bool MaybeCoalesceStreamFrame(const QuicStreamFrame& frame); bool RemoveSoftMaxPacketLength(); bool IncludeNonceInPublicHeader() const; bool IncludeVersionInHeader() const; QuicPacketNumberLength GetPacketNumberLength() const; size_t PacketHeaderSize() const; QuicConnectionIdIncluded GetDestinationConnectionIdIncluded() const; QuicConnectionIdIncluded GetSourceConnectionIdIncluded() const; quiche::QuicheVariableLengthIntegerLength GetRetryTokenLengthLength() const; absl::string_view GetRetryToken() const; quiche::QuicheVariableLengthIntegerLength GetLengthLength() const; bool StreamFrameIsClientHello(const QuicStreamFrame& frame) const; bool HasIetfLongHeader() const; size_t GetSerializedFrameLength(const QuicFrame& frame); void MaybeAddExtraPaddingForHeaderProtection(); bool AttemptingToSendUnencryptedStreamData(); bool AddPaddedFrameWithRetry(const QuicFrame& frame); void MaybeBundleOpportunistically(); DelegateInterface* delegate_; DebugDelegate* debug_delegate_; QuicFramer* framer_; QuicRandom* random_; bool have_diversification_nonce_; DiversificationNonce diversification_nonce_; QuicByteCount max_packet_length_; QuicByteCount next_max_packet_length_; size_t max_plaintext_size_; QuicConnectionIdIncluded server_connection_id_included_; QuicFrames queued_frames_; size_t packet_size_; QuicConnectionId server_connection_id_; QuicConnectionId client_connection_id_; SerializedPacket packet_; std::string retry_token_; QuicByteCount pending_padding_bytes_; bool needs_full_padding_; TransmissionType next_transmission_type_; bool flusher_attached_; bool fully_pad_crypto_handshake_packets_; QuicPacketNumber write_start_packet_number_; QuicByteCount latched_hard_max_packet_length_; QuicByteCount max_datagram_frame_size_; }; } #endif #include "quiche/quic/core/quic_packet_creator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_padding_frame.h" #include "quiche/quic/core/frames/quic_path_challenge_frame.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_chaos_protector.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_exported_stats.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_server_stats.h" #include "quiche/common/print_elements.h" namespace quic { namespace { QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: return INITIAL; case ENCRYPTION_HANDSHAKE: return HANDSHAKE; case ENCRYPTION_ZERO_RTT: return ZERO_RTT_PROTECTED; case ENCRYPTION_FORWARD_SECURE: QUIC_BUG(quic_bug_12398_1) << "Try to derive long header type for packet with encryption level: " << level; return INVALID_PACKET_TYPE; default:
#include "quiche/quic/core/quic_packet_creator.h" #include <cstdint> #include <limits> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_packet_creator_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" using ::testing::_; using ::testing::AtLeast; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SaveArg; using ::testing::StrictMock; namespace quic { namespace test { namespace { const QuicPacketNumber kPacketNumber = QuicPacketNumber(UINT64_C(0x12345678)); QuicConnectionId CreateTestConnectionId() { return TestConnectionId(UINT64_C(0xFEDCBA9876543210)); } struct TestParams { TestParams(ParsedQuicVersion version, bool version_serialization) : version(version), version_serialization(version_serialization) {} ParsedQuicVersion version; bool version_serialization; }; std::string PrintToString(const TestParams& p) { return absl::StrCat(ParsedQuicVersionToString(p.version), "_", (p.version_serialization ? "Include" : "No"), "Version"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (size_t i = 0; i < all_supported_versions.size(); ++i) { params.push_back(TestParams(all_supported_versions[i], true)); params.push_back(TestParams(all_supported_versions[i], false)); } return params; } class MockDebugDelegate : public QuicPacketCreator::DebugDelegate { public: ~MockDebugDelegate() override = default; MOCK_METHOD(void, OnFrameAddedToPacket, (const QuicFrame& frame), (override)); MOCK_METHOD(void, OnStreamFrameCoalesced, (const QuicStreamFrame& frame), (override)); }; class TestPacketCreator : public QuicPacketCreator { public: TestPacketCreator(QuicConnectionId connection_id, QuicFramer* framer, DelegateInterface* delegate, SimpleDataProducer* producer) : QuicPacketCreator(connection_id, framer, delegate), producer_(producer), version_(framer->version()) {} bool ConsumeDataToFillCurrentPacket(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, bool fin, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame) { if (!data.empty()) { producer_->SaveStreamData(id, data); } return QuicPacketCreator::ConsumeDataToFillCurrentPacket( id, data.length(), offset, fin, needs_full_padding, transmission_type, frame); } void StopSendingVersion() { set_encryption_level(ENCRYPTION_FORWARD_SECURE); } SimpleDataProducer* producer_; ParsedQuicVersion version_; }; class QuicPacketCreatorTest : public QuicTestWithParam<TestParams> { public: void ClearSerializedPacketForTests(SerializedPacket ) { } void SaveSerializedPacket(SerializedPacket serialized_packet) { serialized_packet_.reset(CopySerializedPacket( serialized_packet, &allocator_, true)); } void DeleteSerializedPacket() { serialized_packet_ = nullptr; } protected: QuicPacketCreatorTest() : connection_id_(TestConnectionId(2)), server_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), Perspective::IS_SERVER, connection_id_.length()), client_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), Perspective::IS_CLIENT, connection_id_.length()), data_("foo"), creator_(connection_id_, &client_framer_, &delegate_, &producer_) { EXPECT_CALL(delegate_, GetPacketBuffer()) .WillRepeatedly(Return(QuicPacketBuffer())); EXPECT_CALL(delegate_, GetSerializedPacketFate(_, _)) .WillRepeatedly(Return(SEND_TO_WRITER)); creator_.SetEncrypter( ENCRYPTION_INITIAL, std::make_unique<TaggingEncrypter>(ENCRYPTION_INITIAL)); creator_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); creator_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); creator_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); client_framer_.set_visitor(&framer_visitor_); server_framer_.set_visitor(&framer_visitor_); client_framer_.set_data_producer(&producer_); if (server_framer_.version().KnowsWhichDecrypterToUse()) { server_framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>()); } else { server_framer_.SetDecrypter(ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>()); server_framer_.SetAlternativeDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>(), false); } } ~QuicPacketCreatorTest() override {} SerializedPacket SerializeAllFrames(const QuicFrames& frames) { SerializedPacket packet = QuicPacketCreatorPeer::SerializeAllFrames( &creator_, frames, buffer_, kMaxOutgoingPacketSize); EXPECT_EQ(QuicPacketCreatorPeer::GetEncryptionLevel(&creator_), packet.encryption_level); return packet; } void ProcessPacket(const SerializedPacket& packet) { QuicEncryptedPacket encrypted_packet(packet.encrypted_buffer, packet.encrypted_length); server_framer_.ProcessPacket(encrypted_packet); } void CheckStreamFrame(const QuicFrame& frame, QuicStreamId stream_id, const std::string& data, QuicStreamOffset offset, bool fin) { EXPECT_EQ(STREAM_FRAME, frame.type); EXPECT_EQ(stream_id, frame.stream_frame.stream_id); char buf[kMaxOutgoingPacketSize]; QuicDataWriter writer(kMaxOutgoingPacketSize, buf, quiche::HOST_BYTE_ORDER); if (frame.stream_frame.data_length > 0) { producer_.WriteStreamData(stream_id, frame.stream_frame.offset, frame.stream_frame.data_length, &writer); } EXPECT_EQ(data, absl::string_view(buf, frame.stream_frame.data_length)); EXPECT_EQ(offset, frame.stream_frame.offset); EXPECT_EQ(fin, frame.stream_frame.fin); } size_t GetPacketHeaderOverhead(QuicTransportVersion version) { return GetPacketHeaderSize( version, creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)); } size_t GetEncryptionOverhead() { return creator_.max_packet_length() - client_framer_.GetMaxPlaintextSize(creator_.max_packet_length()); } size_t GetStreamFrameOverhead(QuicTransportVersion version) { return QuicFramer::GetMinStreamFrameSize( version, GetNthClientInitiatedStreamId(1), kOffset, true, 0); } bool IsDefaultTestConfiguration() { TestParams p = GetParam(); return p.version == AllSupportedVersions()[0] && p.version_serialization; } QuicStreamId GetNthClientInitiatedStreamId(int n) const { return QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT) + n * 2; } void TestChaosProtection(bool enabled); static constexpr QuicStreamOffset kOffset = 0u; char buffer_[kMaxOutgoingPacketSize]; QuicConnectionId connection_id_; QuicFrames frames_; QuicFramer server_framer_; QuicFramer client_framer_; StrictMock<MockFramerVisitor> framer_visitor_; StrictMock<MockPacketCreatorDelegate> delegate_; std::string data_; TestPacketCreator creator_; std::unique_ptr<SerializedPacket> serialized_packet_; SimpleDataProducer producer_; quiche::SimpleBufferAllocator allocator_; }; INSTANTIATE_TEST_SUITE_P(QuicPacketCreatorTests, QuicPacketCreatorTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicPacketCreatorTest, SerializeFrames) { ParsedQuicVersion version = client_framer_.version(); for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { EncryptionLevel level = static_cast<EncryptionLevel>(i); bool has_ack = false, has_stream = false; creator_.set_encryption_level(level); size_t payload_len = 0; if (level != ENCRYPTION_ZERO_RTT) { frames_.push_back(QuicFrame(new QuicAckFrame(InitAckFrame(1)))); has_ack = true; payload_len += version.UsesTls() ? 12 : 6; } if (level != ENCRYPTION_INITIAL && level != ENCRYPTION_HANDSHAKE) { QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); frames_.push_back(QuicFrame( QuicStreamFrame(stream_id, false, 0u, absl::string_view()))); has_stream = true; payload_len += 2; } SerializedPacket serialized = SerializeAllFrames(frames_); EXPECT_EQ(level, serialized.encryption_level); if (level != ENCRYPTION_ZERO_RTT) { delete frames_[0].ack_frame; } frames_.clear(); ASSERT_GT(payload_len, 0); size_t min_payload = version.UsesTls() ? 3 : 7; bool need_padding = (version.HasHeaderProtection() && (payload_len < min_payload)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (need_padding) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } if (has_ack) { EXPECT_CALL(framer_visitor_, OnAckFrameStart(_, _)) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2))) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckFrameEnd(QuicPacketNumber(1), _)) .WillOnce(Return(true)); } if (has_stream) { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(serialized); } } TEST_P(QuicPacketCreatorTest, SerializeConnectionClose) { QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame( creator_.transport_version(), QUIC_NO_ERROR, NO_IETF_QUIC_ERROR, "error", 0); QuicFrames frames; frames.push_back(QuicFrame(frame)); SerializedPacket serialized = SerializeAllFrames(frames); EXPECT_EQ(ENCRYPTION_INITIAL, serialized.encryption_level); ASSERT_EQ(QuicPacketNumber(1u), serialized.packet_number); ASSERT_EQ(QuicPacketNumber(1u), creator_.packet_number()); InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnConnectionCloseFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); ProcessPacket(serialized); } TEST_P(QuicPacketCreatorTest, SerializePacketWithPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, SerializeLargerPacketWithPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount packet_size = 100 + kDefaultMaxPacketSize; creator_.SetMaxPacketLength(packet_size); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, IncreaseMaxPacketLengthWithFramesPending) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount packet_size = 100 + kDefaultMaxPacketSize; creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.SetMaxPacketLength(packet_size); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); DeleteSerializedPacket(); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, ConsumeCryptoDataToFillCurrentPacket) { std::string data = "crypto data"; QuicFrame frame; ASSERT_TRUE(creator_.ConsumeCryptoDataToFillCurrentPacket( ENCRYPTION_INITIAL, data.length(), 0, true, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(frame.crypto_frame->data_length, data.length()); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataToFillCurrentPacket) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(4u, consumed); CheckStreamFrame(frame, stream_id, "test", 0u, false); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataFin) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, true, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(4u, consumed); CheckStreamFrame(frame, stream_id, "test", 0u, true); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataFinOnly) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, {}, 0u, true, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(0u, consumed); CheckStreamFrame(frame, stream_id, std::string(), 0u, true); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(absl::StartsWith(creator_.GetPendingFramesInfo(), "type { STREAM_FRAME }")); } TEST_P(QuicPacketCreatorTest, CreateAllFreeBytesForStreamFrames) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead(); for (size_t i = overhead + QuicPacketCreator::MinPlaintextPacketSize( client_framer_.version(), QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); i < overhead + 100; ++i) { SCOPED_TRACE(i); creator_.SetMaxPacketLength(i); const bool should_have_room = i > overhead + GetStreamFrameOverhead(client_framer_.transport_version()); ASSERT_EQ(should_have_room, creator_.HasRoomForStreamFrame(GetNthClientInitiatedStreamId(1), kOffset, 0xffff)); if (should_have_room) { QuicFrame frame; const std::string data("testdata"); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly(Invoke( this, &QuicPacketCreatorTest::ClearSerializedPacketForTests)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); creator_.FlushCurrentPacket(); } } } TEST_P(QuicPacketCreatorTest, StreamFrameConsumption) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(2u, creator_.ExpansionOnNewFrame()); size_t expected_bytes_free = bytes_free < 3 ? 0 : bytes_free - 2; EXPECT_EQ(expected_bytes_free, creator_.BytesFree()) << "delta: " << delta; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, CryptoStreamFramePacketPadding) { SetQuicFlag(quic_enforce_single_packet_chlo, false); size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead(); if (QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { overhead += QuicFramer::GetMinCryptoFrameSize(kOffset, kMaxOutgoingPacketSize); } else { overhead += QuicFramer::GetMinStreamFrameSize( client_framer_.transport_version(), GetNthClientInitiatedStreamId(1), kOffset, false, 0); } ASSERT_GT(kMaxOutgoingPacketSize, overhead); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { SCOPED_TRACE(delta); std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); if (client_framer_.version().CanSendCoalescedPackets()) { EXPECT_CALL(delegate_, GetSerializedPacketFate(_, _)) .WillRepeatedly(Return(COALESCE)); } if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), data, kOffset, false, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); } else { producer_.SaveCryptoData(ENCRYPTION_INITIAL, kOffset, data); ASSERT_TRUE(creator_.ConsumeCryptoDataToFillCurrentPacket( ENCRYPTION_INITIAL, data.length(), kOffset, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.crypto_frame->data_length; EXPECT_LT(0u, bytes_consumed); } creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); if (client_framer_.version().CanSendCoalescedPackets()) { EXPECT_EQ(kDefaultMaxPacketSize - bytes_free, serialized_packet_->encrypted_length); } else { EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); } DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, NonCryptoStreamFramePacketNonPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); ASSERT_GT(kDefaultMaxPacketSize, overhead); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); if (bytes_free > 0) { EXPECT_EQ(kDefaultMaxPacketSize - bytes_free, serialized_packet_->encrypted_length); } else { EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); } DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, BuildPathChallengePacket) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; MockRandom randomizer; QuicPathFrameBuffer payload; randomizer.RandBytes(payload.data(), payload.size()); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1a, 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 0x00, 0x00, 0x00, 0x00, 0x00 }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = creator_.BuildPaddedPathChallengePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payload, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); EXPECT_EQ(kQuicPathFrameBufferSize, payload.size()); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildConnectivityProbingPacket) { QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet99[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; size_t packet_size = ABSL_ARRAYSIZE(packet); if (creator_.version().HasIetfQuicFrames()) { p = packet99; packet_size = ABSL_ARRAYSIZE(packet99); } std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = creator_.BuildConnectivityProbingPacket( header, buffer.get(), packet_size, ENCRYPTION_INITIAL); EXPECT_NE(0u, length); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(p), packet_size); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket1ResponseUnpadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); size_t length = creator_.BuildPathResponsePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payloads, false, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket1ResponsePadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]);
286
cpp
google/quiche
quic_stream_id_manager
quiche/quic/core/quic_stream_id_manager.cc
quiche/quic/core/quic_stream_id_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_ID_MANAGER_H_ #define QUICHE_QUIC_CORE_QUIC_STREAM_ID_MANAGER_H_ #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace test { class QuicSessionPeer; class QuicStreamIdManagerPeer; } class QUICHE_EXPORT QuicStreamIdManager { public: class QUICHE_EXPORT DelegateInterface { public: virtual ~DelegateInterface() = default; virtual bool CanSendMaxStreams() = 0; virtual void SendMaxStreams(QuicStreamCount stream_count, bool unidirectional) = 0; }; QuicStreamIdManager(DelegateInterface* delegate, bool unidirectional, Perspective perspective, ParsedQuicVersion version, QuicStreamCount max_allowed_outgoing_streams, QuicStreamCount max_allowed_incoming_streams); ~QuicStreamIdManager(); std::string DebugString() const { return absl::StrCat( " { unidirectional_: ", unidirectional_, ", perspective: ", perspective_, ", outgoing_max_streams_: ", outgoing_max_streams_, ", next_outgoing_stream_id_: ", next_outgoing_stream_id_, ", outgoing_stream_count_: ", outgoing_stream_count_, ", incoming_actual_max_streams_: ", incoming_actual_max_streams_, ", incoming_advertised_max_streams_: ", incoming_advertised_max_streams_, ", incoming_stream_count_: ", incoming_stream_count_, ", available_streams_.size(): ", available_streams_.size(), ", largest_peer_created_stream_id_: ", largest_peer_created_stream_id_, " }"); } bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame, std::string* error_details); bool CanOpenNextOutgoingStream() const; void SendMaxStreamsFrame(); void OnStreamClosed(QuicStreamId stream_id); QuicStreamId GetNextOutgoingStreamId(); void SetMaxOpenIncomingStreams(QuicStreamCount max_open_streams); bool MaybeAllowNewOutgoingStreams(QuicStreamCount max_open_streams); bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id, std::string* error_details); bool IsAvailableStream(QuicStreamId id) const; void StopIncreasingIncomingMaxStreams() { stop_increasing_incoming_max_streams_ = true; } QuicStreamCount incoming_initial_max_open_streams() const { return incoming_initial_max_open_streams_; } QuicStreamId next_outgoing_stream_id() const { return next_outgoing_stream_id_; } QuicStreamCount available_incoming_streams() const; QuicStreamId largest_peer_created_stream_id() const { return largest_peer_created_stream_id_; } QuicStreamCount outgoing_max_streams() const { return outgoing_max_streams_; } QuicStreamCount incoming_actual_max_streams() const { return incoming_actual_max_streams_; } QuicStreamCount incoming_advertised_max_streams() const { return incoming_advertised_max_streams_; } QuicStreamCount outgoing_stream_count() const { return outgoing_stream_count_; } void MaybeSendMaxStreamsFrame(); private: friend class test::QuicSessionPeer; friend class test::QuicStreamIdManagerPeer; QuicStreamId GetFirstOutgoingStreamId() const; QuicStreamId GetFirstIncomingStreamId() const; DelegateInterface* delegate_; const bool unidirectional_; const Perspective perspective_; const ParsedQuicVersion version_; QuicStreamCount outgoing_max_streams_; QuicStreamId next_outgoing_stream_id_; QuicStreamCount outgoing_stream_count_; QuicStreamCount incoming_actual_max_streams_; QuicStreamCount incoming_advertised_max_streams_; QuicStreamCount incoming_initial_max_open_streams_; QuicStreamCount incoming_stream_count_; absl::flat_hash_set<QuicStreamId> available_streams_; QuicStreamId largest_peer_created_stream_id_; bool stop_increasing_incoming_max_streams_; }; } #endif #include "quiche/quic/core/quic_stream_id_manager.h" #include <algorithm> #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? " Server: " : " Client: ") QuicStreamIdManager::QuicStreamIdManager( DelegateInterface* delegate, bool unidirectional, Perspective perspective, ParsedQuicVersion version, QuicStreamCount max_allowed_outgoing_streams, QuicStreamCount max_allowed_incoming_streams) : delegate_(delegate), unidirectional_(unidirectional), perspective_(perspective), version_(version), outgoing_max_streams_(max_allowed_outgoing_streams), next_outgoing_stream_id_(GetFirstOutgoingStreamId()), outgoing_stream_count_(0), incoming_actual_max_streams_(max_allowed_incoming_streams), incoming_advertised_max_streams_(max_allowed_incoming_streams), incoming_initial_max_open_streams_(max_allowed_incoming_streams), incoming_stream_count_(0), largest_peer_created_stream_id_( QuicUtils::GetInvalidStreamId(version.transport_version)), stop_increasing_incoming_max_streams_(false) {} QuicStreamIdManager::~QuicStreamIdManager() {} bool QuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { QUICHE_DCHECK_EQ(frame.unidirectional, unidirectional_); if (frame.stream_count > incoming_advertised_max_streams_) { *error_details = absl::StrCat( "StreamsBlockedFrame's stream count ", frame.stream_count, " exceeds incoming max stream ", incoming_advertised_max_streams_); return false; } QUICHE_DCHECK_LE(incoming_advertised_max_streams_, incoming_actual_max_streams_); if (incoming_advertised_max_streams_ == incoming_actual_max_streams_) { return true; } if (frame.stream_count < incoming_actual_max_streams_ && delegate_->CanSendMaxStreams()) { SendMaxStreamsFrame(); } return true; } bool QuicStreamIdManager::MaybeAllowNewOutgoingStreams( QuicStreamCount max_open_streams) { if (max_open_streams <= outgoing_max_streams_) { return false; } outgoing_max_streams_ = std::min(max_open_streams, QuicUtils::GetMaxStreamCount()); return true; } void QuicStreamIdManager::SetMaxOpenIncomingStreams( QuicStreamCount max_open_streams) { QUIC_BUG_IF(quic_bug_12413_1, incoming_stream_count_ > 0) << "non-zero incoming stream count " << incoming_stream_count_ << " when setting max incoming stream to " << max_open_streams; QUIC_DLOG_IF(WARNING, incoming_initial_max_open_streams_ != max_open_streams) << absl::StrCat(unidirectional_ ? "unidirectional " : "bidirectional: ", "incoming stream limit changed from ", incoming_initial_max_open_streams_, " to ", max_open_streams); incoming_actual_max_streams_ = max_open_streams; incoming_advertised_max_streams_ = max_open_streams; incoming_initial_max_open_streams_ = max_open_streams; } void QuicStreamIdManager::MaybeSendMaxStreamsFrame() { int divisor = GetQuicFlag(quic_max_streams_window_divisor); if (divisor > 0) { if ((incoming_advertised_max_streams_ - incoming_stream_count_) > (incoming_initial_max_open_streams_ / divisor)) { return; } } if (delegate_->CanSendMaxStreams() && incoming_advertised_max_streams_ < incoming_actual_max_streams_) { SendMaxStreamsFrame(); } } void QuicStreamIdManager::SendMaxStreamsFrame() { QUIC_BUG_IF(quic_bug_12413_2, incoming_advertised_max_streams_ >= incoming_actual_max_streams_); incoming_advertised_max_streams_ = incoming_actual_max_streams_; delegate_->SendMaxStreams(incoming_advertised_max_streams_, unidirectional_); } void QuicStreamIdManager::OnStreamClosed(QuicStreamId stream_id) { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id, version_), unidirectional_); if (QuicUtils::IsOutgoingStreamId(version_, stream_id, perspective_)) { return; } if (incoming_actual_max_streams_ == QuicUtils::GetMaxStreamCount()) { return; } if (!stop_increasing_incoming_max_streams_) { incoming_actual_max_streams_++; MaybeSendMaxStreamsFrame(); } } QuicStreamId QuicStreamIdManager::GetNextOutgoingStreamId() { QUIC_BUG_IF(quic_bug_12413_3, outgoing_stream_count_ >= outgoing_max_streams_) << "Attempt to allocate a new outgoing stream that would exceed the " "limit (" << outgoing_max_streams_ << ")"; QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += QuicUtils::StreamIdDelta(version_.transport_version); outgoing_stream_count_++; return id; } bool QuicStreamIdManager::CanOpenNextOutgoingStream() const { QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version)); return outgoing_stream_count_ < outgoing_max_streams_; } bool QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id, std::string* error_details) { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id, version_), unidirectional_); QUICHE_DCHECK_NE(QuicUtils::IsServerInitiatedStreamId( version_.transport_version, stream_id), perspective_ == Perspective::IS_SERVER); if (available_streams_.erase(stream_id) == 1) { return true; } if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(version_.transport_version)) { QUICHE_DCHECK_GT(stream_id, largest_peer_created_stream_id_); } const QuicStreamCount delta = QuicUtils::StreamIdDelta(version_.transport_version); const QuicStreamId least_new_stream_id = largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(version_.transport_version) ? GetFirstIncomingStreamId() : largest_peer_created_stream_id_ + delta; const QuicStreamCount stream_count_increment = (stream_id - least_new_stream_id) / delta + 1; if (incoming_stream_count_ + stream_count_increment > incoming_advertised_max_streams_) { QUIC_DLOG(INFO) << ENDPOINT << "Failed to create a new incoming stream with id:" << stream_id << ", reaching MAX_STREAMS limit: " << incoming_advertised_max_streams_ << "."; *error_details = absl::StrCat("Stream id ", stream_id, " would exceed stream count limit ", incoming_advertised_max_streams_); return false; } for (QuicStreamId id = least_new_stream_id; id < stream_id; id += delta) { available_streams_.insert(id); } incoming_stream_count_ += stream_count_increment; largest_peer_created_stream_id_ = stream_id; return true; } bool QuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id, version_), unidirectional_); if (QuicUtils::IsOutgoingStreamId(version_, id, perspective_)) { return id >= next_outgoing_stream_id_; } return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(version_.transport_version) || id > largest_peer_created_stream_id_ || available_streams_.contains(id); } QuicStreamId QuicStreamIdManager::GetFirstOutgoingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( version_.transport_version, perspective_) : QuicUtils::GetFirstBidirectionalStreamId( version_.transport_version, perspective_); } QuicStreamId QuicStreamIdManager::GetFirstIncomingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( version_.transport_version, QuicUtils::InvertPerspective(perspective_)) : QuicUtils::GetFirstBidirectionalStreamId( version_.transport_version, QuicUtils::InvertPerspective(perspective_)); } QuicStreamCount QuicStreamIdManager::available_incoming_streams() const { return incoming_advertised_max_streams_ - incoming_stream_count_; } }
#include "quiche/quic/core/quic_stream_id_manager.h" #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h" using testing::_; using testing::StrictMock; namespace quic { namespace test { namespace { class MockDelegate : public QuicStreamIdManager::DelegateInterface { public: MOCK_METHOD(void, SendMaxStreams, (QuicStreamCount stream_count, bool unidirectional), (override)); MOCK_METHOD(bool, CanSendMaxStreams, (), (override)); }; struct TestParams { TestParams(ParsedQuicVersion version, Perspective perspective, bool is_unidirectional) : version(version), perspective(perspective), is_unidirectional(is_unidirectional) {} ParsedQuicVersion version; Perspective perspective; bool is_unidirectional; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.perspective == Perspective::IS_CLIENT ? "Client" : "Server"), (p.is_unidirectional ? "Unidirectional" : "Bidirectional")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (!version.HasIetfQuicFrames()) { continue; } for (Perspective perspective : {Perspective::IS_CLIENT, Perspective::IS_SERVER}) { for (bool is_unidirectional : {true, false}) { params.push_back(TestParams(version, perspective, is_unidirectional)); } } } return params; } class QuicStreamIdManagerTest : public QuicTestWithParam<TestParams> { protected: QuicStreamIdManagerTest() : stream_id_manager_(&delegate_, IsUnidirectional(), perspective(), GetParam().version, 0, kDefaultMaxStreamsPerConnection) { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); } QuicTransportVersion transport_version() const { return GetParam().version.transport_version; } QuicStreamId GetNthIncomingStreamId(int n) { return QuicUtils::StreamIdDelta(transport_version()) * n + (IsUnidirectional() ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), QuicUtils::InvertPerspective(perspective())) : QuicUtils::GetFirstBidirectionalStreamId( transport_version(), QuicUtils::InvertPerspective(perspective()))); } bool IsUnidirectional() { return GetParam().is_unidirectional; } Perspective perspective() { return GetParam().perspective; } StrictMock<MockDelegate> delegate_; QuicStreamIdManager stream_id_manager_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicStreamIdManagerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicStreamIdManagerTest, Initialization) { EXPECT_EQ(0u, stream_id_manager_.outgoing_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_advertised_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_initial_max_open_streams()); } TEST_P(QuicStreamIdManagerTest, CheckMaxStreamsWindowForSingleStream) { stream_id_manager_.SetMaxOpenIncomingStreams(1); EXPECT_EQ(1u, stream_id_manager_.incoming_initial_max_open_streams()); EXPECT_EQ(1u, stream_id_manager_.incoming_actual_max_streams()); } TEST_P(QuicStreamIdManagerTest, CheckMaxStreamsBadValuesOverMaxFailsOutgoing) { QuicStreamCount implementation_max = QuicUtils::GetMaxStreamCount(); EXPECT_LT(stream_id_manager_.outgoing_max_streams(), implementation_max); EXPECT_TRUE( stream_id_manager_.MaybeAllowNewOutgoingStreams(implementation_max + 1)); EXPECT_EQ(implementation_max, stream_id_manager_.outgoing_max_streams()); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedOk) { QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamsBlockedFrame frame(0, stream_count - 1, IsUnidirectional()); EXPECT_CALL(delegate_, SendMaxStreams(stream_count, IsUnidirectional())) .Times(0); std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedNoOp) { QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamsBlockedFrame frame(0, stream_count, IsUnidirectional()); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedTooBig) { EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams() + 1; QuicStreamsBlockedFrame frame(0, stream_count, IsUnidirectional()); std::string error_details; EXPECT_FALSE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ( error_details, "StreamsBlockedFrame's stream count 101 exceeds incoming max stream 100"); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdValidBelowLimit) { QuicStreamId stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 2); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdValidAtLimit) { QuicStreamId stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 1); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdInValidAboveLimit) { QuicStreamId stream_id = GetNthIncomingStreamId(stream_id_manager_.incoming_actual_max_streams()); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( stream_id, &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", stream_id, " would exceed stream count limit 100")); } TEST_P(QuicStreamIdManagerTest, OnStreamsBlockedFrame) { QuicStreamCount advertised_stream_count = stream_id_manager_.incoming_advertised_max_streams(); QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); frame.stream_count = advertised_stream_count; std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); frame.stream_count = advertised_stream_count + 1; EXPECT_FALSE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ( error_details, "StreamsBlockedFrame's stream count 101 exceeds incoming max stream 100"); QuicStreamCount actual_stream_count = stream_id_manager_.incoming_actual_max_streams(); stream_id_manager_.OnStreamClosed( QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_)); EXPECT_EQ(actual_stream_count + 1u, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams() + 1u); frame.stream_count = advertised_stream_count; EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(stream_id_manager_.incoming_actual_max_streams(), IsUnidirectional())); EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, OnStreamsBlockedFrameCantSend) { QuicStreamCount advertised_stream_count = stream_id_manager_.incoming_advertised_max_streams(); QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); QuicStreamCount actual_stream_count = stream_id_manager_.incoming_actual_max_streams(); stream_id_manager_.OnStreamClosed( QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_)); EXPECT_EQ(actual_stream_count + 1u, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams() + 1u); frame.stream_count = advertised_stream_count; EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(false)); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); const QuicStreamCount advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ(advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, GetNextOutgoingStream) { size_t number_of_streams = kDefaultMaxStreamsPerConnection; EXPECT_TRUE( stream_id_manager_.MaybeAllowNewOutgoingStreams(number_of_streams)); QuicStreamId stream_id = IsUnidirectional() ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version(), perspective()); EXPECT_EQ(number_of_streams, stream_id_manager_.outgoing_max_streams()); while (number_of_streams) { EXPECT_TRUE(stream_id_manager_.CanOpenNextOutgoingStream()); EXPECT_EQ(stream_id, stream_id_manager_.GetNextOutgoingStreamId()); stream_id += QuicUtils::StreamIdDelta(transport_version()); number_of_streams--; } EXPECT_FALSE(stream_id_manager_.CanOpenNextOutgoingStream()); EXPECT_QUIC_BUG( stream_id_manager_.GetNextOutgoingStreamId(), "Attempt to allocate a new outgoing stream that would exceed the limit"); } TEST_P(QuicStreamIdManagerTest, MaybeIncreaseLargestPeerStreamId) { QuicStreamId max_stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 1); EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(max_stream_id, nullptr)); QuicStreamId first_stream_id = GetNthIncomingStreamId(0); EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( first_stream_id, nullptr)); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( max_stream_id + QuicUtils::StreamIdDelta(transport_version()), &error_details)); EXPECT_EQ(error_details, absl::StrCat( "Stream id ", max_stream_id + QuicUtils::StreamIdDelta(transport_version()), " would exceed stream count limit 100")); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindow) { int stream_count = stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor) - 1; EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamId stream_id = GetNthIncomingStreamId(0); size_t old_available_incoming_streams = stream_id_manager_.available_incoming_streams(); auto i = stream_count; while (i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); old_available_incoming_streams--; EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); i--; stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); while (stream_count) { stream_id_manager_.OnStreamClosed(stream_id); stream_count--; stream_id += QuicUtils::StreamIdDelta(transport_version()); expected_actual_max++; EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(_, IsUnidirectional())); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id_manager_.OnStreamClosed(stream_id); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindowCantSend) { int stream_count = stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor) - 1; EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamId stream_id = GetNthIncomingStreamId(0); size_t old_available_incoming_streams = stream_id_manager_.available_incoming_streams(); auto i = stream_count; while (i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); old_available_incoming_streams--; EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); i--; stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); while (stream_count) { stream_id_manager_.OnStreamClosed(stream_id); stream_count--; stream_id += QuicUtils::StreamIdDelta(transport_version()); expected_actual_max++; EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(false)); EXPECT_CALL(delegate_, SendMaxStreams(_, IsUnidirectional())).Times(0); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id_manager_.OnStreamClosed(stream_id); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindowStopsIncreasing) { QuicStreamId stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamId stream_id = GetNthIncomingStreamId(0); for (QuicStreamCount i = 0; i < stream_count; ++i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id_manager_.StopIncreasingIncomingMaxStreams(); EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); for (QuicStreamCount i = 0; i < stream_count; ++i) { stream_id_manager_.OnStreamClosed(stream_id); stream_id += QuicUtils::StreamIdDelta(transport_version()); EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } } TEST_P(QuicStreamIdManagerTest, StreamsBlockedEdgeConditions) { QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); stream_id_manager_.SetMaxOpenIncomingStreams(0); frame.stream_count = 0; std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(123u, IsUnidirectional())); QuicStreamIdManagerPeer::set_incoming_actual_max_streams(&stream_id_manager_, 123); frame.stream_count = 0; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); } TEST_P(QuicStreamIdManagerTest, MaxStreamsSlidingWindow) { QuicStreamCount first_advert = stream_id_manager_.incoming_advertised_max_streams(); int i = static_cast<int>(stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor)); QuicStreamId id = QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(first_advert + i, IsUnidirectional())); while (i) { EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(id, nullptr)); stream_id_manager_.OnStreamClosed(id); i--; id += QuicUtils::StreamIdDelta(transport_version()); } } TEST_P(QuicStreamIdManagerTest, NewStreamDoesNotExceedLimit) { EXPECT_TRUE(stream_id_manager_.MaybeAllowNewOutgoingStreams(100)); size_t stream_count = stream_id_manager_.outgoing_max_streams(); EXPECT_NE(0u, stream_count); while (stream_count) { EXPECT_TRUE(stream_id_manager_.CanOpenNextOutgoingStream()); stream_id_manager_.GetNextOutgoingStreamId(); stream_count--; } EXPECT_EQ(stream_id_manager_.outgoing_stream_count(), stream_id_manager_.outgoing_max_streams()); EXPECT_FALSE(stream_id_manager_.CanOpenNextOutgoingStream()); } TEST_P(QuicStreamIdManagerTest, AvailableStreams) { stream_id_manager_.MaybeIncreaseLargestPeerStreamId(GetNthIncomingStreamId(3), nullptr); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(1))); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(2))); EXPECT_FALSE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(3))); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(4))); } TEST_P(QuicStreamIdManagerTest, ExtremeMaybeIncreaseLargestPeerStreamId) { QuicStreamId too_big_stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() + 20); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( too_big_stream_id, &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", too_big_stream_id, " would exceed stream count limit 100")); } } } }
287
cpp
google/quiche
uber_quic_stream_id_manager
quiche/quic/core/uber_quic_stream_id_manager.cc
quiche/quic/core/uber_quic_stream_id_manager_test.cc
#ifndef QUICHE_QUIC_CORE_UBER_QUIC_STREAM_ID_MANAGER_H_ #define QUICHE_QUIC_CORE_UBER_QUIC_STREAM_ID_MANAGER_H_ #include "quiche/quic/core/quic_stream_id_manager.h" #include "quiche/quic/core/quic_types.h" namespace quic { namespace test { class QuicSessionPeer; class UberQuicStreamIdManagerPeer; } class QuicSession; class QUICHE_EXPORT UberQuicStreamIdManager { public: UberQuicStreamIdManager( Perspective perspective, ParsedQuicVersion version, QuicStreamIdManager::DelegateInterface* delegate, QuicStreamCount max_open_outgoing_bidirectional_streams, QuicStreamCount max_open_outgoing_unidirectional_streams, QuicStreamCount max_open_incoming_bidirectional_streams, QuicStreamCount max_open_incoming_unidirectional_streams); bool MaybeAllowNewOutgoingBidirectionalStreams( QuicStreamCount max_open_streams); bool MaybeAllowNewOutgoingUnidirectionalStreams( QuicStreamCount max_open_streams); void SetMaxOpenIncomingBidirectionalStreams(QuicStreamCount max_open_streams); void SetMaxOpenIncomingUnidirectionalStreams( QuicStreamCount max_open_streams); bool CanOpenNextOutgoingBidirectionalStream() const; bool CanOpenNextOutgoingUnidirectionalStream() const; QuicStreamId GetNextOutgoingBidirectionalStreamId(); QuicStreamId GetNextOutgoingUnidirectionalStreamId(); bool MaybeIncreaseLargestPeerStreamId(QuicStreamId id, std::string* error_details); void OnStreamClosed(QuicStreamId id); bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame, std::string* error_details); bool IsAvailableStream(QuicStreamId id) const; void StopIncreasingIncomingMaxStreams(); void MaybeSendMaxStreamsFrame(); QuicStreamCount GetMaxAllowdIncomingBidirectionalStreams() const; QuicStreamCount GetMaxAllowdIncomingUnidirectionalStreams() const; QuicStreamId GetLargestPeerCreatedStreamId(bool unidirectional) const; QuicStreamId next_outgoing_bidirectional_stream_id() const; QuicStreamId next_outgoing_unidirectional_stream_id() const; QuicStreamCount max_outgoing_bidirectional_streams() const; QuicStreamCount max_outgoing_unidirectional_streams() const; QuicStreamCount max_incoming_bidirectional_streams() const; QuicStreamCount max_incoming_unidirectional_streams() const; QuicStreamCount advertised_max_incoming_bidirectional_streams() const; QuicStreamCount advertised_max_incoming_unidirectional_streams() const; QuicStreamCount outgoing_bidirectional_stream_count() const; QuicStreamCount outgoing_unidirectional_stream_count() const; private: friend class test::QuicSessionPeer; friend class test::UberQuicStreamIdManagerPeer; ParsedQuicVersion version_; QuicStreamIdManager bidirectional_stream_id_manager_; QuicStreamIdManager unidirectional_stream_id_manager_; }; } #endif #include "quiche/quic/core/uber_quic_stream_id_manager.h" #include <string> #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" namespace quic { UberQuicStreamIdManager::UberQuicStreamIdManager( Perspective perspective, ParsedQuicVersion version, QuicStreamIdManager::DelegateInterface* delegate, QuicStreamCount max_open_outgoing_bidirectional_streams, QuicStreamCount max_open_outgoing_unidirectional_streams, QuicStreamCount max_open_incoming_bidirectional_streams, QuicStreamCount max_open_incoming_unidirectional_streams) : version_(version), bidirectional_stream_id_manager_(delegate, false, perspective, version, max_open_outgoing_bidirectional_streams, max_open_incoming_bidirectional_streams), unidirectional_stream_id_manager_( delegate, true, perspective, version, max_open_outgoing_unidirectional_streams, max_open_incoming_unidirectional_streams) {} bool UberQuicStreamIdManager::MaybeAllowNewOutgoingBidirectionalStreams( QuicStreamCount max_open_streams) { return bidirectional_stream_id_manager_.MaybeAllowNewOutgoingStreams( max_open_streams); } bool UberQuicStreamIdManager::MaybeAllowNewOutgoingUnidirectionalStreams( QuicStreamCount max_open_streams) { return unidirectional_stream_id_manager_.MaybeAllowNewOutgoingStreams( max_open_streams); } void UberQuicStreamIdManager::SetMaxOpenIncomingBidirectionalStreams( QuicStreamCount max_open_streams) { bidirectional_stream_id_manager_.SetMaxOpenIncomingStreams(max_open_streams); } void UberQuicStreamIdManager::SetMaxOpenIncomingUnidirectionalStreams( QuicStreamCount max_open_streams) { unidirectional_stream_id_manager_.SetMaxOpenIncomingStreams(max_open_streams); } bool UberQuicStreamIdManager::CanOpenNextOutgoingBidirectionalStream() const { return bidirectional_stream_id_manager_.CanOpenNextOutgoingStream(); } bool UberQuicStreamIdManager::CanOpenNextOutgoingUnidirectionalStream() const { return unidirectional_stream_id_manager_.CanOpenNextOutgoingStream(); } QuicStreamId UberQuicStreamIdManager::GetNextOutgoingBidirectionalStreamId() { return bidirectional_stream_id_manager_.GetNextOutgoingStreamId(); } QuicStreamId UberQuicStreamIdManager::GetNextOutgoingUnidirectionalStreamId() { return unidirectional_stream_id_manager_.GetNextOutgoingStreamId(); } bool UberQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( QuicStreamId id, std::string* error_details) { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { return bidirectional_stream_id_manager_.MaybeIncreaseLargestPeerStreamId( id, error_details); } return unidirectional_stream_id_manager_.MaybeIncreaseLargestPeerStreamId( id, error_details); } void UberQuicStreamIdManager::OnStreamClosed(QuicStreamId id) { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { bidirectional_stream_id_manager_.OnStreamClosed(id); return; } unidirectional_stream_id_manager_.OnStreamClosed(id); } bool UberQuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { if (frame.unidirectional) { return unidirectional_stream_id_manager_.OnStreamsBlockedFrame( frame, error_details); } return bidirectional_stream_id_manager_.OnStreamsBlockedFrame(frame, error_details); } bool UberQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { return bidirectional_stream_id_manager_.IsAvailableStream(id); } return unidirectional_stream_id_manager_.IsAvailableStream(id); } void UberQuicStreamIdManager::StopIncreasingIncomingMaxStreams() { unidirectional_stream_id_manager_.StopIncreasingIncomingMaxStreams(); bidirectional_stream_id_manager_.StopIncreasingIncomingMaxStreams(); } void UberQuicStreamIdManager::MaybeSendMaxStreamsFrame() { unidirectional_stream_id_manager_.MaybeSendMaxStreamsFrame(); bidirectional_stream_id_manager_.MaybeSendMaxStreamsFrame(); } QuicStreamCount UberQuicStreamIdManager::GetMaxAllowdIncomingBidirectionalStreams() const { return bidirectional_stream_id_manager_.incoming_initial_max_open_streams(); } QuicStreamCount UberQuicStreamIdManager::GetMaxAllowdIncomingUnidirectionalStreams() const { return unidirectional_stream_id_manager_.incoming_initial_max_open_streams(); } QuicStreamId UberQuicStreamIdManager::GetLargestPeerCreatedStreamId( bool unidirectional) const { if (unidirectional) { return unidirectional_stream_id_manager_.largest_peer_created_stream_id(); } return bidirectional_stream_id_manager_.largest_peer_created_stream_id(); } QuicStreamId UberQuicStreamIdManager::next_outgoing_bidirectional_stream_id() const { return bidirectional_stream_id_manager_.next_outgoing_stream_id(); } QuicStreamId UberQuicStreamIdManager::next_outgoing_unidirectional_stream_id() const { return unidirectional_stream_id_manager_.next_outgoing_stream_id(); } QuicStreamCount UberQuicStreamIdManager::max_outgoing_bidirectional_streams() const { return bidirectional_stream_id_manager_.outgoing_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_outgoing_unidirectional_streams() const { return unidirectional_stream_id_manager_.outgoing_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_incoming_bidirectional_streams() const { return bidirectional_stream_id_manager_.incoming_actual_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_incoming_unidirectional_streams() const { return unidirectional_stream_id_manager_.incoming_actual_max_streams(); } QuicStreamCount UberQuicStreamIdManager::advertised_max_incoming_bidirectional_streams() const { return bidirectional_stream_id_manager_.incoming_advertised_max_streams(); } QuicStreamCount UberQuicStreamIdManager::advertised_max_incoming_unidirectional_streams() const { return unidirectional_stream_id_manager_.incoming_advertised_max_streams(); } QuicStreamCount UberQuicStreamIdManager::outgoing_bidirectional_stream_count() const { return bidirectional_stream_id_manager_.outgoing_stream_count(); } QuicStreamCount UberQuicStreamIdManager::outgoing_unidirectional_stream_count() const { return unidirectional_stream_id_manager_.outgoing_stream_count(); } }
#include "quiche/quic/core/uber_quic_stream_id_manager.h" #include <string> #include <vector> #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::StrictMock; namespace quic { namespace test { namespace { struct TestParams { explicit TestParams(ParsedQuicVersion version, Perspective perspective) : version(version), perspective(perspective) {} ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (!version.HasIetfQuicFrames()) { continue; } params.push_back(TestParams(version, Perspective::IS_CLIENT)); params.push_back(TestParams(version, Perspective::IS_SERVER)); } return params; } class MockDelegate : public QuicStreamIdManager::DelegateInterface { public: MOCK_METHOD(bool, CanSendMaxStreams, (), (override)); MOCK_METHOD(void, SendMaxStreams, (QuicStreamCount stream_count, bool unidirectional), (override)); }; class UberQuicStreamIdManagerTest : public QuicTestWithParam<TestParams> { protected: UberQuicStreamIdManagerTest() : manager_(perspective(), version(), &delegate_, 0, 0, kDefaultMaxStreamsPerConnection, kDefaultMaxStreamsPerConnection) {} QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthServerInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthPeerInitiatedBidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_SERVER) ? GetNthClientInitiatedBidirectionalId(n) : GetNthServerInitiatedBidirectionalId(n)); } QuicStreamId GetNthPeerInitiatedUnidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_SERVER) ? GetNthClientInitiatedUnidirectionalId(n) : GetNthServerInitiatedUnidirectionalId(n)); } QuicStreamId GetNthSelfInitiatedBidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_CLIENT) ? GetNthClientInitiatedBidirectionalId(n) : GetNthServerInitiatedBidirectionalId(n)); } QuicStreamId GetNthSelfInitiatedUnidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_CLIENT) ? GetNthClientInitiatedUnidirectionalId(n) : GetNthServerInitiatedUnidirectionalId(n)); } QuicStreamId StreamCountToId(QuicStreamCount stream_count, Perspective perspective, bool bidirectional) { return ((bidirectional) ? QuicUtils::GetFirstBidirectionalStreamId( transport_version(), perspective) : QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), perspective)) + ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version())); } ParsedQuicVersion version() { return GetParam().version; } QuicTransportVersion transport_version() { return version().transport_version; } Perspective perspective() { return GetParam().perspective; } testing::StrictMock<MockDelegate> delegate_; UberQuicStreamIdManager manager_; }; INSTANTIATE_TEST_SUITE_P(Tests, UberQuicStreamIdManagerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(UberQuicStreamIdManagerTest, Initialization) { EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(0), manager_.next_outgoing_bidirectional_stream_id()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(0), manager_.next_outgoing_unidirectional_stream_id()); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenOutgoingStreams) { const size_t kNumMaxOutgoingStream = 123; EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams( kNumMaxOutgoingStream)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams( kNumMaxOutgoingStream + 1)); EXPECT_EQ(kNumMaxOutgoingStream, manager_.max_outgoing_bidirectional_streams()); EXPECT_EQ(kNumMaxOutgoingStream + 1, manager_.max_outgoing_unidirectional_streams()); int i = kNumMaxOutgoingStream; while (i) { EXPECT_TRUE(manager_.CanOpenNextOutgoingBidirectionalStream()); manager_.GetNextOutgoingBidirectionalStreamId(); EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); i--; } EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); EXPECT_FALSE(manager_.CanOpenNextOutgoingUnidirectionalStream()); EXPECT_FALSE(manager_.CanOpenNextOutgoingBidirectionalStream()); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenIncomingStreams) { const size_t kNumMaxIncomingStreams = 456; manager_.SetMaxOpenIncomingUnidirectionalStreams(kNumMaxIncomingStreams); manager_.SetMaxOpenIncomingBidirectionalStreams(kNumMaxIncomingStreams + 1); EXPECT_EQ(kNumMaxIncomingStreams + 1, manager_.GetMaxAllowdIncomingBidirectionalStreams()); EXPECT_EQ(kNumMaxIncomingStreams, manager_.GetMaxAllowdIncomingUnidirectionalStreams()); EXPECT_EQ(manager_.max_incoming_bidirectional_streams(), manager_.advertised_max_incoming_bidirectional_streams()); EXPECT_EQ(manager_.max_incoming_unidirectional_streams(), manager_.advertised_max_incoming_unidirectional_streams()); size_t i; for (i = 0; i < kNumMaxIncomingStreams; i++) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(i), nullptr)); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i), nullptr)); } EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i), nullptr)); std::string error_details; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(i), &error_details)); EXPECT_EQ(error_details, absl::StrCat( "Stream id ", GetNthPeerInitiatedUnidirectionalStreamId(i), " would exceed stream count limit ", kNumMaxIncomingStreams)); EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i + 1), &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", GetNthPeerInitiatedBidirectionalStreamId(i + 1), " would exceed stream count limit ", kNumMaxIncomingStreams + 1)); } TEST_P(UberQuicStreamIdManagerTest, GetNextOutgoingStreamId) { EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams(10)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams(10)); EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(0), manager_.GetNextOutgoingBidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(1), manager_.GetNextOutgoingBidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(0), manager_.GetNextOutgoingUnidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(1), manager_.GetNextOutgoingUnidirectionalStreamId()); } TEST_P(UberQuicStreamIdManagerTest, AvailableStreams) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(3), nullptr)); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedBidirectionalStreamId(1))); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedBidirectionalStreamId(2))); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(3), nullptr)); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedUnidirectionalStreamId(1))); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedUnidirectionalStreamId(2))); } TEST_P(UberQuicStreamIdManagerTest, MaybeIncreaseLargestPeerStreamId) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams(), QuicUtils::InvertPerspective(perspective()), true), nullptr)); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams(), QuicUtils::InvertPerspective(perspective()), false), nullptr)); std::string expected_error_details = perspective() == Perspective::IS_SERVER ? "Stream id 400 would exceed stream count limit 100" : "Stream id 401 would exceed stream count limit 100"; std::string error_details; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams() + 1, QuicUtils::InvertPerspective(perspective()), true), &error_details)); EXPECT_EQ(expected_error_details, error_details); expected_error_details = perspective() == Perspective::IS_SERVER ? "Stream id 402 would exceed stream count limit 100" : "Stream id 403 would exceed stream count limit 100"; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams() + 1, QuicUtils::InvertPerspective(perspective()), false), &error_details)); EXPECT_EQ(expected_error_details, error_details); } TEST_P(UberQuicStreamIdManagerTest, OnStreamsBlockedFrame) { QuicStreamCount stream_count = manager_.advertised_max_incoming_bidirectional_streams() - 1; QuicStreamsBlockedFrame frame(kInvalidControlFrameId, stream_count, false); EXPECT_CALL(delegate_, SendMaxStreams(manager_.max_incoming_bidirectional_streams(), frame.unidirectional)) .Times(0); EXPECT_TRUE(manager_.OnStreamsBlockedFrame(frame, nullptr)); stream_count = manager_.advertised_max_incoming_unidirectional_streams() - 1; frame.stream_count = stream_count; frame.unidirectional = true; EXPECT_CALL(delegate_, SendMaxStreams(manager_.max_incoming_unidirectional_streams(), frame.unidirectional)) .Times(0); EXPECT_TRUE(manager_.OnStreamsBlockedFrame(frame, nullptr)); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenOutgoingStreamsPlusFrame) { const size_t kNumMaxOutgoingStream = 123; EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams( kNumMaxOutgoingStream)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams( kNumMaxOutgoingStream + 1)); EXPECT_EQ(kNumMaxOutgoingStream, manager_.max_outgoing_bidirectional_streams()); EXPECT_EQ(kNumMaxOutgoingStream + 1, manager_.max_outgoing_unidirectional_streams()); int i = kNumMaxOutgoingStream; while (i) { EXPECT_TRUE(manager_.CanOpenNextOutgoingBidirectionalStream()); manager_.GetNextOutgoingBidirectionalStreamId(); EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); i--; } EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); EXPECT_FALSE(manager_.CanOpenNextOutgoingUnidirectionalStream()); EXPECT_FALSE(manager_.CanOpenNextOutgoingBidirectionalStream()); } } } }
288
cpp
google/quiche
qpack_decoder
quiche/quic/core/qpack/qpack_decoder.cc
quiche/quic/core/qpack/qpack_decoder_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_ #include <cstdint> #include <memory> #include <set> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_decoder_stream_sender.h" #include "quiche/quic/core/qpack/qpack_encoder_stream_receiver.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/core/qpack/qpack_progressive_decoder.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackDecoder : public QpackEncoderStreamReceiver::Delegate, public QpackProgressiveDecoder::BlockedStreamLimitEnforcer, public QpackProgressiveDecoder::DecodingCompletedVisitor { public: class QUICHE_EXPORT EncoderStreamErrorDelegate { public: virtual ~EncoderStreamErrorDelegate() {} virtual void OnEncoderStreamError(QuicErrorCode error_code, absl::string_view error_message) = 0; }; QpackDecoder(uint64_t maximum_dynamic_table_capacity, uint64_t maximum_blocked_streams, EncoderStreamErrorDelegate* encoder_stream_error_delegate); ~QpackDecoder() override; void OnStreamReset(QuicStreamId stream_id); bool OnStreamBlocked(QuicStreamId stream_id) override; void OnStreamUnblocked(QuicStreamId stream_id) override; void OnDecodingCompleted(QuicStreamId stream_id, uint64_t required_insert_count) override; std::unique_ptr<QpackProgressiveDecoder> CreateProgressiveDecoder( QuicStreamId stream_id, QpackProgressiveDecoder::HeadersHandlerInterface* handler); void OnInsertWithNameReference(bool is_static, uint64_t name_index, absl::string_view value) override; void OnInsertWithoutNameReference(absl::string_view name, absl::string_view value) override; void OnDuplicate(uint64_t index) override; void OnSetDynamicTableCapacity(uint64_t capacity) override; void OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) override; void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) { decoder_stream_sender_.set_qpack_stream_sender_delegate(delegate); } QpackStreamReceiver* encoder_stream_receiver() { return &encoder_stream_receiver_; } bool dynamic_table_entry_referenced() const { return header_table_.dynamic_table_entry_referenced(); } void FlushDecoderStream(); private: EncoderStreamErrorDelegate* const encoder_stream_error_delegate_; QpackEncoderStreamReceiver encoder_stream_receiver_; QpackDecoderStreamSender decoder_stream_sender_; QpackDecoderHeaderTable header_table_; std::set<QuicStreamId> blocked_streams_; const uint64_t maximum_blocked_streams_; uint64_t known_received_count_; }; class QUICHE_EXPORT NoopEncoderStreamErrorDelegate : public QpackDecoder::EncoderStreamErrorDelegate { public: ~NoopEncoderStreamErrorDelegate() override = default; void OnEncoderStreamError(QuicErrorCode , absl::string_view ) override {} }; } #endif #include "quiche/quic/core/qpack/qpack_decoder.h" #include <memory> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_index_conversions.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QpackDecoder::QpackDecoder( uint64_t maximum_dynamic_table_capacity, uint64_t maximum_blocked_streams, EncoderStreamErrorDelegate* encoder_stream_error_delegate) : encoder_stream_error_delegate_(encoder_stream_error_delegate), encoder_stream_receiver_(this), maximum_blocked_streams_(maximum_blocked_streams), known_received_count_(0) { QUICHE_DCHECK(encoder_stream_error_delegate_); header_table_.SetMaximumDynamicTableCapacity(maximum_dynamic_table_capacity); } QpackDecoder::~QpackDecoder() {} void QpackDecoder::OnStreamReset(QuicStreamId stream_id) { if (header_table_.maximum_dynamic_table_capacity() > 0) { decoder_stream_sender_.SendStreamCancellation(stream_id); if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { decoder_stream_sender_.Flush(); } } } bool QpackDecoder::OnStreamBlocked(QuicStreamId stream_id) { auto result = blocked_streams_.insert(stream_id); QUICHE_DCHECK(result.second); return blocked_streams_.size() <= maximum_blocked_streams_; } void QpackDecoder::OnStreamUnblocked(QuicStreamId stream_id) { size_t result = blocked_streams_.erase(stream_id); QUICHE_DCHECK_EQ(1u, result); } void QpackDecoder::OnDecodingCompleted(QuicStreamId stream_id, uint64_t required_insert_count) { if (required_insert_count > 0) { decoder_stream_sender_.SendHeaderAcknowledgement(stream_id); if (known_received_count_ < required_insert_count) { known_received_count_ = required_insert_count; } } if (known_received_count_ < header_table_.inserted_entry_count()) { decoder_stream_sender_.SendInsertCountIncrement( header_table_.inserted_entry_count() - known_received_count_); known_received_count_ = header_table_.inserted_entry_count(); } if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { decoder_stream_sender_.Flush(); } } void QpackDecoder::OnInsertWithNameReference(bool is_static, uint64_t name_index, absl::string_view value) { if (is_static) { auto entry = header_table_.LookupEntry( true, name_index); if (!entry) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY, "Invalid static table entry."); return; } if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(), value)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_STATIC, "Error inserting entry with name reference."); return; } header_table_.InsertEntry(entry->name(), value); return; } uint64_t absolute_index; if (!QpackEncoderStreamRelativeIndexToAbsoluteIndex( name_index, header_table_.inserted_entry_count(), &absolute_index)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX, "Invalid relative index."); return; } const QpackEntry* entry = header_table_.LookupEntry( false, absolute_index); if (!entry) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INSERTION_DYNAMIC_ENTRY_NOT_FOUND, "Dynamic table entry not found."); return; } if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(), value)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_DYNAMIC, "Error inserting entry with name reference."); return; } header_table_.InsertEntry(entry->name(), value); } void QpackDecoder::OnInsertWithoutNameReference(absl::string_view name, absl::string_view value) { if (!header_table_.EntryFitsDynamicTableCapacity(name, value)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL, "Error inserting literal entry."); return; } header_table_.InsertEntry(name, value); } void QpackDecoder::OnDuplicate(uint64_t index) { uint64_t absolute_index; if (!QpackEncoderStreamRelativeIndexToAbsoluteIndex( index, header_table_.inserted_entry_count(), &absolute_index)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX, "Invalid relative index."); return; } const QpackEntry* entry = header_table_.LookupEntry( false, absolute_index); if (!entry) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_DUPLICATE_DYNAMIC_ENTRY_NOT_FOUND, "Dynamic table entry not found."); return; } if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(), entry->value())) { OnErrorDetected(QUIC_INTERNAL_ERROR, "Error inserting duplicate entry."); return; } header_table_.InsertEntry(entry->name(), entry->value()); } void QpackDecoder::OnSetDynamicTableCapacity(uint64_t capacity) { if (!header_table_.SetDynamicTableCapacity(capacity)) { OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY, "Error updating dynamic table capacity."); } } void QpackDecoder::OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) { encoder_stream_error_delegate_->OnEncoderStreamError(error_code, error_message); } std::unique_ptr<QpackProgressiveDecoder> QpackDecoder::CreateProgressiveDecoder( QuicStreamId stream_id, QpackProgressiveDecoder::HeadersHandlerInterface* handler) { return std::make_unique<QpackProgressiveDecoder>(stream_id, this, this, &header_table_, handler); } void QpackDecoder::FlushDecoderStream() { decoder_stream_sender_.Flush(); } }
#include "quiche/quic/core/qpack/qpack_decoder.h" #include <algorithm> #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_decoder_test_utils.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::_; using ::testing::Eq; using ::testing::Invoke; using ::testing::Mock; using ::testing::Sequence; using ::testing::StrictMock; using ::testing::Values; namespace quic { namespace test { namespace { const char* const kHeaderAcknowledgement = "\x81"; const uint64_t kMaximumDynamicTableCapacity = 1024; const uint64_t kMaximumBlockedStreams = 1; class QpackDecoderTest : public QuicTestWithParam<FragmentMode> { protected: QpackDecoderTest() : qpack_decoder_(kMaximumDynamicTableCapacity, kMaximumBlockedStreams, &encoder_stream_error_delegate_), fragment_mode_(GetParam()) { qpack_decoder_.set_qpack_stream_sender_delegate( &decoder_stream_sender_delegate_); } ~QpackDecoderTest() override = default; void SetUp() override { ON_CALL(handler_, OnDecodingErrorDetected(_, _)) .WillByDefault(Invoke([this](QuicErrorCode , absl::string_view ) { progressive_decoder_.reset(); })); } void DecodeEncoderStreamData(absl::string_view data) { qpack_decoder_.encoder_stream_receiver()->Decode(data); } std::unique_ptr<QpackProgressiveDecoder> CreateProgressiveDecoder( QuicStreamId stream_id) { return qpack_decoder_.CreateProgressiveDecoder(stream_id, &handler_); } void FlushDecoderStream() { qpack_decoder_.FlushDecoderStream(); } void StartDecoding() { progressive_decoder_ = CreateProgressiveDecoder( 1); } void DecodeData(absl::string_view data) { auto fragment_size_generator = FragmentModeToFragmentSizeGenerator(fragment_mode_); while (progressive_decoder_ && !data.empty()) { size_t fragment_size = std::min(fragment_size_generator(), data.size()); progressive_decoder_->Decode(data.substr(0, fragment_size)); data = data.substr(fragment_size); } } void EndDecoding() { if (progressive_decoder_) { progressive_decoder_->EndHeaderBlock(); } } void DecodeHeaderBlock(absl::string_view data) { StartDecoding(); DecodeData(data); EndDecoding(); } StrictMock<MockEncoderStreamErrorDelegate> encoder_stream_error_delegate_; StrictMock<MockQpackStreamSenderDelegate> decoder_stream_sender_delegate_; StrictMock<MockHeadersHandler> handler_; private: QpackDecoder qpack_decoder_; const FragmentMode fragment_mode_; std::unique_ptr<QpackProgressiveDecoder> progressive_decoder_; }; INSTANTIATE_TEST_SUITE_P(All, QpackDecoderTest, Values(FragmentMode::kSingleChunk, FragmentMode::kOctetByOctet)); TEST_P(QpackDecoderTest, NoPrefix) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Incomplete header data prefix."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("00", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, InvalidPrefix) { StartDecoding(); EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Encoded integer too large."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffffffffff", &input)); DecodeData(input); } TEST_P(QpackDecoderTest, EmptyHeaderBlock) { EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("0000", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, LiteralEntryEmptyName) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq(""), Eq("foo"))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("00002003666f6f", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, LiteralEntryEmptyValue) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq(""))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000023666f6f00", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, LiteralEntryEmptyNameAndValue) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq(""), Eq(""))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("00002000", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, SimpleLiteralEntry) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000023666f6f03626172", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, MultipleLiteralEntries) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))); std::string str(127, 'a'); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foobaar"), absl::string_view(str))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "0000" "23666f6f03626172" "2700666f6f62616172" "7f0061616161616161" "616161616161616161" "6161616161616161616161616161616161616161616161616161616161616161616161" "6161616161616161616161616161616161616161616161616161616161616161616161" "6161616161616161616161616161616161616161616161616161616161616161616161" "616161616161", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, NameLenTooLargeForVarintDecoder) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Encoded integer too large."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000027ffffffffffffffffffff", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, NameLenExceedsLimit) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("String literal too long."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000027ffff7f", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, ValueLenTooLargeForVarintDecoder) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Encoded integer too large."))); std::string input; ASSERT_TRUE( absl::HexStringToBytes("000023666f6f7fffffffffffffffffffff", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, ValueLenExceedsLimit) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("String literal too long."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000023666f6f7fffff7f", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, LineFeedInValue) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ba\nr"))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes("000023666f6f0462610a72", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, IncompleteHeaderBlock) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Incomplete header block."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("00002366", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, HuffmanSimple) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("custom-key"), Eq("custom-value"))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "00002f0125a849e95ba97d7f8925a849e95bb8e8b4bf", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, AlternatingHuffmanNonHuffman) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("custom-key"), Eq("custom-value"))) .Times(4); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "0000" "2f0125a849e95ba97d7f" "8925a849e95bb8e8b4bf" "2703637573746f6d2d6b6579" "0c637573746f6d2d76616c7565" "2f0125a849e95ba97d7f" "0c637573746f6d2d76616c7565" "2703637573746f6d2d6b6579" "8925a849e95bb8e8b4bf", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, HuffmanNameDoesNotHaveEOSPrefix) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error in Huffman-encoded string."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "00002f0125a849e95ba97d7e8925a849e95bb8e8b4bf", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, HuffmanValueDoesNotHaveEOSPrefix) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error in Huffman-encoded string."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "00002f0125a849e95ba97d7f8925a849e95bb8e8b4be", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, HuffmanNameEOSPrefixTooLong) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error in Huffman-encoded string."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "00002f0225a849e95ba97d7fff8925a849e95bb8e8b4bf", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, HuffmanValueEOSPrefixTooLong) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error in Huffman-encoded string."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "00002f0125a849e95ba97d7f8a25a849e95bb8e8b4bfff", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, StaticTable) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("GET"))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("POST"))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("TRACE"))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("accept-encoding"), Eq("gzip, deflate, br"))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("accept-encoding"), Eq("compress"))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("accept-encoding"), Eq(""))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("location"), Eq(""))); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("location"), Eq("foo"))); EXPECT_CALL(handler_, OnDecodingCompleted()); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "0000d1dfccd45f108621e9aec2a11f5c8294e75f000554524143455f1000", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, TooHighStaticTableIndex) { EXPECT_CALL(handler_, OnHeaderDecoded(Eq("x-frame-options"), Eq("sameorigin"))); EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Static table entry not found."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("0000ff23ff24", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, DynamicTable) { std::string input; ASSERT_TRUE(absl::HexStringToBytes( "3fe107" "6294e703626172" "80035a5a5a" "cf8294e7" "01", &input)); DecodeEncoderStreamData(input); Sequence s; EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo"))) .InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s); if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } ASSERT_TRUE(absl::HexStringToBytes( "0500" "83" "82" "81" "80" "41025a5a", &input)); DecodeHeaderBlock(input); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { FlushDecoderStream(); } EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo"))) .InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s); if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } ASSERT_TRUE(absl::HexStringToBytes( "0502" "85" "84" "83" "82" "43025a5a", &input)); DecodeHeaderBlock(input); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { FlushDecoderStream(); } EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo"))) .InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s); EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s); if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))) .InSequence(s); } ASSERT_TRUE(absl::HexStringToBytes( "0582" "80" "10" "11" "12" "01025a5a", &input)); DecodeHeaderBlock(input); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { FlushDecoderStream(); } } TEST_P(QpackDecoderTest, DecreasingDynamicTableCapacityEvictsEntries) { std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input)); DecodeEncoderStreamData(input); EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))); EXPECT_CALL(handler_, OnDecodingCompleted()); EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))); ASSERT_TRUE(absl::HexStringToBytes( "0200" "80", &input)); DecodeHeaderBlock(input); ASSERT_TRUE(absl::HexStringToBytes("3f01", &input)); DecodeEncoderStreamData(input); EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Dynamic table entry already evicted."))); ASSERT_TRUE(absl::HexStringToBytes( "0200" "80", &input)); DecodeHeaderBlock(input); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { FlushDecoderStream(); } } TEST_P(QpackDecoderTest, EncoderStreamErrorEntryTooLarge) { std::string input; EXPECT_CALL( encoder_stream_error_delegate_, OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL, Eq("Error inserting literal entry."))); ASSERT_TRUE(absl::HexStringToBytes("3f03", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, EncoderStreamErrorInvalidStaticTableEntry) { EXPECT_CALL( encoder_stream_error_delegate_, OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY, Eq("Invalid static table entry."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("ff2400", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, EncoderStreamErrorInvalidDynamicTableEntry) { EXPECT_CALL(encoder_stream_error_delegate_, OnEncoderStreamError( QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX, Eq("Invalid relative index."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "3fe107" "6294e703626172" "8100", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, EncoderStreamErrorDuplicateInvalidEntry) { EXPECT_CALL(encoder_stream_error_delegate_, OnEncoderStreamError( QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX, Eq("Invalid relative index."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes( "3fe107" "6294e703626172" "01", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, EncoderStreamErrorTooLargeInteger) { EXPECT_CALL(encoder_stream_error_delegate_, OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, InvalidDynamicEntryWhenBaseIsZero) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Invalid relative index."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes( "0280" "80", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, InvalidNegativeBase) { EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error calculating Base."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("0281", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, InvalidDynamicEntryByRelativeIndex) { std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input)); DecodeEncoderStreamData(input); EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Invalid relative index."))); ASSERT_TRUE(absl::HexStringToBytes( "0200" "81", &input)); DecodeHeaderBlock(input); EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Invalid relative index."))); ASSERT_TRUE(absl::HexStringToBytes( "0200" "4100", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, EvictedDynamicTableEntry) { std::string input; ASSERT_TRUE(absl::HexStringToBytes("3f61", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE(absl::HexStringToBytes("00000000", &input)); DecodeEncoderStreamData(input); EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Dynamic table entry already evicted."))); ASSERT_TRUE(absl::HexStringToBytes( "0500" "82", &input)); DecodeHeaderBlock(input); EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Dynamic table entry already evicted."))); ASSERT_TRUE(absl::HexStringToBytes( "0500" "4200", &input)); DecodeHeaderBlock(input); EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Dynamic table entry already evicted."))); ASSERT_TRUE(absl::HexStringToBytes( "0380" "10", &input)); DecodeHeaderBlock(input); EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Dynamic table entry already evicted."))); ASSERT_TRUE(absl::HexStringToBytes( "0380" "0000", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, TableCapacityMustNotExceedMaximum) { EXPECT_CALL( encoder_stream_error_delegate_, OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY, Eq("Error updating dynamic table capacity."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fe10f", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, SetDynamicTableCapacity) { std::string input; ASSERT_TRUE(absl::HexStringToBytes("3f61", &input)); DecodeEncoderStreamData(input); } TEST_P(QpackDecoderTest, InvalidEncodedRequiredInsertCount) { EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error decoding Required Insert Count."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("4100", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, DataAfterInvalidEncodedRequiredInsertCount) { EXPECT_CALL(handler_, OnDecodingErrorDetected( QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Error decoding Required Insert Count."))); std::string input; ASSERT_TRUE(absl::HexStringToBytes("410000", &input)); DecodeHeaderBlock(input); } TEST_P(QpackDecoderTest, WrappedRequiredInsertCount) { std::string input; ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input)); DecodeEncoderStreamData(input); ASSERT_TRUE( absl::HexStringToBytes("6294e7" "7fd903", &input)); DecodeEncoderStreamData(input); std::string header_value(600, 'Z'); DecodeEncoderStreamData(header_value); DecodeEncoderStreamDat
289
cpp
google/quiche
qpack_instruction_decoder
quiche/quic/core/qpack/qpack_instruction_decoder.cc
quiche/quic/core/qpack/qpack_instruction_decoder_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_INSTRUCTION_DECODER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_INSTRUCTION_DECODER_H_ #include <cstddef> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h" #include "quiche/http2/hpack/varint/hpack_varint_decoder.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackInstructionDecoder { public: enum class ErrorCode { INTEGER_TOO_LARGE, STRING_LITERAL_TOO_LONG, HUFFMAN_ENCODING_ERROR, }; class QUICHE_EXPORT Delegate { public: virtual ~Delegate() = default; virtual bool OnInstructionDecoded(const QpackInstruction* instruction) = 0; virtual void OnInstructionDecodingError( ErrorCode error_code, absl::string_view error_message) = 0; }; QpackInstructionDecoder(const QpackLanguage* language, Delegate* delegate); QpackInstructionDecoder() = delete; QpackInstructionDecoder(const QpackInstructionDecoder&) = delete; QpackInstructionDecoder& operator=(const QpackInstructionDecoder&) = delete; bool Decode(absl::string_view data); bool AtInstructionBoundary() const; bool s_bit() const { return s_bit_; } uint64_t varint() const { return varint_; } uint64_t varint2() const { return varint2_; } const std::string& name() const { return name_; } const std::string& value() const { return value_; } private: enum class State { kStartInstruction, kStartField, kReadBit, kVarintStart, kVarintResume, kVarintDone, kReadString, kReadStringDone }; bool DoStartInstruction(absl::string_view data); bool DoStartField(); bool DoReadBit(absl::string_view data); bool DoVarintStart(absl::string_view data, size_t* bytes_consumed); bool DoVarintResume(absl::string_view data, size_t* bytes_consumed); bool DoVarintDone(); bool DoReadString(absl::string_view data, size_t* bytes_consumed); bool DoReadStringDone(); const QpackInstruction* LookupOpcode(uint8_t byte) const; void OnError(ErrorCode error_code, absl::string_view error_message); const QpackLanguage* const language_; Delegate* const delegate_; bool s_bit_; uint64_t varint_; uint64_t varint2_; std::string name_; std::string value_; bool is_huffman_encoded_; size_t string_length_; http2::HpackVarintDecoder varint_decoder_; http2::HpackHuffmanDecoder huffman_decoder_; bool error_detected_; State state_; const QpackInstruction* instruction_; QpackInstructionFields::const_iterator field_; }; } #endif #include "quiche/quic/core/qpack/qpack_instruction_decoder.h" #include <algorithm> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const size_t kStringLiteralLengthLimit = 1024 * 1024; } QpackInstructionDecoder::QpackInstructionDecoder(const QpackLanguage* language, Delegate* delegate) : language_(language), delegate_(delegate), s_bit_(false), varint_(0), varint2_(0), is_huffman_encoded_(false), string_length_(0), error_detected_(false), state_(State::kStartInstruction) {} bool QpackInstructionDecoder::Decode(absl::string_view data) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(!error_detected_); while (true) { bool success = true; size_t bytes_consumed = 0; switch (state_) { case State::kStartInstruction: success = DoStartInstruction(data); break; case State::kStartField: success = DoStartField(); break; case State::kReadBit: success = DoReadBit(data); break; case State::kVarintStart: success = DoVarintStart(data, &bytes_consumed); break; case State::kVarintResume: success = DoVarintResume(data, &bytes_consumed); break; case State::kVarintDone: success = DoVarintDone(); break; case State::kReadString: success = DoReadString(data, &bytes_consumed); break; case State::kReadStringDone: success = DoReadStringDone(); break; } if (!success) { return false; } QUICHE_DCHECK(!error_detected_); QUICHE_DCHECK_LE(bytes_consumed, data.size()); data = absl::string_view(data.data() + bytes_consumed, data.size() - bytes_consumed); if (data.empty() && (state_ != State::kStartField) && (state_ != State::kVarintDone) && (state_ != State::kReadStringDone)) { return true; } } } bool QpackInstructionDecoder::AtInstructionBoundary() const { return state_ == State::kStartInstruction; } bool QpackInstructionDecoder::DoStartInstruction(absl::string_view data) { QUICHE_DCHECK(!data.empty()); instruction_ = LookupOpcode(data[0]); field_ = instruction_->fields.begin(); state_ = State::kStartField; return true; } bool QpackInstructionDecoder::DoStartField() { if (field_ == instruction_->fields.end()) { if (!delegate_->OnInstructionDecoded(instruction_)) { return false; } state_ = State::kStartInstruction; return true; } switch (field_->type) { case QpackInstructionFieldType::kSbit: case QpackInstructionFieldType::kName: case QpackInstructionFieldType::kValue: state_ = State::kReadBit; return true; case QpackInstructionFieldType::kVarint: case QpackInstructionFieldType::kVarint2: state_ = State::kVarintStart; return true; default: QUIC_BUG(quic_bug_10767_1) << "Invalid field type."; return false; } } bool QpackInstructionDecoder::DoReadBit(absl::string_view data) { QUICHE_DCHECK(!data.empty()); switch (field_->type) { case QpackInstructionFieldType::kSbit: { const uint8_t bitmask = field_->param; s_bit_ = (data[0] & bitmask) == bitmask; ++field_; state_ = State::kStartField; return true; } case QpackInstructionFieldType::kName: case QpackInstructionFieldType::kValue: { const uint8_t prefix_length = field_->param; QUICHE_DCHECK_GE(7, prefix_length); const uint8_t bitmask = 1 << prefix_length; is_huffman_encoded_ = (data[0] & bitmask) == bitmask; state_ = State::kVarintStart; return true; } default: QUIC_BUG(quic_bug_10767_2) << "Invalid field type."; return false; } } bool QpackInstructionDecoder::DoVarintStart(absl::string_view data, size_t* bytes_consumed) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint || field_->type == QpackInstructionFieldType::kVarint2 || field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); http2::DecodeBuffer buffer(data.data() + 1, data.size() - 1); http2::DecodeStatus status = varint_decoder_.Start(data[0], field_->param, &buffer); *bytes_consumed = 1 + buffer.Offset(); switch (status) { case http2::DecodeStatus::kDecodeDone: state_ = State::kVarintDone; return true; case http2::DecodeStatus::kDecodeInProgress: state_ = State::kVarintResume; return true; case http2::DecodeStatus::kDecodeError: OnError(ErrorCode::INTEGER_TOO_LARGE, "Encoded integer too large."); return false; default: QUIC_BUG(quic_bug_10767_3) << "Unknown decode status " << status; return false; } } bool QpackInstructionDecoder::DoVarintResume(absl::string_view data, size_t* bytes_consumed) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint || field_->type == QpackInstructionFieldType::kVarint2 || field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); http2::DecodeBuffer buffer(data); http2::DecodeStatus status = varint_decoder_.Resume(&buffer); *bytes_consumed = buffer.Offset(); switch (status) { case http2::DecodeStatus::kDecodeDone: state_ = State::kVarintDone; return true; case http2::DecodeStatus::kDecodeInProgress: QUICHE_DCHECK_EQ(*bytes_consumed, data.size()); QUICHE_DCHECK(buffer.Empty()); return true; case http2::DecodeStatus::kDecodeError: OnError(ErrorCode::INTEGER_TOO_LARGE, "Encoded integer too large."); return false; default: QUIC_BUG(quic_bug_10767_4) << "Unknown decode status " << status; return false; } } bool QpackInstructionDecoder::DoVarintDone() { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint || field_->type == QpackInstructionFieldType::kVarint2 || field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); if (field_->type == QpackInstructionFieldType::kVarint) { varint_ = varint_decoder_.value(); ++field_; state_ = State::kStartField; return true; } if (field_->type == QpackInstructionFieldType::kVarint2) { varint2_ = varint_decoder_.value(); ++field_; state_ = State::kStartField; return true; } string_length_ = varint_decoder_.value(); if (string_length_ > kStringLiteralLengthLimit) { OnError(ErrorCode::STRING_LITERAL_TOO_LONG, "String literal too long."); return false; } std::string* const string = (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_; string->clear(); if (string_length_ == 0) { ++field_; state_ = State::kStartField; return true; } string->reserve(string_length_); state_ = State::kReadString; return true; } bool QpackInstructionDecoder::DoReadString(absl::string_view data, size_t* bytes_consumed) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); std::string* const string = (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_; QUICHE_DCHECK_LT(string->size(), string_length_); *bytes_consumed = std::min(string_length_ - string->size(), data.size()); string->append(data.data(), *bytes_consumed); QUICHE_DCHECK_LE(string->size(), string_length_); if (string->size() == string_length_) { state_ = State::kReadStringDone; } return true; } bool QpackInstructionDecoder::DoReadStringDone() { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); std::string* const string = (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_; QUICHE_DCHECK_EQ(string->size(), string_length_); if (is_huffman_encoded_) { huffman_decoder_.Reset(); std::string decoded_value; huffman_decoder_.Decode(*string, &decoded_value); if (!huffman_decoder_.InputProperlyTerminated()) { OnError(ErrorCode::HUFFMAN_ENCODING_ERROR, "Error in Huffman-encoded string."); return false; } *string = std::move(decoded_value); } ++field_; state_ = State::kStartField; return true; } const QpackInstruction* QpackInstructionDecoder::LookupOpcode( uint8_t byte) const { for (const auto* instruction : *language_) { if ((byte & instruction->opcode.mask) == instruction->opcode.value) { return instruction; } } QUICHE_DCHECK(false); return nullptr; } void QpackInstructionDecoder::OnError(ErrorCode error_code, absl::string_view error_message) { QUICHE_DCHECK(!error_detected_); error_detected_ = true; delegate_->OnInstructionDecodingError(error_code, error_message); } }
#include "quiche/quic/core/qpack/qpack_instruction_decoder.h" #include <algorithm> #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::_; using ::testing::Eq; using ::testing::Expectation; using ::testing::InvokeWithoutArgs; using ::testing::Return; using ::testing::StrictMock; using ::testing::Values; namespace quic { namespace test { namespace { const QpackInstruction* TestInstruction1() { static const QpackInstruction* const instruction = new QpackInstruction{QpackInstructionOpcode{0x00, 0x80}, {{QpackInstructionFieldType::kSbit, 0x40}, {QpackInstructionFieldType::kVarint, 6}, {QpackInstructionFieldType::kVarint2, 8}}}; return instruction; } const QpackInstruction* TestInstruction2() { static const QpackInstruction* const instruction = new QpackInstruction{QpackInstructionOpcode{0x80, 0x80}, {{QpackInstructionFieldType::kName, 6}, {QpackInstructionFieldType::kValue, 7}}}; return instruction; } const QpackLanguage* TestLanguage() { static const QpackLanguage* const language = new QpackLanguage{TestInstruction1(), TestInstruction2()}; return language; } class MockDelegate : public QpackInstructionDecoder::Delegate { public: MockDelegate() { ON_CALL(*this, OnInstructionDecoded(_)).WillByDefault(Return(true)); } MockDelegate(const MockDelegate&) = delete; MockDelegate& operator=(const MockDelegate&) = delete; ~MockDelegate() override = default; MOCK_METHOD(bool, OnInstructionDecoded, (const QpackInstruction*), (override)); MOCK_METHOD(void, OnInstructionDecodingError, (QpackInstructionDecoder::ErrorCode error_code, absl::string_view error_message), (override)); }; class QpackInstructionDecoderTest : public QuicTestWithParam<FragmentMode> { protected: QpackInstructionDecoderTest() : decoder_(std::make_unique<QpackInstructionDecoder>(TestLanguage(), &delegate_)), fragment_mode_(GetParam()) {} ~QpackInstructionDecoderTest() override = default; void SetUp() override { ON_CALL(delegate_, OnInstructionDecodingError(_, _)) .WillByDefault(InvokeWithoutArgs([this]() { decoder_.reset(); })); } void DecodeInstruction(absl::string_view data) { EXPECT_TRUE(decoder_->AtInstructionBoundary()); FragmentSizeGenerator fragment_size_generator = FragmentModeToFragmentSizeGenerator(fragment_mode_); while (!data.empty()) { size_t fragment_size = std::min(fragment_size_generator(), data.size()); bool success = decoder_->Decode(data.substr(0, fragment_size)); if (!decoder_) { EXPECT_FALSE(success); return; } EXPECT_TRUE(success); data = data.substr(fragment_size); if (!data.empty()) { EXPECT_FALSE(decoder_->AtInstructionBoundary()); } } EXPECT_TRUE(decoder_->AtInstructionBoundary()); } StrictMock<MockDelegate> delegate_; std::unique_ptr<QpackInstructionDecoder> decoder_; private: const FragmentMode fragment_mode_; }; INSTANTIATE_TEST_SUITE_P(All, QpackInstructionDecoderTest, Values(FragmentMode::kSingleChunk, FragmentMode::kOctetByOctet)); TEST_P(QpackInstructionDecoderTest, SBitAndVarint2) { std::string encoded_data; EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1())); ASSERT_TRUE(absl::HexStringToBytes("7f01ff65", &encoded_data)); DecodeInstruction(encoded_data); EXPECT_TRUE(decoder_->s_bit()); EXPECT_EQ(64u, decoder_->varint()); EXPECT_EQ(356u, decoder_->varint2()); EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1())); ASSERT_TRUE(absl::HexStringToBytes("05c8", &encoded_data)); DecodeInstruction(encoded_data); EXPECT_FALSE(decoder_->s_bit()); EXPECT_EQ(5u, decoder_->varint()); EXPECT_EQ(200u, decoder_->varint2()); } TEST_P(QpackInstructionDecoderTest, NameAndValue) { std::string encoded_data; EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2())); ASSERT_TRUE(absl::HexStringToBytes("83666f6f03626172", &encoded_data)); DecodeInstruction(encoded_data); EXPECT_EQ("foo", decoder_->name()); EXPECT_EQ("bar", decoder_->value()); EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2())); ASSERT_TRUE(absl::HexStringToBytes("8000", &encoded_data)); DecodeInstruction(encoded_data); EXPECT_EQ("", decoder_->name()); EXPECT_EQ("", decoder_->value()); EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2())); ASSERT_TRUE(absl::HexStringToBytes("c294e7838c767f", &encoded_data)); DecodeInstruction(encoded_data); EXPECT_EQ("foo", decoder_->name()); EXPECT_EQ("bar", decoder_->value()); } TEST_P(QpackInstructionDecoderTest, InvalidHuffmanEncoding) { std::string encoded_data; EXPECT_CALL(delegate_, OnInstructionDecodingError( QpackInstructionDecoder::ErrorCode::HUFFMAN_ENCODING_ERROR, Eq("Error in Huffman-encoded string."))); ASSERT_TRUE(absl::HexStringToBytes("c1ff", &encoded_data)); DecodeInstruction(encoded_data); } TEST_P(QpackInstructionDecoderTest, InvalidVarintEncoding) { std::string encoded_data; EXPECT_CALL(delegate_, OnInstructionDecodingError( QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &encoded_data)); DecodeInstruction(encoded_data); } TEST_P(QpackInstructionDecoderTest, StringLiteralTooLong) { std::string encoded_data; EXPECT_CALL(delegate_, OnInstructionDecodingError( QpackInstructionDecoder::ErrorCode::STRING_LITERAL_TOO_LONG, Eq("String literal too long."))); ASSERT_TRUE(absl::HexStringToBytes("bfffff7f", &encoded_data)); DecodeInstruction(encoded_data); } TEST_P(QpackInstructionDecoderTest, DelegateSignalsError) { Expectation first_call = EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1())) .WillOnce(InvokeWithoutArgs([this]() -> bool { EXPECT_EQ(1u, decoder_->varint()); return true; })); EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1())) .After(first_call) .WillOnce(InvokeWithoutArgs([this]() -> bool { EXPECT_EQ(2u, decoder_->varint()); return false; })); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("01000200030004000500", &encoded_data)); EXPECT_FALSE(decoder_->Decode(encoded_data)); } TEST_P(QpackInstructionDecoderTest, DelegateSignalsErrorAndDestroysDecoder) { EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1())) .WillOnce(InvokeWithoutArgs([this]() -> bool { EXPECT_EQ(1u, decoder_->varint()); decoder_.reset(); return false; })); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("0100", &encoded_data)); DecodeInstruction(encoded_data); } } } }
290
cpp
google/quiche
qpack_receive_stream
quiche/quic/core/qpack/qpack_receive_stream.cc
quiche/quic/core/qpack/qpack_receive_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_RECEIVE_STREAM_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_RECEIVE_STREAM_H_ #include "quiche/quic/core/qpack/qpack_stream_receiver.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QuicSession; class QUICHE_EXPORT QpackReceiveStream : public QuicStream { public: QpackReceiveStream(PendingStream* pending, QuicSession* session, QpackStreamReceiver* receiver); QpackReceiveStream(const QpackReceiveStream&) = delete; QpackReceiveStream& operator=(const QpackReceiveStream&) = delete; ~QpackReceiveStream() override = default; void OnStreamReset(const QuicRstStreamFrame& frame) override; void OnDataAvailable() override; QuicStreamOffset NumBytesConsumed() const { return sequencer()->NumBytesConsumed(); } private: QpackStreamReceiver* receiver_; }; } #endif #include "quiche/quic/core/qpack/qpack_receive_stream.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_session.h" namespace quic { QpackReceiveStream::QpackReceiveStream(PendingStream* pending, QuicSession* session, QpackStreamReceiver* receiver) : QuicStream(pending, session, true), receiver_(receiver) {} void QpackReceiveStream::OnStreamReset(const QuicRstStreamFrame& ) { stream_delegate()->OnStreamError( QUIC_HTTP_CLOSED_CRITICAL_STREAM, "RESET_STREAM received for QPACK receive stream"); } void QpackReceiveStream::OnDataAvailable() { iovec iov; while (!reading_stopped() && sequencer()->GetReadableRegion(&iov)) { QUICHE_DCHECK(!sequencer()->IsClosed()); receiver_->Decode(absl::string_view( reinterpret_cast<const char*>(iov.iov_base), iov.iov_len)); sequencer()->MarkConsumed(iov.iov_len); } } }
#include "quiche/quic/core/qpack/qpack_receive_stream.h" #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::StrictMock; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: version: " << ParsedQuicVersionToString(version) << ", perspective: " << perspective; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} ParsedQuicVersion version; Perspective perspective; }; std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (const auto& version : AllSupportedVersions()) { if (!VersionUsesHttp3(version.transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(version, p); } } return params; } class QpackReceiveStreamTest : public QuicTestWithParam<TestParams> { public: QpackReceiveStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), SupportedVersions(GetParam().version))), session_(connection_) { EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); EXPECT_CALL( static_cast<const MockQuicCryptoStream&>(*session_.GetCryptoStream()), encryption_established()) .WillRepeatedly(testing::Return(true)); QuicStreamId id = perspective() == Perspective::IS_SERVER ? GetNthClientInitiatedUnidirectionalStreamId( session_.transport_version(), 3) : GetNthServerInitiatedUnidirectionalStreamId( session_.transport_version(), 3); char type[] = {0x03}; QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1)); session_.OnStreamFrame(data1); qpack_receive_stream_ = QuicSpdySessionPeer::GetQpackDecoderReceiveStream(&session_); } Perspective perspective() const { return GetParam().perspective; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QpackReceiveStream* qpack_receive_stream_; }; INSTANTIATE_TEST_SUITE_P(Tests, QpackReceiveStreamTest, ::testing::ValuesIn(GetTestParams())); TEST_P(QpackReceiveStreamTest, ResetQpackReceiveStream) { EXPECT_TRUE(qpack_receive_stream_->is_static()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, qpack_receive_stream_->id(), QUIC_STREAM_CANCELLED, 1234); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _)); qpack_receive_stream_->OnStreamReset(rst_frame); } } } }
291
cpp
google/quiche
qpack_blocking_manager
quiche/quic/core/qpack/qpack_blocking_manager.cc
quiche/quic/core/qpack/qpack_blocking_manager_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_BLOCKING_MANAGER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_BLOCKING_MANAGER_H_ #include <cstdint> #include <map> #include <set> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QpackBlockingManagerPeer; } class QUICHE_EXPORT QpackBlockingManager { public: using IndexSet = std::multiset<uint64_t>; QpackBlockingManager(); bool OnHeaderAcknowledgement(QuicStreamId stream_id); void OnStreamCancellation(QuicStreamId stream_id); bool OnInsertCountIncrement(uint64_t increment); void OnHeaderBlockSent(QuicStreamId stream_id, IndexSet indices); bool blocking_allowed_on_stream(QuicStreamId stream_id, uint64_t maximum_blocked_streams) const; uint64_t smallest_blocking_index() const; uint64_t known_received_count() const { return known_received_count_; } static uint64_t RequiredInsertCount(const IndexSet& indices); private: friend test::QpackBlockingManagerPeer; using HeaderBlocksForStream = std::list<IndexSet>; using HeaderBlocks = absl::flat_hash_map<QuicStreamId, HeaderBlocksForStream>; void IncreaseReferenceCounts(const IndexSet& indices); void DecreaseReferenceCounts(const IndexSet& indices); HeaderBlocks header_blocks_; std::map<uint64_t, uint64_t> entry_reference_counts_; uint64_t known_received_count_; }; } #endif #include "quiche/quic/core/qpack/qpack_blocking_manager.h" #include <limits> #include <utility> namespace quic { QpackBlockingManager::QpackBlockingManager() : known_received_count_(0) {} bool QpackBlockingManager::OnHeaderAcknowledgement(QuicStreamId stream_id) { auto it = header_blocks_.find(stream_id); if (it == header_blocks_.end()) { return false; } QUICHE_DCHECK(!it->second.empty()); const IndexSet& indices = it->second.front(); QUICHE_DCHECK(!indices.empty()); const uint64_t required_index_count = RequiredInsertCount(indices); if (known_received_count_ < required_index_count) { known_received_count_ = required_index_count; } DecreaseReferenceCounts(indices); it->second.pop_front(); if (it->second.empty()) { header_blocks_.erase(it); } return true; } void QpackBlockingManager::OnStreamCancellation(QuicStreamId stream_id) { auto it = header_blocks_.find(stream_id); if (it == header_blocks_.end()) { return; } for (const IndexSet& indices : it->second) { DecreaseReferenceCounts(indices); } header_blocks_.erase(it); } bool QpackBlockingManager::OnInsertCountIncrement(uint64_t increment) { if (increment > std::numeric_limits<uint64_t>::max() - known_received_count_) { return false; } known_received_count_ += increment; return true; } void QpackBlockingManager::OnHeaderBlockSent(QuicStreamId stream_id, IndexSet indices) { QUICHE_DCHECK(!indices.empty()); IncreaseReferenceCounts(indices); header_blocks_[stream_id].push_back(std::move(indices)); } bool QpackBlockingManager::blocking_allowed_on_stream( QuicStreamId stream_id, uint64_t maximum_blocked_streams) const { if (header_blocks_.size() + 1 <= maximum_blocked_streams) { return true; } if (maximum_blocked_streams == 0) { return false; } uint64_t blocked_stream_count = 0; for (const auto& header_blocks_for_stream : header_blocks_) { for (const IndexSet& indices : header_blocks_for_stream.second) { if (RequiredInsertCount(indices) > known_received_count_) { if (header_blocks_for_stream.first == stream_id) { return true; } ++blocked_stream_count; if (blocked_stream_count + 1 > maximum_blocked_streams) { return false; } break; } } } return true; } uint64_t QpackBlockingManager::smallest_blocking_index() const { return entry_reference_counts_.empty() ? std::numeric_limits<uint64_t>::max() : entry_reference_counts_.begin()->first; } uint64_t QpackBlockingManager::RequiredInsertCount(const IndexSet& indices) { return *indices.rbegin() + 1; } void QpackBlockingManager::IncreaseReferenceCounts(const IndexSet& indices) { for (const uint64_t index : indices) { auto it = entry_reference_counts_.lower_bound(index); if (it != entry_reference_counts_.end() && it->first == index) { ++it->second; } else { entry_reference_counts_.insert(it, {index, 1}); } } } void QpackBlockingManager::DecreaseReferenceCounts(const IndexSet& indices) { for (const uint64_t index : indices) { auto it = entry_reference_counts_.find(index); QUICHE_DCHECK(it != entry_reference_counts_.end()); QUICHE_DCHECK_NE(0u, it->second); if (it->second == 1) { entry_reference_counts_.erase(it); } else { --it->second; } } } }
#include "quiche/quic/core/qpack/qpack_blocking_manager.h" #include <limits> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QpackBlockingManagerPeer { public: static bool stream_is_blocked(const QpackBlockingManager* manager, QuicStreamId stream_id) { for (const auto& header_blocks_for_stream : manager->header_blocks_) { if (header_blocks_for_stream.first != stream_id) { continue; } for (const auto& indices : header_blocks_for_stream.second) { if (QpackBlockingManager::RequiredInsertCount(indices) > manager->known_received_count_) { return true; } } } return false; } }; namespace { class QpackBlockingManagerTest : public QuicTest { protected: QpackBlockingManagerTest() = default; ~QpackBlockingManagerTest() override = default; bool stream_is_blocked(QuicStreamId stream_id) const { return QpackBlockingManagerPeer::stream_is_blocked(&manager_, stream_id); } QpackBlockingManager manager_; }; TEST_F(QpackBlockingManagerTest, Empty) { EXPECT_EQ(0u, manager_.known_received_count()); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); EXPECT_FALSE(manager_.OnHeaderAcknowledgement(0)); EXPECT_FALSE(manager_.OnHeaderAcknowledgement(1)); } TEST_F(QpackBlockingManagerTest, NotBlockedByInsertCountIncrement) { EXPECT_TRUE(manager_.OnInsertCountIncrement(2)); manager_.OnHeaderBlockSent(0, {1, 0}); EXPECT_FALSE(stream_is_blocked(0)); } TEST_F(QpackBlockingManagerTest, UnblockedByInsertCountIncrement) { manager_.OnHeaderBlockSent(0, {1, 0}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_TRUE(manager_.OnInsertCountIncrement(2)); EXPECT_FALSE(stream_is_blocked(0)); } TEST_F(QpackBlockingManagerTest, NotBlockedByHeaderAcknowledgement) { manager_.OnHeaderBlockSent(0, {2, 1, 1}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_FALSE(stream_is_blocked(0)); manager_.OnHeaderBlockSent(1, {2, 2}); EXPECT_FALSE(stream_is_blocked(1)); } TEST_F(QpackBlockingManagerTest, UnblockedByHeaderAcknowledgement) { manager_.OnHeaderBlockSent(0, {2, 1, 1}); manager_.OnHeaderBlockSent(1, {2, 2}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_TRUE(stream_is_blocked(1)); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_FALSE(stream_is_blocked(0)); EXPECT_FALSE(stream_is_blocked(1)); } TEST_F(QpackBlockingManagerTest, KnownReceivedCount) { EXPECT_EQ(0u, manager_.known_received_count()); manager_.OnHeaderBlockSent(0, {0}); EXPECT_EQ(0u, manager_.known_received_count()); manager_.OnHeaderBlockSent(1, {1}); EXPECT_EQ(0u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(1u, manager_.known_received_count()); manager_.OnHeaderBlockSent(2, {5}); EXPECT_EQ(1u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1)); EXPECT_EQ(2u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnInsertCountIncrement(2)); EXPECT_EQ(4u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(2)); EXPECT_EQ(6u, manager_.known_received_count()); manager_.OnStreamCancellation(0); EXPECT_EQ(6u, manager_.known_received_count()); manager_.OnHeaderBlockSent(0, {3}); EXPECT_EQ(6u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(6u, manager_.known_received_count()); manager_.OnHeaderBlockSent(1, {5}); EXPECT_EQ(6u, manager_.known_received_count()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1)); EXPECT_EQ(6u, manager_.known_received_count()); } TEST_F(QpackBlockingManagerTest, SmallestBlockingIndex) { EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(0, {0}); EXPECT_EQ(0u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(1, {2}); EXPECT_EQ(0u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(2u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(1, {1}); EXPECT_EQ(1u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1)); EXPECT_EQ(1u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnInsertCountIncrement(2)); EXPECT_EQ(1u, manager_.smallest_blocking_index()); manager_.OnStreamCancellation(1); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); } TEST_F(QpackBlockingManagerTest, HeaderAcknowledgementsOnSingleStream) { EXPECT_EQ(0u, manager_.known_received_count()); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(0, {2, 1, 1}); EXPECT_EQ(0u, manager_.known_received_count()); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(1u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(0, {1, 0}); EXPECT_EQ(0u, manager_.known_received_count()); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(0u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(3u, manager_.known_received_count()); EXPECT_FALSE(stream_is_blocked(0)); EXPECT_EQ(0u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(0, {3}); EXPECT_EQ(3u, manager_.known_received_count()); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(0u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(3u, manager_.known_received_count()); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(3u, manager_.smallest_blocking_index()); EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0)); EXPECT_EQ(4u, manager_.known_received_count()); EXPECT_FALSE(stream_is_blocked(0)); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); EXPECT_FALSE(manager_.OnHeaderAcknowledgement(0)); } TEST_F(QpackBlockingManagerTest, CancelStream) { manager_.OnHeaderBlockSent(0, {3}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(3u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(0, {2}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_EQ(2u, manager_.smallest_blocking_index()); manager_.OnHeaderBlockSent(1, {4}); EXPECT_TRUE(stream_is_blocked(0)); EXPECT_TRUE(stream_is_blocked(1)); EXPECT_EQ(2u, manager_.smallest_blocking_index()); manager_.OnStreamCancellation(0); EXPECT_FALSE(stream_is_blocked(0)); EXPECT_TRUE(stream_is_blocked(1)); EXPECT_EQ(4u, manager_.smallest_blocking_index()); manager_.OnStreamCancellation(1); EXPECT_FALSE(stream_is_blocked(0)); EXPECT_FALSE(stream_is_blocked(1)); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), manager_.smallest_blocking_index()); } TEST_F(QpackBlockingManagerTest, BlockingAllowedOnStream) { const QuicStreamId kStreamId1 = 1; const QuicStreamId kStreamId2 = 2; const QuicStreamId kStreamId3 = 3; EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 0)); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 0)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1)); manager_.OnHeaderBlockSent(kStreamId1, {0}); manager_.OnHeaderBlockSent(kStreamId1, {1}); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1)); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 1)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2)); manager_.OnHeaderBlockSent(kStreamId2, {2}); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2)); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId3, 2)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId3, 3)); manager_.OnHeaderAcknowledgement(kStreamId1); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2)); manager_.OnHeaderAcknowledgement(kStreamId1); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 1)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2)); manager_.OnHeaderAcknowledgement(kStreamId2); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 0)); EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 0)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1)); EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1)); } TEST_F(QpackBlockingManagerTest, InsertCountIncrementOverflow) { EXPECT_TRUE(manager_.OnInsertCountIncrement(10)); EXPECT_EQ(10u, manager_.known_received_count()); EXPECT_FALSE(manager_.OnInsertCountIncrement( std::numeric_limits<uint64_t>::max() - 5)); } } } }
292
cpp
google/quiche
qpack_required_insert_count
quiche/quic/core/qpack/qpack_required_insert_count.cc
quiche/quic/core/qpack/qpack_required_insert_count_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_REQUIRED_INSERT_COUNT_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_REQUIRED_INSERT_COUNT_H_ #include <cstdint> #include "quiche/quic/platform/api/quic_export.h" namespace quic { QUICHE_EXPORT uint64_t QpackEncodeRequiredInsertCount( uint64_t required_insert_count, uint64_t max_entries); QUICHE_EXPORT bool QpackDecodeRequiredInsertCount( uint64_t encoded_required_insert_count, uint64_t max_entries, uint64_t total_number_of_inserts, uint64_t* required_insert_count); } #endif #include "quiche/quic/core/qpack/qpack_required_insert_count.h" #include <limits> #include "quiche/quic/platform/api/quic_logging.h" namespace quic { uint64_t QpackEncodeRequiredInsertCount(uint64_t required_insert_count, uint64_t max_entries) { if (required_insert_count == 0) { return 0; } return required_insert_count % (2 * max_entries) + 1; } bool QpackDecodeRequiredInsertCount(uint64_t encoded_required_insert_count, uint64_t max_entries, uint64_t total_number_of_inserts, uint64_t* required_insert_count) { if (encoded_required_insert_count == 0) { *required_insert_count = 0; return true; } QUICHE_DCHECK_LE(max_entries, std::numeric_limits<uint64_t>::max() / 32); if (encoded_required_insert_count > 2 * max_entries) { return false; } *required_insert_count = encoded_required_insert_count - 1; QUICHE_DCHECK_LT(*required_insert_count, std::numeric_limits<uint64_t>::max() / 16); uint64_t current_wrapped = total_number_of_inserts % (2 * max_entries); QUICHE_DCHECK_LT(current_wrapped, std::numeric_limits<uint64_t>::max() / 16); if (current_wrapped >= *required_insert_count + max_entries) { *required_insert_count += 2 * max_entries; } else if (current_wrapped + max_entries < *required_insert_count) { current_wrapped += 2 * max_entries; } if (*required_insert_count > std::numeric_limits<uint64_t>::max() - total_number_of_inserts) { return false; } *required_insert_count += total_number_of_inserts; if (current_wrapped >= *required_insert_count) { return false; } *required_insert_count -= current_wrapped; return true; } }
#include "quiche/quic/core/qpack/qpack_required_insert_count.h" #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { TEST(QpackRequiredInsertCountTest, QpackEncodeRequiredInsertCount) { EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 0)); EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 8)); EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 1024)); EXPECT_EQ(2u, QpackEncodeRequiredInsertCount(1, 8)); EXPECT_EQ(5u, QpackEncodeRequiredInsertCount(20, 8)); EXPECT_EQ(7u, QpackEncodeRequiredInsertCount(106, 10)); } struct { uint64_t required_insert_count; uint64_t max_entries; uint64_t total_number_of_inserts; } kTestData[] = { {0, 0, 0}, {0, 100, 0}, {0, 100, 500}, {15, 100, 25}, {20, 100, 10}, {90, 100, 110}, {234, 100, 180}, {5678, 100, 5701}, {401, 100, 500}, {600, 100, 500}}; TEST(QpackRequiredInsertCountTest, QpackDecodeRequiredInsertCount) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) { const uint64_t required_insert_count = kTestData[i].required_insert_count; const uint64_t max_entries = kTestData[i].max_entries; const uint64_t total_number_of_inserts = kTestData[i].total_number_of_inserts; if (required_insert_count != 0) { ASSERT_LT(0u, max_entries) << i; ASSERT_LT(total_number_of_inserts, required_insert_count + max_entries) << i; ASSERT_LE(required_insert_count, total_number_of_inserts + max_entries) << i; } uint64_t encoded_required_insert_count = QpackEncodeRequiredInsertCount(required_insert_count, max_entries); uint64_t decoded_required_insert_count = required_insert_count + 1; EXPECT_TRUE(QpackDecodeRequiredInsertCount( encoded_required_insert_count, max_entries, total_number_of_inserts, &decoded_required_insert_count)) << i; EXPECT_EQ(decoded_required_insert_count, required_insert_count) << i; } } struct { uint64_t encoded_required_insert_count; uint64_t max_entries; uint64_t total_number_of_inserts; } kInvalidTestData[] = { {1, 0, 0}, {9, 0, 0}, {1, 10, 2}, {18, 10, 2}, {400, 100, 500}, {601, 100, 500}}; TEST(QpackRequiredInsertCountTest, DecodeRequiredInsertCountError) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kInvalidTestData); ++i) { uint64_t decoded_required_insert_count = 0; EXPECT_FALSE(QpackDecodeRequiredInsertCount( kInvalidTestData[i].encoded_required_insert_count, kInvalidTestData[i].max_entries, kInvalidTestData[i].total_number_of_inserts, &decoded_required_insert_count)) << i; } } } } }
293
cpp
google/quiche
qpack_header_table
quiche/quic/core/qpack/qpack_header_table.cc
quiche/quic/core/qpack/qpack_header_table_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_HEADER_TABLE_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_HEADER_TABLE_H_ #include <cstdint> #include <deque> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/spdy/core/hpack/hpack_entry.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" namespace quic { using QpackEntry = spdy::HpackEntry; using QpackLookupEntry = spdy::HpackLookupEntry; constexpr size_t kQpackEntrySizeOverhead = spdy::kHpackEntrySizeOverhead; using QpackEncoderDynamicTable = quiche::QuicheCircularDeque<std::unique_ptr<QpackEntry>>; using QpackDecoderDynamicTable = quiche::QuicheCircularDeque<QpackEntry>; template <typename DynamicEntryTable> class QUICHE_EXPORT QpackHeaderTableBase { public: QpackHeaderTableBase(); QpackHeaderTableBase(const QpackHeaderTableBase&) = delete; QpackHeaderTableBase& operator=(const QpackHeaderTableBase&) = delete; virtual ~QpackHeaderTableBase() = default; bool EntryFitsDynamicTableCapacity(absl::string_view name, absl::string_view value) const; virtual uint64_t InsertEntry(absl::string_view name, absl::string_view value); bool SetDynamicTableCapacity(uint64_t capacity); bool SetMaximumDynamicTableCapacity(uint64_t maximum_dynamic_table_capacity); uint64_t dynamic_table_size() const { return dynamic_table_size_; } uint64_t dynamic_table_capacity() const { return dynamic_table_capacity_; } uint64_t maximum_dynamic_table_capacity() const { return maximum_dynamic_table_capacity_; } uint64_t max_entries() const { return max_entries_; } uint64_t inserted_entry_count() const { return dynamic_entries_.size() + dropped_entry_count_; } uint64_t dropped_entry_count() const { return dropped_entry_count_; } void set_dynamic_table_entry_referenced() { dynamic_table_entry_referenced_ = true; } bool dynamic_table_entry_referenced() const { return dynamic_table_entry_referenced_; } protected: virtual void RemoveEntryFromEnd(); const DynamicEntryTable& dynamic_entries() const { return dynamic_entries_; } private: void EvictDownToCapacity(uint64_t capacity); DynamicEntryTable dynamic_entries_; uint64_t dynamic_table_size_; uint64_t dynamic_table_capacity_; uint64_t maximum_dynamic_table_capacity_; uint64_t max_entries_; uint64_t dropped_entry_count_; bool dynamic_table_entry_referenced_; }; template <typename DynamicEntryTable> QpackHeaderTableBase<DynamicEntryTable>::QpackHeaderTableBase() : dynamic_table_size_(0), dynamic_table_capacity_(0), maximum_dynamic_table_capacity_(0), max_entries_(0), dropped_entry_count_(0), dynamic_table_entry_referenced_(false) {} template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const { return QpackEntry::Size(name, value) <= dynamic_table_capacity_; } namespace internal { QUICHE_EXPORT inline size_t GetSize(const QpackEntry& entry) { return entry.Size(); } QUICHE_EXPORT inline size_t GetSize(const std::unique_ptr<QpackEntry>& entry) { return entry->Size(); } QUICHE_EXPORT inline std::unique_ptr<QpackEntry> NewEntry( std::string name, std::string value, QpackEncoderDynamicTable& ) { return std::make_unique<QpackEntry>(std::move(name), std::move(value)); } QUICHE_EXPORT inline QpackEntry NewEntry(std::string name, std::string value, QpackDecoderDynamicTable& ) { return QpackEntry{std::move(name), std::move(value)}; } } template <typename DynamicEntryTable> uint64_t QpackHeaderTableBase<DynamicEntryTable>::InsertEntry( absl::string_view name, absl::string_view value) { QUICHE_DCHECK(EntryFitsDynamicTableCapacity(name, value)); const uint64_t index = dropped_entry_count_ + dynamic_entries_.size(); auto new_entry = internal::NewEntry(std::string(name), std::string(value), dynamic_entries_); const size_t entry_size = internal::GetSize(new_entry); EvictDownToCapacity(dynamic_table_capacity_ - entry_size); dynamic_table_size_ += entry_size; dynamic_entries_.push_back(std::move(new_entry)); return index; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetDynamicTableCapacity( uint64_t capacity) { if (capacity > maximum_dynamic_table_capacity_) { return false; } dynamic_table_capacity_ = capacity; EvictDownToCapacity(capacity); QUICHE_DCHECK_LE(dynamic_table_size_, dynamic_table_capacity_); return true; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity) { if (maximum_dynamic_table_capacity_ == 0) { maximum_dynamic_table_capacity_ = maximum_dynamic_table_capacity; max_entries_ = maximum_dynamic_table_capacity / 32; return true; } return maximum_dynamic_table_capacity == maximum_dynamic_table_capacity_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::RemoveEntryFromEnd() { const uint64_t entry_size = internal::GetSize(dynamic_entries_.front()); QUICHE_DCHECK_GE(dynamic_table_size_, entry_size); dynamic_table_size_ -= entry_size; dynamic_entries_.pop_front(); ++dropped_entry_count_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::EvictDownToCapacity( uint64_t capacity) { while (dynamic_table_size_ > capacity) { QUICHE_DCHECK(!dynamic_entries_.empty()); RemoveEntryFromEnd(); } } class QUICHE_EXPORT QpackEncoderHeaderTable : public QpackHeaderTableBase<QpackEncoderDynamicTable> { public: enum class MatchType { kNameAndValue, kName, kNoMatch }; struct MatchResult { MatchType match_type; bool is_static; uint64_t index; }; QpackEncoderHeaderTable(); ~QpackEncoderHeaderTable() override = default; uint64_t InsertEntry(absl::string_view name, absl::string_view value) override; MatchResult FindHeaderField(absl::string_view name, absl::string_view value) const; MatchResult FindHeaderName(absl::string_view name) const; uint64_t MaxInsertSizeWithoutEvictingGivenEntry(uint64_t index) const; uint64_t draining_index(float draining_fraction) const; protected: void RemoveEntryFromEnd() override; private: using NameValueToEntryMap = spdy::HpackHeaderTable::NameValueToEntryMap; using NameToEntryMap = spdy::HpackHeaderTable::NameToEntryMap; const NameValueToEntryMap& static_index_; const NameToEntryMap& static_name_index_; NameValueToEntryMap dynamic_index_; NameToEntryMap dynamic_name_index_; }; class QUICHE_EXPORT QpackDecoderHeaderTable : public QpackHeaderTableBase<QpackDecoderDynamicTable> { public: class QUICHE_EXPORT Observer { public: virtual ~Observer() = default; virtual void OnInsertCountReachedThreshold() = 0; virtual void Cancel() = 0; }; QpackDecoderHeaderTable(); ~QpackDecoderHeaderTable() override; uint64_t InsertEntry(absl::string_view name, absl::string_view value) override; const QpackEntry* LookupEntry(bool is_static, uint64_t index) const; void RegisterObserver(uint64_t required_insert_count, Observer* observer); void UnregisterObserver(uint64_t required_insert_count, Observer* observer); private: using StaticEntryTable = spdy::HpackHeaderTable::StaticEntryTable; const StaticEntryTable& static_entries_; std::multimap<uint64_t, Observer*> observers_; }; } #endif #include "quiche/quic/core/qpack/qpack_header_table.h" #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_static_table.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QpackEncoderHeaderTable::QpackEncoderHeaderTable() : static_index_(ObtainQpackStaticTable().GetStaticIndex()), static_name_index_(ObtainQpackStaticTable().GetStaticNameIndex()) {} uint64_t QpackEncoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackEncoderDynamicTable>::InsertEntry(name, value); name = dynamic_entries().back()->name(); value = dynamic_entries().back()->value(); auto index_result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); if (!index_result.second) { QUICHE_DCHECK_GT(index, index_result.first->second); dynamic_index_.erase(index_result.first); auto result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); QUICHE_CHECK(result.second); } auto name_result = dynamic_name_index_.insert({name, index}); if (!name_result.second) { QUICHE_DCHECK_GT(index, name_result.first->second); dynamic_name_index_.erase(name_result.first); auto result = dynamic_name_index_.insert({name, index}); QUICHE_CHECK(result.second); } return index; } QpackEncoderHeaderTable::MatchResult QpackEncoderHeaderTable::FindHeaderField( absl::string_view name, absl::string_view value) const { QpackLookupEntry query{name, value}; auto index_it = static_index_.find(query); if (index_it != static_index_.end()) { return { MatchType::kNameAndValue, true, index_it->second}; } index_it = dynamic_index_.find(query); if (index_it != dynamic_index_.end()) { return { MatchType::kNameAndValue, false, index_it->second}; } return FindHeaderName(name); } QpackEncoderHeaderTable::MatchResult QpackEncoderHeaderTable::FindHeaderName( absl::string_view name) const { auto name_index_it = static_name_index_.find(name); if (name_index_it != static_name_index_.end()) { return { MatchType::kName, true, name_index_it->second}; } name_index_it = dynamic_name_index_.find(name); if (name_index_it != dynamic_name_index_.end()) { return { MatchType::kName, false, name_index_it->second}; } return { MatchType::kNoMatch, false, 0}; } uint64_t QpackEncoderHeaderTable::MaxInsertSizeWithoutEvictingGivenEntry( uint64_t index) const { QUICHE_DCHECK_LE(dropped_entry_count(), index); if (index > inserted_entry_count()) { return dynamic_table_capacity(); } uint64_t max_insert_size = dynamic_table_capacity() - dynamic_table_size(); uint64_t entry_index = dropped_entry_count(); for (const auto& entry : dynamic_entries()) { if (entry_index >= index) { break; } ++entry_index; max_insert_size += entry->Size(); } return max_insert_size; } uint64_t QpackEncoderHeaderTable::draining_index( float draining_fraction) const { QUICHE_DCHECK_LE(0.0, draining_fraction); QUICHE_DCHECK_LE(draining_fraction, 1.0); const uint64_t required_space = draining_fraction * dynamic_table_capacity(); uint64_t space_above_draining_index = dynamic_table_capacity() - dynamic_table_size(); if (dynamic_entries().empty() || space_above_draining_index >= required_space) { return dropped_entry_count(); } auto it = dynamic_entries().begin(); uint64_t entry_index = dropped_entry_count(); while (space_above_draining_index < required_space) { space_above_draining_index += (*it)->Size(); ++it; ++entry_index; if (it == dynamic_entries().end()) { return inserted_entry_count(); } } return entry_index; } void QpackEncoderHeaderTable::RemoveEntryFromEnd() { const QpackEntry* const entry = dynamic_entries().front().get(); const uint64_t index = dropped_entry_count(); auto index_it = dynamic_index_.find({entry->name(), entry->value()}); if (index_it != dynamic_index_.end() && index_it->second == index) { dynamic_index_.erase(index_it); } auto name_it = dynamic_name_index_.find(entry->name()); if (name_it != dynamic_name_index_.end() && name_it->second == index) { dynamic_name_index_.erase(name_it); } QpackHeaderTableBase<QpackEncoderDynamicTable>::RemoveEntryFromEnd(); } QpackDecoderHeaderTable::QpackDecoderHeaderTable() : static_entries_(ObtainQpackStaticTable().GetStaticEntries()) {} QpackDecoderHeaderTable::~QpackDecoderHeaderTable() { for (auto& entry : observers_) { entry.second->Cancel(); } } uint64_t QpackDecoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackDecoderDynamicTable>::InsertEntry(name, value); while (!observers_.empty()) { auto it = observers_.begin(); if (it->first > inserted_entry_count()) { break; } Observer* observer = it->second; observers_.erase(it); observer->OnInsertCountReachedThreshold(); } return index; } const QpackEntry* QpackDecoderHeaderTable::LookupEntry(bool is_static, uint64_t index) const { if (is_static) { if (index >= static_entries_.size()) { return nullptr; } return &static_entries_[index]; } if (index < dropped_entry_count()) { return nullptr; } index -= dropped_entry_count(); if (index >= dynamic_entries().size()) { return nullptr; } return &dynamic_entries()[index]; } void QpackDecoderHeaderTable::RegisterObserver(uint64_t required_insert_count, Observer* observer) { QUICHE_DCHECK_GT(required_insert_count, 0u); observers_.insert({required_insert_count, observer}); } void QpackDecoderHeaderTable::UnregisterObserver(uint64_t required_insert_count, Observer* observer) { auto it = observers_.lower_bound(required_insert_count); while (it != observers_.end() && it->first == required_insert_count) { if (it->second == observer) { observers_.erase(it); return; } ++it; } QUICHE_NOTREACHED(); } }
#include "quiche/quic/core/qpack/qpack_header_table.h" #include <memory> #include <tuple> #include <utility> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_static_table.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/spdy/core/hpack/hpack_entry.h" namespace quic { namespace test { namespace { using ::testing::_; using ::testing::FieldsAre; using ::testing::Mock; using ::testing::StrictMock; constexpr uint64_t kMaximumDynamicTableCapacityForTesting = 1024 * 1024; constexpr bool kStaticEntry = true; constexpr bool kDynamicEntry = false; template <typename T> class QpackHeaderTableTest : public QuicTest { protected: ~QpackHeaderTableTest() override = default; void SetUp() override { ASSERT_TRUE(table_.SetMaximumDynamicTableCapacity( kMaximumDynamicTableCapacityForTesting)); ASSERT_TRUE( table_.SetDynamicTableCapacity(kMaximumDynamicTableCapacityForTesting)); } bool EntryFitsDynamicTableCapacity(absl::string_view name, absl::string_view value) const { return table_.EntryFitsDynamicTableCapacity(name, value); } void InsertEntry(absl::string_view name, absl::string_view value) { table_.InsertEntry(name, value); } bool SetDynamicTableCapacity(uint64_t capacity) { return table_.SetDynamicTableCapacity(capacity); } uint64_t max_entries() const { return table_.max_entries(); } uint64_t inserted_entry_count() const { return table_.inserted_entry_count(); } uint64_t dropped_entry_count() const { return table_.dropped_entry_count(); } T table_; }; using MyTypes = ::testing::Types<QpackEncoderHeaderTable, QpackDecoderHeaderTable>; TYPED_TEST_SUITE(QpackHeaderTableTest, MyTypes); TYPED_TEST(QpackHeaderTableTest, MaxEntries) { TypeParam table1; table1.SetMaximumDynamicTableCapacity(1024); EXPECT_EQ(32u, table1.max_entries()); TypeParam table2; table2.SetMaximumDynamicTableCapacity(500); EXPECT_EQ(15u, table2.max_entries()); } TYPED_TEST(QpackHeaderTableTest, SetDynamicTableCapacity) { EXPECT_TRUE(this->SetDynamicTableCapacity(1024)); EXPECT_EQ(32u * 1024, this->max_entries()); EXPECT_TRUE(this->SetDynamicTableCapacity(500)); EXPECT_EQ(32u * 1024, this->max_entries()); EXPECT_FALSE(this->SetDynamicTableCapacity( 2 * kMaximumDynamicTableCapacityForTesting)); } TYPED_TEST(QpackHeaderTableTest, EntryFitsDynamicTableCapacity) { EXPECT_TRUE(this->SetDynamicTableCapacity(39)); EXPECT_TRUE(this->EntryFitsDynamicTableCapacity("foo", "bar")); EXPECT_TRUE(this->EntryFitsDynamicTableCapacity("foo", "bar2")); EXPECT_FALSE(this->EntryFitsDynamicTableCapacity("foo", "bar12")); } class QpackEncoderHeaderTableTest : public QpackHeaderTableTest<QpackEncoderHeaderTable> { protected: enum MatchType { kNameAndValue, kName, kNoMatch }; ~QpackEncoderHeaderTableTest() override = default; std::tuple<MatchType, bool, uint64_t> FindHeaderField( absl::string_view name, absl::string_view value) const { QpackEncoderHeaderTable::MatchResult match_result = table_.FindHeaderField(name, value); return {static_cast<MatchType>(match_result.match_type), match_result.is_static, match_result.index}; } std::tuple<MatchType, bool, uint64_t> FindHeaderName( absl::string_view name) const { QpackEncoderHeaderTable::MatchResult match_result = table_.FindHeaderName(name); return {static_cast<MatchType>(match_result.match_type), match_result.is_static, match_result.index}; } uint64_t MaxInsertSizeWithoutEvictingGivenEntry(uint64_t index) const { return table_.MaxInsertSizeWithoutEvictingGivenEntry(index); } uint64_t draining_index(float draining_fraction) const { return table_.draining_index(draining_fraction); } }; TEST_F(QpackEncoderHeaderTableTest, FindStaticHeaderField) { EXPECT_THAT(FindHeaderField(":method", "GET"), FieldsAre(kNameAndValue, kStaticEntry, 17u)); EXPECT_THAT(FindHeaderField(":method", "POST"), FieldsAre(kNameAndValue, kStaticEntry, 20u)); EXPECT_THAT(FindHeaderField(":method", "TRACE"), FieldsAre(kName, kStaticEntry, 15u)); EXPECT_THAT(FindHeaderName(":method"), FieldsAre(kName, kStaticEntry, 15u)); EXPECT_THAT(FindHeaderField("accept-encoding", "gzip, deflate, br"), FieldsAre(kNameAndValue, kStaticEntry, 31u)); EXPECT_THAT(FindHeaderField("accept-encoding", "compress"), FieldsAre(kName, kStaticEntry, 31u)); EXPECT_THAT(FindHeaderField("accept-encoding", ""), FieldsAre(kName, kStaticEntry, 31u)); EXPECT_THAT(FindHeaderName("accept-encoding"), FieldsAre(kName, kStaticEntry, 31u)); EXPECT_THAT(FindHeaderField("location", ""), FieldsAre(kNameAndValue, kStaticEntry, 12u)); EXPECT_THAT(FindHeaderField("location", "foo"), FieldsAre(kName, kStaticEntry, 12u)); EXPECT_THAT(FindHeaderName("location"), FieldsAre(kName, kStaticEntry, 12u)); EXPECT_THAT(FindHeaderField("foo", ""), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kNoMatch, _, _)); } TEST_F(QpackEncoderHeaderTableTest, FindDynamicHeaderField) { EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderField("foo", "baz"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kNoMatch, _, _)); InsertEntry("foo", "bar"); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 0u)); EXPECT_THAT(FindHeaderField("foo", "baz"), FieldsAre(kName, kDynamicEntry, 0u)); EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kName, kDynamicEntry, 0u)); InsertEntry("foo", "bar"); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); EXPECT_THAT(FindHeaderField("foo", "baz"), FieldsAre(kName, kDynamicEntry, 1u)); EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kName, kDynamicEntry, 1u)); } TEST_F(QpackEncoderHeaderTableTest, FindHeaderFieldPrefersStaticTable) { InsertEntry(":method", "GET"); EXPECT_THAT(FindHeaderField(":method", "GET"), FieldsAre(kNameAndValue, kStaticEntry, 17u)); EXPECT_THAT(FindHeaderField(":method", "TRACE"), FieldsAre(kName, kStaticEntry, 15u)); EXPECT_THAT(FindHeaderName(":method"), FieldsAre(kName, kStaticEntry, 15u)); InsertEntry(":method", "TRACE"); EXPECT_THAT(FindHeaderField(":method", "TRACE"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); } TEST_F(QpackEncoderHeaderTableTest, EvictByInsertion) { EXPECT_TRUE(SetDynamicTableCapacity(40)); InsertEntry("foo", "bar"); EXPECT_EQ(1u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 0u)); InsertEntry("baz", "qux"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); } TEST_F(QpackEncoderHeaderTableTest, EvictByUpdateTableSize) { InsertEntry("foo", "bar"); InsertEntry("baz", "qux"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 0u)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); EXPECT_TRUE(SetDynamicTableCapacity(40)); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); EXPECT_TRUE(SetDynamicTableCapacity(20)); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(2u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNoMatch, _, _)); } TEST_F(QpackEncoderHeaderTableTest, EvictOldestOfIdentical) { EXPECT_TRUE(SetDynamicTableCapacity(80)); InsertEntry("foo", "bar"); InsertEntry("foo", "bar"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); InsertEntry("baz", "qux"); EXPECT_EQ(3u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNameAndValue, kDynamicEntry, 1u)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNameAndValue, kDynamicEntry, 2u)); } TEST_F(QpackEncoderHeaderTableTest, EvictOldestOfSameName) { EXPECT_TRUE(SetDynamicTableCapacity(80)); InsertEntry("foo", "bar"); InsertEntry("foo", "baz"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "foo"), FieldsAre(kName, kDynamicEntry, 1u)); InsertEntry("baz", "qux"); EXPECT_EQ(3u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); EXPECT_THAT(FindHeaderField("foo", "foo"), FieldsAre(kName, kDynamicEntry, 1u)); EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNameAndValue, kDynamicEntry, 2u)); } TEST_F(QpackEncoderHeaderTableTest, MaxInsertSizeWithoutEvictingGivenEntry) { const uint64_t dynamic_table_capacity = 100; EXPECT_TRUE(SetDynamicTableCapacity(dynamic_table_capacity)); EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(0)); const uint64_t entry_size1 = QpackEntry::Size("foo", "bar"); InsertEntry("foo", "bar"); EXPECT_EQ(dynamic_table_capacity - entry_size1, MaxInsertSizeWithoutEvictingGivenEntry(0)); EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(1)); const uint64_t entry_size2 = QpackEntry::Size("baz", "foobar"); InsertEntry("baz", "foobar"); EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(2)); EXPECT_EQ(dynamic_table_capacity - entry_size2, MaxInsertSizeWithoutEvictingGivenEntry(1)); EXPECT_EQ(dynamic_table_capacity - entry_size2 - entry_size1, MaxInsertSizeWithoutEvictingGivenEntry(0)); const uint64_t entry_size3 = QpackEntry::Size("last", "entry"); InsertEntry("last", "entry"); EXPECT_EQ(1u, dropped_entry_count()); EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(3)); EXPECT_EQ(dynamic_table_capacity - entry_size3, MaxInsertSizeWithoutEvictingGivenEntry(2)); EXPECT_EQ(dynamic_table_capacity - entry_size3 - entry_size2, MaxInsertSizeWithoutEvictingGivenEntry(1)); } TEST_F(QpackEncoderHeaderTableTest, DrainingIndex) { EXPECT_TRUE(SetDynamicTableCapacity(4 * QpackEntry::Size("foo", "bar"))); EXPECT_EQ(0u, draining_index(0.0)); EXPECT_EQ(0u, draining_index(1.0)); InsertEntry("foo", "bar"); EXPECT_EQ(0u, draining_index(0.0)); EXPECT_EQ(1u, draining_index(1.0)); InsertEntry("foo", "bar"); EXPECT_EQ(0u, draining_index(0.0)); EXPECT_EQ(0u, draining_index(0.5)); EXPECT_EQ(2u, draining_index(1.0)); InsertEntry("foo", "bar"); InsertEntry("foo", "bar"); EXPECT_EQ(0u, draining_index(0.0)); EXPECT_EQ(2u, draining_index(0.5)); EXPECT_EQ(4u, draining_index(1.0)); } class MockObserver : public QpackDecoderHeaderTable::Observer { public: ~MockObserver() override = default; MOCK_METHOD(void, OnInsertCountReachedThreshold, (), (override)); MOCK_METHOD(void, Cancel, (), (override)); }; class QpackDecoderHeaderTableTest : public QpackHeaderTableTest<QpackDecoderHeaderTable> { protected: ~QpackDecoderHeaderTableTest() override = default; void ExpectEntryAtIndex(bool is_static, uint64_t index, absl::string_view expected_name, absl::string_view expected_value) const { const auto* entry = table_.LookupEntry(is_static, index); ASSERT_TRUE(entry); EXPECT_EQ(expected_name, entry->name()); EXPECT_EQ(expected_value, entry->value()); } void ExpectNoEntryAtIndex(bool is_static, uint64_t index) const { EXPECT_FALSE(table_.LookupEntry(is_static, index)); } void RegisterObserver(uint64_t required_insert_count, QpackDecoderHeaderTable::Observer* observer) { table_.RegisterObserver(required_insert_count, observer); } void UnregisterObserver(uint64_t required_insert_count, QpackDecoderHeaderTable::Observer* observer) { table_.UnregisterObserver(required_insert_count, observer); } }; TEST_F(QpackDecoderHeaderTableTest, LookupStaticEntry) { ExpectEntryAtIndex(kStaticEntry, 0, ":authority", ""); ExpectEntryAtIndex(kStaticEntry, 1, ":path", "/"); ExpectEntryAtIndex(kStaticEntry, 98, "x-frame-options", "sameorigin"); ASSERT_EQ(99u, QpackStaticTableVector().size()); ExpectNoEntryAtIndex(kStaticEntry, 99); } TEST_F(QpackDecoderHeaderTableTest, InsertAndLookupDynamicEntry) { ExpectNoEntryAtIndex(kDynamicEntry, 0); ExpectNoEntryAtIndex(kDynamicEntry, 1); ExpectNoEntryAtIndex(kDynamicEntry, 2); ExpectNoEntryAtIndex(kDynamicEntry, 3); InsertEntry("foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar"); ExpectNoEntryAtIndex(kDynamicEntry, 1); ExpectNoEntryAtIndex(kDynamicEntry, 2); ExpectNoEntryAtIndex(kDynamicEntry, 3); InsertEntry("baz", "bing"); ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 1, "baz", "bing"); ExpectNoEntryAtIndex(kDynamicEntry, 2); ExpectNoEntryAtIndex(kDynamicEntry, 3); InsertEntry("baz", "bing"); ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 1, "baz", "bing"); ExpectEntryAtIndex(kDynamicEntry, 2, "baz", "bing"); ExpectNoEntryAtIndex(kDynamicEntry, 3); } TEST_F(QpackDecoderHeaderTableTest, EvictByInsertion) { EXPECT_TRUE(SetDynamicTableCapacity(40)); InsertEntry("foo", "bar"); EXPECT_EQ(1u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar"); InsertEntry("baz", "qux"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux"); } TEST_F(QpackDecoderHeaderTableTest, EvictByUpdateTableSize) { ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectNoEntryAtIndex(kDynamicEntry, 1u); InsertEntry("foo", "bar"); InsertEntry("baz", "qux"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux"); EXPECT_TRUE(SetDynamicTableCapacity(40)); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux"); EXPECT_TRUE(SetDynamicTableCapacity(20)); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(2u, dropped_entry_count()); ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectNoEntryAtIndex(kDynamicEntry, 1u); } TEST_F(QpackDecoderHeaderTableTest, EvictOldestOfIdentical) { EXPECT_TRUE(SetDynamicTableCapacity(80)); InsertEntry("foo", "bar"); InsertEntry("foo", "bar"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "bar"); ExpectNoEntryAtIndex(kDynamicEntry, 2u); InsertEntry("baz", "qux"); EXPECT_EQ(3u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 2u, "baz", "qux"); } TEST_F(QpackDecoderHeaderTableTest, EvictOldestOfSameName) { EXPECT_TRUE(SetDynamicTableCapacity(80)); InsertEntry("foo", "bar"); InsertEntry("foo", "baz"); EXPECT_EQ(2u, inserted_entry_count()); EXPECT_EQ(0u, dropped_entry_count()); ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar"); ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "baz"); ExpectNoEntryAtIndex(kDynamicEntry, 2u); InsertEntry("baz", "qux"); EXPECT_EQ(3u, inserted_entry_count()); EXPECT_EQ(1u, dropped_entry_count()); ExpectNoEntryAtIndex(kDynamicEntry, 0u); ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "baz"); ExpectEntryAtIndex(kDynamicEntry, 2u, "baz", "qux"); } TEST_F(QpackDecoderHeaderTableTest, RegisterObserver) { StrictMock<MockObserver> observer1; RegisterObserver(1, &observer1); EXPECT_CALL(observer1, OnInsertCountReachedThreshold); InsertEntry("foo", "bar"); EXPECT_EQ(1u, inserted_entry_count()); Mock::VerifyAndClearExpectations(&observer1); StrictMock<MockObserver> observer2; StrictMock<MockObserver> observer3; RegisterObserver(3, &observer3); RegisterObserver(2, &observer2); EXPECT_CALL(observer2, OnInsertCountReachedThreshold); InsertEntry("foo", "bar"); EXPECT_EQ(2u, inserted_entry_count()); Mock::VerifyAndClearExpectations(&observer3); EXPECT_CALL(observer3, OnInsertCountReachedThreshold); InsertEntry("foo", "bar"); EXPECT_EQ(3u, inserted_entry_count()); Mock::VerifyAndClearExpectations(&observer2); StrictMock<MockObserver> observer4; StrictMock<MockObserver> observer5; RegisterObserver(4, &observer4); RegisterObserver(4, &observer5); EXPECT_CALL(observer4, OnInsertCountReachedThreshold); EXPECT_CALL(observer5, OnInsertCountReachedThreshold); InsertEntry("foo", "bar"); EXPECT_EQ(4u, inserted_entry_count()); Mock::VerifyAndClearExpectations(&observer4); Mock::VerifyAndClearExpectations(&observer5); } TEST_F(QpackDecoderHeaderTableTest, UnregisterObserver) { StrictMock<MockObserver> observer1; StrictMock<MockObserver> observer2; StrictMock<MockObserver> observer3; StrictMock<MockObserver> observer4; RegisterObserver(1, &observer1); RegisterObserver(2, &observer2); RegisterObserver(2, &observer3); RegisterObserver(3, &observer4); UnregisterObserver(2, &observer3); EXPECT_CALL(observer1, OnInsertCountReachedThreshold); EXPECT_CALL(observer2, OnInsertCountReachedThreshold); EXPECT_CALL(observer4, OnInsertCountReachedThreshold); InsertEntry("foo", "bar"); InsertEntry("foo", "bar"); InsertEntry("foo", "bar"); EXPECT_EQ(3u, inserted_entry_count()); } TEST_F(QpackDecoderHeaderTableTest, Cancel) { StrictMock<MockObserver> observer; auto table = std::make_unique<QpackDecoderHeaderTable>(); table->RegisterObserver(1, &observer); EXPECT_CALL(observer, Cancel); table.reset(); } } } }
294
cpp
google/quiche
value_splitting_header_list
quiche/quic/core/qpack/value_splitting_header_list.cc
quiche/quic/core/qpack/value_splitting_header_list_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_VALUE_SPLITTING_HEADER_LIST_H_ #define QUICHE_QUIC_CORE_QPACK_VALUE_SPLITTING_HEADER_LIST_H_ #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { class QUICHE_EXPORT ValueSplittingHeaderList { public: using value_type = spdy::Http2HeaderBlock::value_type; class QUICHE_EXPORT const_iterator { public: const_iterator(const spdy::Http2HeaderBlock* header_list, spdy::Http2HeaderBlock::const_iterator header_list_iterator); const_iterator(const const_iterator&) = default; const_iterator& operator=(const const_iterator&) = delete; bool operator==(const const_iterator& other) const; bool operator!=(const const_iterator& other) const; const const_iterator& operator++(); const value_type& operator*() const; const value_type* operator->() const; private: void UpdateHeaderField(); const spdy::Http2HeaderBlock* const header_list_; spdy::Http2HeaderBlock::const_iterator header_list_iterator_; absl::string_view::size_type value_start_; absl::string_view::size_type value_end_; value_type header_field_; }; explicit ValueSplittingHeaderList(const spdy::Http2HeaderBlock* header_list); ValueSplittingHeaderList(const ValueSplittingHeaderList&) = delete; ValueSplittingHeaderList& operator=(const ValueSplittingHeaderList&) = delete; const_iterator begin() const; const_iterator end() const; private: const spdy::Http2HeaderBlock* const header_list_; }; } #endif #include "quiche/quic/core/qpack/value_splitting_header_list.h" #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const char kCookieKey[] = "cookie"; const char kCookieSeparator = ';'; const char kOptionalSpaceAfterCookieSeparator = ' '; const char kNonCookieSeparator = '\0'; } ValueSplittingHeaderList::const_iterator::const_iterator( const spdy::Http2HeaderBlock* header_list, spdy::Http2HeaderBlock::const_iterator header_list_iterator) : header_list_(header_list), header_list_iterator_(header_list_iterator), value_start_(0) { UpdateHeaderField(); } bool ValueSplittingHeaderList::const_iterator::operator==( const const_iterator& other) const { return header_list_iterator_ == other.header_list_iterator_ && value_start_ == other.value_start_; } bool ValueSplittingHeaderList::const_iterator::operator!=( const const_iterator& other) const { return !(*this == other); } const ValueSplittingHeaderList::const_iterator& ValueSplittingHeaderList::const_iterator::operator++() { if (value_end_ == absl::string_view::npos) { ++header_list_iterator_; value_start_ = 0; } else { value_start_ = value_end_ + 1; } UpdateHeaderField(); return *this; } const ValueSplittingHeaderList::value_type& ValueSplittingHeaderList::const_iterator::operator*() const { return header_field_; } const ValueSplittingHeaderList::value_type* ValueSplittingHeaderList::const_iterator::operator->() const { return &header_field_; } void ValueSplittingHeaderList::const_iterator::UpdateHeaderField() { QUICHE_DCHECK(value_start_ != absl::string_view::npos); if (header_list_iterator_ == header_list_->end()) { return; } const absl::string_view name = header_list_iterator_->first; const absl::string_view original_value = header_list_iterator_->second; if (name == kCookieKey) { value_end_ = original_value.find(kCookieSeparator, value_start_); } else { value_end_ = original_value.find(kNonCookieSeparator, value_start_); } const absl::string_view value = original_value.substr(value_start_, value_end_ - value_start_); header_field_ = std::make_pair(name, value); if (name == kCookieKey && value_end_ != absl::string_view::npos && value_end_ + 1 < original_value.size() && original_value[value_end_ + 1] == kOptionalSpaceAfterCookieSeparator) { ++value_end_; } } ValueSplittingHeaderList::ValueSplittingHeaderList( const spdy::Http2HeaderBlock* header_list) : header_list_(header_list) { QUICHE_DCHECK(header_list_); } ValueSplittingHeaderList::const_iterator ValueSplittingHeaderList::begin() const { return const_iterator(header_list_, header_list_->begin()); } ValueSplittingHeaderList::const_iterator ValueSplittingHeaderList::end() const { return const_iterator(header_list_, header_list_->end()); } }
#include "quiche/quic/core/qpack/value_splitting_header_list.h" #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { using ::testing::ElementsAre; using ::testing::Pair; TEST(ValueSplittingHeaderListTest, Comparison) { spdy::Http2HeaderBlock block; block["foo"] = absl::string_view("bar\0baz", 7); block["baz"] = "qux"; block["cookie"] = "foo; bar"; ValueSplittingHeaderList headers(&block); ValueSplittingHeaderList::const_iterator it1 = headers.begin(); const int kEnd = 6; for (int i = 0; i < kEnd; ++i) { if (i == 0) { EXPECT_TRUE(it1 == headers.begin()); EXPECT_TRUE(headers.begin() == it1); EXPECT_FALSE(it1 != headers.begin()); EXPECT_FALSE(headers.begin() != it1); } else { EXPECT_FALSE(it1 == headers.begin()); EXPECT_FALSE(headers.begin() == it1); EXPECT_TRUE(it1 != headers.begin()); EXPECT_TRUE(headers.begin() != it1); } if (i == kEnd - 1) { EXPECT_TRUE(it1 == headers.end()); EXPECT_TRUE(headers.end() == it1); EXPECT_FALSE(it1 != headers.end()); EXPECT_FALSE(headers.end() != it1); } else { EXPECT_FALSE(it1 == headers.end()); EXPECT_FALSE(headers.end() == it1); EXPECT_TRUE(it1 != headers.end()); EXPECT_TRUE(headers.end() != it1); } ValueSplittingHeaderList::const_iterator it2 = headers.begin(); for (int j = 0; j < kEnd; ++j) { if (i == j) { EXPECT_TRUE(it1 == it2); EXPECT_FALSE(it1 != it2); } else { EXPECT_FALSE(it1 == it2); EXPECT_TRUE(it1 != it2); } if (j < kEnd - 1) { ASSERT_NE(it2, headers.end()); ++it2; } } if (i < kEnd - 1) { ASSERT_NE(it1, headers.end()); ++it1; } } } TEST(ValueSplittingHeaderListTest, Empty) { spdy::Http2HeaderBlock block; ValueSplittingHeaderList headers(&block); EXPECT_THAT(headers, ElementsAre()); EXPECT_EQ(headers.begin(), headers.end()); } TEST(ValueSplittingHeaderListTest, Split) { struct { const char* name; absl::string_view value; std::vector<const char*> expected_values; } kTestData[]{ {"foo", "", {""}}, {"foo", "bar", {"bar"}}, {"foo", {"bar\0baz", 7}, {"bar", "baz"}}, {"cookie", "foo;bar", {"foo", "bar"}}, {"cookie", "foo; bar", {"foo", "bar"}}, {"foo", {"\0", 1}, {"", ""}}, {"bar", {"foo\0", 4}, {"foo", ""}}, {"baz", {"\0bar", 4}, {"", "bar"}}, {"qux", {"\0foobar\0", 8}, {"", "foobar", ""}}, {"cookie", ";", {"", ""}}, {"cookie", "foo;", {"foo", ""}}, {"cookie", ";bar", {"", "bar"}}, {"cookie", ";foobar;", {"", "foobar", ""}}, {"cookie", "; ", {"", ""}}, {"cookie", "foo; ", {"foo", ""}}, {"cookie", "; bar", {"", "bar"}}, {"cookie", "; foobar; ", {"", "foobar", ""}}, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) { spdy::Http2HeaderBlock block; block[kTestData[i].name] = kTestData[i].value; ValueSplittingHeaderList headers(&block); auto it = headers.begin(); for (const char* expected_value : kTestData[i].expected_values) { ASSERT_NE(it, headers.end()); EXPECT_EQ(it->first, kTestData[i].name); EXPECT_EQ(it->second, expected_value); ++it; } EXPECT_EQ(it, headers.end()); } } TEST(ValueSplittingHeaderListTest, MultipleFields) { spdy::Http2HeaderBlock block; block["foo"] = absl::string_view("bar\0baz\0", 8); block["cookie"] = "foo; bar"; block["bar"] = absl::string_view("qux\0foo", 7); ValueSplittingHeaderList headers(&block); EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("foo", "baz"), Pair("foo", ""), Pair("cookie", "foo"), Pair("cookie", "bar"), Pair("bar", "qux"), Pair("bar", "foo"))); } TEST(ValueSplittingHeaderListTest, CookieStartsWithSpace) { spdy::Http2HeaderBlock block; block["foo"] = "bar"; block["cookie"] = " foo"; block["bar"] = "baz"; ValueSplittingHeaderList headers(&block); EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("cookie", " foo"), Pair("bar", "baz"))); } } } }
295
cpp
google/quiche
qpack_decoder_stream_receiver
quiche/quic/core/qpack/qpack_decoder_stream_receiver.cc
quiche/quic/core/qpack/qpack_decoder_stream_receiver_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_STREAM_RECEIVER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_STREAM_RECEIVER_H_ #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instruction_decoder.h" #include "quiche/quic/core/qpack/qpack_stream_receiver.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackDecoderStreamReceiver : public QpackInstructionDecoder::Delegate, public QpackStreamReceiver { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() = default; virtual void OnInsertCountIncrement(uint64_t increment) = 0; virtual void OnHeaderAcknowledgement(QuicStreamId stream_id) = 0; virtual void OnStreamCancellation(QuicStreamId stream_id) = 0; virtual void OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) = 0; }; explicit QpackDecoderStreamReceiver(Delegate* delegate); QpackDecoderStreamReceiver() = delete; QpackDecoderStreamReceiver(const QpackDecoderStreamReceiver&) = delete; QpackDecoderStreamReceiver& operator=(const QpackDecoderStreamReceiver&) = delete; void Decode(absl::string_view data) override; bool OnInstructionDecoded(const QpackInstruction* instruction) override; void OnInstructionDecodingError(QpackInstructionDecoder::ErrorCode error_code, absl::string_view error_message) override; private: QpackInstructionDecoder instruction_decoder_; Delegate* const delegate_; bool error_detected_; }; } #endif #include "quiche/quic/core/qpack/qpack_decoder_stream_receiver.h" #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/quic/core/qpack/qpack_instructions.h" namespace quic { QpackDecoderStreamReceiver::QpackDecoderStreamReceiver(Delegate* delegate) : instruction_decoder_(QpackDecoderStreamLanguage(), this), delegate_(delegate), error_detected_(false) { QUICHE_DCHECK(delegate_); } void QpackDecoderStreamReceiver::Decode(absl::string_view data) { if (data.empty() || error_detected_) { return; } instruction_decoder_.Decode(data); } bool QpackDecoderStreamReceiver::OnInstructionDecoded( const QpackInstruction* instruction) { if (instruction == InsertCountIncrementInstruction()) { delegate_->OnInsertCountIncrement(instruction_decoder_.varint()); return true; } if (instruction == HeaderAcknowledgementInstruction()) { delegate_->OnHeaderAcknowledgement(instruction_decoder_.varint()); return true; } QUICHE_DCHECK_EQ(instruction, StreamCancellationInstruction()); delegate_->OnStreamCancellation(instruction_decoder_.varint()); return true; } void QpackDecoderStreamReceiver::OnInstructionDecodingError( QpackInstructionDecoder::ErrorCode error_code, absl::string_view error_message) { QUICHE_DCHECK(!error_detected_); error_detected_ = true; QuicErrorCode quic_error_code = (error_code == QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE) ? QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE : QUIC_INTERNAL_ERROR; delegate_->OnErrorDetected(quic_error_code, error_message); } }
#include "quiche/quic/core/qpack/qpack_decoder_stream_receiver.h" #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" using testing::Eq; using testing::StrictMock; namespace quic { namespace test { namespace { class MockDelegate : public QpackDecoderStreamReceiver::Delegate { public: ~MockDelegate() override = default; MOCK_METHOD(void, OnInsertCountIncrement, (uint64_t increment), (override)); MOCK_METHOD(void, OnHeaderAcknowledgement, (QuicStreamId stream_id), (override)); MOCK_METHOD(void, OnStreamCancellation, (QuicStreamId stream_id), (override)); MOCK_METHOD(void, OnErrorDetected, (QuicErrorCode error_code, absl::string_view error_message), (override)); }; class QpackDecoderStreamReceiverTest : public QuicTest { protected: QpackDecoderStreamReceiverTest() : stream_(&delegate_) {} ~QpackDecoderStreamReceiverTest() override = default; QpackDecoderStreamReceiver stream_; StrictMock<MockDelegate> delegate_; }; TEST_F(QpackDecoderStreamReceiverTest, InsertCountIncrement) { std::string encoded_data; EXPECT_CALL(delegate_, OnInsertCountIncrement(0)); ASSERT_TRUE(absl::HexStringToBytes("00", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnInsertCountIncrement(10)); ASSERT_TRUE(absl::HexStringToBytes("0a", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnInsertCountIncrement(63)); ASSERT_TRUE(absl::HexStringToBytes("3f00", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnInsertCountIncrement(200)); ASSERT_TRUE(absl::HexStringToBytes("3f8901", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &encoded_data)); stream_.Decode(encoded_data); } TEST_F(QpackDecoderStreamReceiverTest, HeaderAcknowledgement) { std::string encoded_data; EXPECT_CALL(delegate_, OnHeaderAcknowledgement(0)); ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnHeaderAcknowledgement(37)); ASSERT_TRUE(absl::HexStringToBytes("a5", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnHeaderAcknowledgement(127)); ASSERT_TRUE(absl::HexStringToBytes("ff00", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnHeaderAcknowledgement(503)); ASSERT_TRUE(absl::HexStringToBytes("fff802", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &encoded_data)); stream_.Decode(encoded_data); } TEST_F(QpackDecoderStreamReceiverTest, StreamCancellation) { std::string encoded_data; EXPECT_CALL(delegate_, OnStreamCancellation(0)); ASSERT_TRUE(absl::HexStringToBytes("40", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnStreamCancellation(19)); ASSERT_TRUE(absl::HexStringToBytes("53", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnStreamCancellation(63)); ASSERT_TRUE(absl::HexStringToBytes("7f00", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnStreamCancellation(110)); ASSERT_TRUE(absl::HexStringToBytes("7f2f", &encoded_data)); stream_.Decode(encoded_data); EXPECT_CALL(delegate_, OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); ASSERT_TRUE(absl::HexStringToBytes("7fffffffffffffffffffff", &encoded_data)); stream_.Decode(encoded_data); } } } }
296
cpp
google/quiche
qpack_send_stream
quiche/quic/core/qpack/qpack_send_stream.cc
quiche/quic/core/qpack/qpack_send_stream_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_SEND_STREAM_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_SEND_STREAM_H_ #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_stream_sender_delegate.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { class QuicSession; class QUICHE_EXPORT QpackSendStream : public QuicStream, public QpackStreamSenderDelegate { public: QpackSendStream(QuicStreamId id, QuicSession* session, uint64_t http3_stream_type); QpackSendStream(const QpackSendStream&) = delete; QpackSendStream& operator=(const QpackSendStream&) = delete; ~QpackSendStream() override = default; void OnStreamReset(const QuicRstStreamFrame& frame) override; bool OnStopSending(QuicResetStreamError code) override; void OnDataAvailable() override { QUICHE_NOTREACHED(); } void WriteStreamData(absl::string_view data) override; uint64_t NumBytesBuffered() const override; void MaybeSendStreamType(); private: const uint64_t http3_stream_type_; bool stream_type_sent_; }; } #endif #include "quiche/quic/core/qpack/qpack_send_stream.h" #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_session.h" namespace quic { QpackSendStream::QpackSendStream(QuicStreamId id, QuicSession* session, uint64_t http3_stream_type) : QuicStream(id, session, true, WRITE_UNIDIRECTIONAL), http3_stream_type_(http3_stream_type), stream_type_sent_(false) {} void QpackSendStream::OnStreamReset(const QuicRstStreamFrame& ) { QUIC_BUG(quic_bug_10805_1) << "OnStreamReset() called for write unidirectional stream."; } bool QpackSendStream::OnStopSending(QuicResetStreamError ) { stream_delegate()->OnStreamError( QUIC_HTTP_CLOSED_CRITICAL_STREAM, "STOP_SENDING received for QPACK send stream"); return false; } void QpackSendStream::WriteStreamData(absl::string_view data) { QuicConnection::ScopedPacketFlusher flusher(session()->connection()); MaybeSendStreamType(); WriteOrBufferData(data, false, nullptr); } uint64_t QpackSendStream::NumBytesBuffered() const { return QuicStream::BufferedDataBytes(); } void QpackSendStream::MaybeSendStreamType() { if (!stream_type_sent_) { char type[sizeof(http3_stream_type_)]; QuicDataWriter writer(ABSL_ARRAYSIZE(type), type); writer.WriteVarInt62(http3_stream_type_); WriteOrBufferData(absl::string_view(writer.data(), writer.length()), false, nullptr); stream_type_sent_ = true; } } }
#include "quiche/quic/core/qpack/qpack_send_stream.h" #include <memory> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::StrictMock; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: version: " << ParsedQuicVersionToString(version) << ", perspective: " << perspective; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& tp) { return absl::StrCat( ParsedQuicVersionToString(tp.version), "_", (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (const auto& version : AllSupportedVersions()) { if (!VersionUsesHttp3(version.transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(version, p); } } return params; } class QpackSendStreamTest : public QuicTestWithParam<TestParams> { public: QpackSendStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), SupportedVersions(GetParam().version))), session_(connection_) { EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); if (connection_->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(connection_); } QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 3); session_.OnConfigNegotiated(); qpack_send_stream_ = QuicSpdySessionPeer::GetQpackDecoderSendStream(&session_); ON_CALL(session_, WritevData(_, _, _, _, _, _)) .WillByDefault(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); } Perspective perspective() const { return GetParam().perspective; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QpackSendStream* qpack_send_stream_; }; INSTANTIATE_TEST_SUITE_P(Tests, QpackSendStreamTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QpackSendStreamTest, WriteStreamTypeOnlyFirstTime) { std::string data = "data"; EXPECT_CALL(session_, WritevData(_, 1, _, _, _, _)); EXPECT_CALL(session_, WritevData(_, data.length(), _, _, _, _)); qpack_send_stream_->WriteStreamData(absl::string_view(data)); EXPECT_CALL(session_, WritevData(_, data.length(), _, _, _, _)); qpack_send_stream_->WriteStreamData(absl::string_view(data)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0); qpack_send_stream_->MaybeSendStreamType(); } TEST_P(QpackSendStreamTest, StopSendingQpackStream) { EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _)); qpack_send_stream_->OnStopSending( QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED)); } TEST_P(QpackSendStreamTest, ReceiveDataOnSendStream) { QuicStreamFrame frame(qpack_send_stream_->id(), false, 0, "test"); EXPECT_CALL( *connection_, CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _)); qpack_send_stream_->OnStreamFrame(frame); } TEST_P(QpackSendStreamTest, GetSendWindowSizeFromSession) { SetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5, true); EXPECT_NE(session_.GetFlowControlSendWindowSize(qpack_send_stream_->id()), std::numeric_limits<QuicByteCount>::max()); } } } }
297
cpp
google/quiche
qpack_decoded_headers_accumulator
quiche/quic/core/qpack/qpack_decoded_headers_accumulator.cc
quiche/quic/core/qpack/qpack_decoded_headers_accumulator_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_DECODED_HEADERS_ACCUMULATOR_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_DECODED_HEADERS_ACCUMULATOR_H_ #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/qpack/qpack_progressive_decoder.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QpackDecoder; class QUICHE_EXPORT QpackDecodedHeadersAccumulator : public QpackProgressiveDecoder::HeadersHandlerInterface { public: class QUICHE_EXPORT Visitor { public: virtual ~Visitor() = default; virtual void OnHeadersDecoded(QuicHeaderList headers, bool header_list_size_limit_exceeded) = 0; virtual void OnHeaderDecodingError(QuicErrorCode error_code, absl::string_view error_message) = 0; }; QpackDecodedHeadersAccumulator(QuicStreamId id, QpackDecoder* qpack_decoder, Visitor* visitor, size_t max_header_list_size); virtual ~QpackDecodedHeadersAccumulator() = default; void OnHeaderDecoded(absl::string_view name, absl::string_view value) override; void OnDecodingCompleted() override; void OnDecodingErrorDetected(QuicErrorCode error_code, absl::string_view error_message) override; void Decode(absl::string_view data); void EndHeaderBlock(); private: std::unique_ptr<QpackProgressiveDecoder> decoder_; Visitor* visitor_; size_t max_header_list_size_; size_t uncompressed_header_bytes_including_overhead_; QuicHeaderList quic_header_list_; size_t uncompressed_header_bytes_without_overhead_; size_t compressed_header_bytes_; bool header_list_size_limit_exceeded_; bool headers_decoded_; bool error_detected_; }; } #endif #include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h" #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_decoder.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QpackDecodedHeadersAccumulator::QpackDecodedHeadersAccumulator( QuicStreamId id, QpackDecoder* qpack_decoder, Visitor* visitor, size_t max_header_list_size) : decoder_(qpack_decoder->CreateProgressiveDecoder(id, this)), visitor_(visitor), max_header_list_size_(max_header_list_size), uncompressed_header_bytes_including_overhead_(0), uncompressed_header_bytes_without_overhead_(0), compressed_header_bytes_(0), header_list_size_limit_exceeded_(false), headers_decoded_(false), error_detected_(false) { quic_header_list_.OnHeaderBlockStart(); } void QpackDecodedHeadersAccumulator::OnHeaderDecoded(absl::string_view name, absl::string_view value) { QUICHE_DCHECK(!error_detected_); uncompressed_header_bytes_without_overhead_ += name.size() + value.size(); if (header_list_size_limit_exceeded_) { return; } uncompressed_header_bytes_including_overhead_ += name.size() + value.size() + kQpackEntrySizeOverhead; const size_t uncompressed_header_bytes = GetQuicFlag(quic_header_size_limit_includes_overhead) ? uncompressed_header_bytes_including_overhead_ : uncompressed_header_bytes_without_overhead_; if (uncompressed_header_bytes > max_header_list_size_) { header_list_size_limit_exceeded_ = true; } quic_header_list_.OnHeader(name, value); } void QpackDecodedHeadersAccumulator::OnDecodingCompleted() { QUICHE_DCHECK(!headers_decoded_); QUICHE_DCHECK(!error_detected_); headers_decoded_ = true; quic_header_list_.OnHeaderBlockEnd( uncompressed_header_bytes_without_overhead_, compressed_header_bytes_); visitor_->OnHeadersDecoded(std::move(quic_header_list_), header_list_size_limit_exceeded_); } void QpackDecodedHeadersAccumulator::OnDecodingErrorDetected( QuicErrorCode error_code, absl::string_view error_message) { QUICHE_DCHECK(!error_detected_); QUICHE_DCHECK(!headers_decoded_); error_detected_ = true; visitor_->OnHeaderDecodingError(error_code, error_message); } void QpackDecodedHeadersAccumulator::Decode(absl::string_view data) { QUICHE_DCHECK(!error_detected_); compressed_header_bytes_ += data.size(); decoder_->Decode(data); } void QpackDecodedHeadersAccumulator::EndHeaderBlock() { QUICHE_DCHECK(!error_detected_); QUICHE_DCHECK(!headers_decoded_); if (!decoder_) { QUIC_BUG(b215142466_EndHeaderBlock); return; } decoder_->EndHeaderBlock(); } }
#include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h" #include <cstring> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_decoder.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::_; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Pair; using ::testing::SaveArg; using ::testing::StrictMock; namespace quic { namespace test { namespace { QuicStreamId kTestStreamId = 1; const size_t kMaxHeaderListSize = 100; const size_t kMaxDynamicTableCapacity = 100; const uint64_t kMaximumBlockedStreams = 1; const char* const kHeaderAcknowledgement = "\x81"; class MockVisitor : public QpackDecodedHeadersAccumulator::Visitor { public: ~MockVisitor() override = default; MOCK_METHOD(void, OnHeadersDecoded, (QuicHeaderList headers, bool header_list_size_limit_exceeded), (override)); MOCK_METHOD(void, OnHeaderDecodingError, (QuicErrorCode error_code, absl::string_view error_message), (override)); }; } class QpackDecodedHeadersAccumulatorTest : public QuicTest { protected: QpackDecodedHeadersAccumulatorTest() : qpack_decoder_(kMaxDynamicTableCapacity, kMaximumBlockedStreams, &encoder_stream_error_delegate_), accumulator_(kTestStreamId, &qpack_decoder_, &visitor_, kMaxHeaderListSize) { qpack_decoder_.set_qpack_stream_sender_delegate( &decoder_stream_sender_delegate_); } NoopEncoderStreamErrorDelegate encoder_stream_error_delegate_; StrictMock<MockQpackStreamSenderDelegate> decoder_stream_sender_delegate_; QpackDecoder qpack_decoder_; StrictMock<MockVisitor> visitor_; QpackDecodedHeadersAccumulator accumulator_; }; TEST_F(QpackDecodedHeadersAccumulatorTest, EmptyPayload) { EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Incomplete header data prefix."))); accumulator_.EndHeaderBlock(); } TEST_F(QpackDecodedHeadersAccumulatorTest, TruncatedHeaderBlockPrefix) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("00", &encoded_data)); accumulator_.Decode(encoded_data); EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Incomplete header data prefix."))); accumulator_.EndHeaderBlock(); } TEST_F(QpackDecodedHeadersAccumulatorTest, EmptyHeaderList) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("0000", &encoded_data)); accumulator_.Decode(encoded_data); QuicHeaderList header_list; EXPECT_CALL(visitor_, OnHeadersDecoded(_, false)) .WillOnce(SaveArg<0>(&header_list)); accumulator_.EndHeaderBlock(); EXPECT_EQ(0u, header_list.uncompressed_header_bytes()); EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes()); EXPECT_TRUE(header_list.empty()); } TEST_F(QpackDecodedHeadersAccumulatorTest, TruncatedPayload) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("00002366", &encoded_data)); accumulator_.Decode(encoded_data); EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Incomplete header block."))); accumulator_.EndHeaderBlock(); } TEST_F(QpackDecodedHeadersAccumulatorTest, InvalidPayload) { EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Static table entry not found."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("0000ff23ff24", &encoded_data)); accumulator_.Decode(encoded_data); } TEST_F(QpackDecodedHeadersAccumulatorTest, Success) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("000023666f6f03626172", &encoded_data)); accumulator_.Decode(encoded_data); QuicHeaderList header_list; EXPECT_CALL(visitor_, OnHeadersDecoded(_, false)) .WillOnce(SaveArg<0>(&header_list)); accumulator_.EndHeaderBlock(); EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar"))); EXPECT_EQ(strlen("foo") + strlen("bar"), header_list.uncompressed_header_bytes()); EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes()); } TEST_F(QpackDecodedHeadersAccumulatorTest, ExceedLimitThenSplitInstruction) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes( "0000" "26666f6f626172" "7d61616161616161616161616161616161616161" "616161616161616161616161616161616161616161616161616161616161616161616161" "616161616161616161616161616161616161616161616161616161616161616161616161" "61616161616161616161616161616161616161616161616161616161616161616161" "ff", &encoded_data)); accumulator_.Decode(encoded_data); ASSERT_TRUE(absl::HexStringToBytes( "0f", &encoded_data)); accumulator_.Decode(encoded_data); EXPECT_CALL(visitor_, OnHeadersDecoded(_, true)); accumulator_.EndHeaderBlock(); } TEST_F(QpackDecodedHeadersAccumulatorTest, ExceedLimitBlocked) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes( "0200" "80" "26666f6f626172" "7d61616161616161616161616161616161616161" "616161616161616161616161616161616161616161616161616161616161616161616161" "616161616161616161616161616161616161616161616161616161616161616161616161" "61616161616161616161616161616161616161616161616161616161616161616161", &encoded_data)); accumulator_.Decode(encoded_data); accumulator_.EndHeaderBlock(); qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity); EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))); EXPECT_CALL(visitor_, OnHeadersDecoded(_, true)); qpack_decoder_.OnInsertWithoutNameReference("foo", "bar"); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { qpack_decoder_.FlushDecoderStream(); } } TEST_F(QpackDecodedHeadersAccumulatorTest, BlockedDecoding) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_data)); accumulator_.Decode(encoded_data); accumulator_.EndHeaderBlock(); qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity); EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))); QuicHeaderList header_list; EXPECT_CALL(visitor_, OnHeadersDecoded(_, false)) .WillOnce(SaveArg<0>(&header_list)); qpack_decoder_.OnInsertWithoutNameReference("foo", "bar"); EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar"))); EXPECT_EQ(strlen("foo") + strlen("bar"), header_list.uncompressed_header_bytes()); EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes()); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { qpack_decoder_.FlushDecoderStream(); } } TEST_F(QpackDecodedHeadersAccumulatorTest, BlockedDecodingUnblockedBeforeEndOfHeaderBlock) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_data)); accumulator_.Decode(encoded_data); qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity); qpack_decoder_.OnInsertWithoutNameReference("foo", "bar"); EXPECT_CALL(decoder_stream_sender_delegate_, WriteStreamData(Eq(kHeaderAcknowledgement))); ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data)); accumulator_.Decode(encoded_data); QuicHeaderList header_list; EXPECT_CALL(visitor_, OnHeadersDecoded(_, false)) .WillOnce(SaveArg<0>(&header_list)); accumulator_.EndHeaderBlock(); EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar"), Pair("foo", "bar"))); if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { qpack_decoder_.FlushDecoderStream(); } } TEST_F(QpackDecodedHeadersAccumulatorTest, BlockedDecodingUnblockedAndErrorBeforeEndOfHeaderBlock) { std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("0200", &encoded_data)); accumulator_.Decode(encoded_data); ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data)); accumulator_.Decode(encoded_data); ASSERT_TRUE(absl::HexStringToBytes("81", &encoded_data)); accumulator_.Decode(encoded_data); qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity); EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED, Eq("Invalid relative index."))); qpack_decoder_.OnInsertWithoutNameReference("foo", "bar"); } } }
298
cpp
google/quiche
qpack_encoder_stream_receiver
quiche/quic/core/qpack/qpack_encoder_stream_receiver.cc
quiche/quic/core/qpack/qpack_encoder_stream_receiver_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_STREAM_RECEIVER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_STREAM_RECEIVER_H_ #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instruction_decoder.h" #include "quiche/quic/core/qpack/qpack_stream_receiver.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackEncoderStreamReceiver : public QpackInstructionDecoder::Delegate, public QpackStreamReceiver { public: class QUICHE_EXPORT Delegate { public: virtual ~Delegate() = default; virtual void OnInsertWithNameReference(bool is_static, uint64_t name_index, absl::string_view value) = 0; virtual void OnInsertWithoutNameReference(absl::string_view name, absl::string_view value) = 0; virtual void OnDuplicate(uint64_t index) = 0; virtual void OnSetDynamicTableCapacity(uint64_t capacity) = 0; virtual void OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) = 0; }; explicit QpackEncoderStreamReceiver(Delegate* delegate); QpackEncoderStreamReceiver() = delete; QpackEncoderStreamReceiver(const QpackEncoderStreamReceiver&) = delete; QpackEncoderStreamReceiver& operator=(const QpackEncoderStreamReceiver&) = delete; ~QpackEncoderStreamReceiver() override = default; void Decode(absl::string_view data) override; bool OnInstructionDecoded(const QpackInstruction* instruction) override; void OnInstructionDecodingError(QpackInstructionDecoder::ErrorCode error_code, absl::string_view error_message) override; private: QpackInstructionDecoder instruction_decoder_; Delegate* const delegate_; bool error_detected_; }; } #endif #include "quiche/quic/core/qpack/qpack_encoder_stream_receiver.h" #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_status.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QpackEncoderStreamReceiver::QpackEncoderStreamReceiver(Delegate* delegate) : instruction_decoder_(QpackEncoderStreamLanguage(), this), delegate_(delegate), error_detected_(false) { QUICHE_DCHECK(delegate_); } void QpackEncoderStreamReceiver::Decode(absl::string_view data) { if (data.empty() || error_detected_) { return; } instruction_decoder_.Decode(data); } bool QpackEncoderStreamReceiver::OnInstructionDecoded( const QpackInstruction* instruction) { if (instruction == InsertWithNameReferenceInstruction()) { delegate_->OnInsertWithNameReference(instruction_decoder_.s_bit(), instruction_decoder_.varint(), instruction_decoder_.value()); return true; } if (instruction == InsertWithoutNameReferenceInstruction()) { delegate_->OnInsertWithoutNameReference(instruction_decoder_.name(), instruction_decoder_.value()); return true; } if (instruction == DuplicateInstruction()) { delegate_->OnDuplicate(instruction_decoder_.varint()); return true; } QUICHE_DCHECK_EQ(instruction, SetDynamicTableCapacityInstruction()); delegate_->OnSetDynamicTableCapacity(instruction_decoder_.varint()); return true; } void QpackEncoderStreamReceiver::OnInstructionDecodingError( QpackInstructionDecoder::ErrorCode error_code, absl::string_view error_message) { QUICHE_DCHECK(!error_detected_); error_detected_ = true; QuicErrorCode quic_error_code; switch (error_code) { case QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE: quic_error_code = QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE; break; case QpackInstructionDecoder::ErrorCode::STRING_LITERAL_TOO_LONG: quic_error_code = QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG; break; case QpackInstructionDecoder::ErrorCode::HUFFMAN_ENCODING_ERROR: quic_error_code = QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR; break; default: quic_error_code = QUIC_INTERNAL_ERROR; } delegate_->OnErrorDetected(quic_error_code, error_message); } }
#include "quiche/quic/core/qpack/qpack_encoder_stream_receiver.h" #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" using testing::Eq; using testing::StrictMock; namespace quic { namespace test { namespace { class MockDelegate : public QpackEncoderStreamReceiver::Delegate { public: ~MockDelegate() override = default; MOCK_METHOD(void, OnInsertWithNameReference, (bool is_static, uint64_t name_index, absl::string_view value), (override)); MOCK_METHOD(void, OnInsertWithoutNameReference, (absl::string_view name, absl::string_view value), (override)); MOCK_METHOD(void, OnDuplicate, (uint64_t index), (override)); MOCK_METHOD(void, OnSetDynamicTableCapacity, (uint64_t capacity), (override)); MOCK_METHOD(void, OnErrorDetected, (QuicErrorCode error_code, absl::string_view error_message), (override)); }; class QpackEncoderStreamReceiverTest : public QuicTest { protected: QpackEncoderStreamReceiverTest() : stream_(&delegate_) {} ~QpackEncoderStreamReceiverTest() override = default; void Decode(absl::string_view data) { stream_.Decode(data); } StrictMock<MockDelegate>* delegate() { return &delegate_; } private: QpackEncoderStreamReceiver stream_; StrictMock<MockDelegate> delegate_; }; TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReference) { EXPECT_CALL(*delegate(), OnInsertWithNameReference(true, 5, Eq(""))); EXPECT_CALL(*delegate(), OnInsertWithNameReference(true, 2, Eq("foo"))); EXPECT_CALL(*delegate(), OnInsertWithNameReference(false, 137, Eq("bar"))); EXPECT_CALL(*delegate(), OnInsertWithNameReference(false, 42, Eq(std::string(127, 'Z')))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes( "c500" "c28294e7" "bf4a03626172" "aa7f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReferenceIndexTooLarge) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE( absl::HexStringToBytes("bfffffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReferenceValueTooLong) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE( absl::HexStringToBytes("c57fffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReference) { EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq(""), Eq(""))); EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq("bar"), Eq("bar"))); EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq("foo"), Eq("foo"))); EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq(std::string(31, 'Z')), Eq(std::string(127, 'Z')))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes( "4000" "4362617203626172" "6294e78294e7" "5f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a7f005a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReferenceNameTooLongForVarintDecoder) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("5fffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReferenceNameExceedsLimit) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG, Eq("String literal too long."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("5fffff7f", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReferenceValueTooLongForVarintDecoder) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE( absl::HexStringToBytes("436261727fffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReferenceValueExceedsLimit) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG, Eq("String literal too long."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("436261727fffff7f", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, Duplicate) { EXPECT_CALL(*delegate(), OnDuplicate(17)); EXPECT_CALL(*delegate(), OnDuplicate(500)); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("111fd503", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, DuplicateIndexTooLarge) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("1fffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, SetDynamicTableCapacity) { EXPECT_CALL(*delegate(), OnSetDynamicTableCapacity(17)); EXPECT_CALL(*delegate(), OnSetDynamicTableCapacity(500)); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("313fd503", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, SetDynamicTableCapacityTooLarge) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &encoded_data)); Decode(encoded_data); } TEST_F(QpackEncoderStreamReceiverTest, InvalidHuffmanEncoding) { EXPECT_CALL(*delegate(), OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR, Eq("Error in Huffman-encoded string."))); std::string encoded_data; ASSERT_TRUE(absl::HexStringToBytes("c281ff", &encoded_data)); Decode(encoded_data); } } } }
299
cpp
google/quiche
qpack_encoder
quiche/quic/core/qpack/qpack_encoder.cc
quiche/quic/core/qpack/qpack_encoder_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_H_ #include <cstdint> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_blocking_manager.h" #include "quiche/quic/core/qpack/qpack_decoder_stream_receiver.h" #include "quiche/quic/core/qpack/qpack_encoder_stream_sender.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_exported_stats.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace test { class QpackEncoderPeer; } class QUICHE_EXPORT QpackEncoder : public QpackDecoderStreamReceiver::Delegate { public: class QUICHE_EXPORT DecoderStreamErrorDelegate { public: virtual ~DecoderStreamErrorDelegate() {} virtual void OnDecoderStreamError(QuicErrorCode error_code, absl::string_view error_message) = 0; }; QpackEncoder(DecoderStreamErrorDelegate* decoder_stream_error_delegate, HuffmanEncoding huffman_encoding); ~QpackEncoder() override; std::string EncodeHeaderList(QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list, QuicByteCount* encoder_stream_sent_byte_count); bool SetMaximumDynamicTableCapacity(uint64_t maximum_dynamic_table_capacity); void SetDynamicTableCapacity(uint64_t dynamic_table_capacity); bool SetMaximumBlockedStreams(uint64_t maximum_blocked_streams); void OnInsertCountIncrement(uint64_t increment) override; void OnHeaderAcknowledgement(QuicStreamId stream_id) override; void OnStreamCancellation(QuicStreamId stream_id) override; void OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) override; void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) { encoder_stream_sender_.set_qpack_stream_sender_delegate(delegate); } QpackStreamReceiver* decoder_stream_receiver() { return &decoder_stream_receiver_; } bool dynamic_table_entry_referenced() const { return header_table_.dynamic_table_entry_referenced(); } uint64_t maximum_blocked_streams() const { return maximum_blocked_streams_; } uint64_t MaximumDynamicTableCapacity() const { return header_table_.maximum_dynamic_table_capacity(); } private: friend class test::QpackEncoderPeer; using Representation = QpackInstructionWithValues; using Representations = std::vector<Representation>; static Representation EncodeIndexedHeaderField( bool is_static, uint64_t index, QpackBlockingManager::IndexSet* referred_indices); static Representation EncodeLiteralHeaderFieldWithNameReference( bool is_static, uint64_t index, absl::string_view value, QpackBlockingManager::IndexSet* referred_indices); static Representation EncodeLiteralHeaderField(absl::string_view name, absl::string_view value); Representations FirstPassEncode( QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list, QpackBlockingManager::IndexSet* referred_indices, QuicByteCount* encoder_stream_sent_byte_count); std::string SecondPassEncode(Representations representations, uint64_t required_insert_count) const; const HuffmanEncoding huffman_encoding_; DecoderStreamErrorDelegate* const decoder_stream_error_delegate_; QpackDecoderStreamReceiver decoder_stream_receiver_; QpackEncoderStreamSender encoder_stream_sender_; QpackEncoderHeaderTable header_table_; uint64_t maximum_blocked_streams_; QpackBlockingManager blocking_manager_; int header_list_count_; const bool better_compression_ = GetQuicReloadableFlag(quic_better_qpack_compression); }; class QUICHE_EXPORT NoopDecoderStreamErrorDelegate : public QpackEncoder::DecoderStreamErrorDelegate { public: ~NoopDecoderStreamErrorDelegate() override = default; void OnDecoderStreamError(QuicErrorCode , absl::string_view ) override {} }; } #endif #include "quiche/quic/core/qpack/qpack_encoder.h" #include <algorithm> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_index_conversions.h" #include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include "quiche/quic/core/qpack/qpack_required_insert_count.h" #include "quiche/quic/core/qpack/value_splitting_header_list.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const float kDrainingFraction = 0.25; } QpackEncoder::QpackEncoder( DecoderStreamErrorDelegate* decoder_stream_error_delegate, HuffmanEncoding huffman_encoding) : huffman_encoding_(huffman_encoding), decoder_stream_error_delegate_(decoder_stream_error_delegate), decoder_stream_receiver_(this), encoder_stream_sender_(huffman_encoding), maximum_blocked_streams_(0), header_list_count_(0) { QUICHE_DCHECK(decoder_stream_error_delegate_); } QpackEncoder::~QpackEncoder() {} QpackEncoder::Representation QpackEncoder::EncodeIndexedHeaderField( bool is_static, uint64_t index, QpackBlockingManager::IndexSet* referred_indices) { if (!is_static) { referred_indices->insert(index); } return Representation::IndexedHeaderField(is_static, index); } QpackEncoder::Representation QpackEncoder::EncodeLiteralHeaderFieldWithNameReference( bool is_static, uint64_t index, absl::string_view value, QpackBlockingManager::IndexSet* referred_indices) { if (!is_static) { referred_indices->insert(index); } return Representation::LiteralHeaderFieldNameReference(is_static, index, value); } QpackEncoder::Representation QpackEncoder::EncodeLiteralHeaderField( absl::string_view name, absl::string_view value) { return Representation::LiteralHeaderField(name, value); } QpackEncoder::Representations QpackEncoder::FirstPassEncode( QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list, QpackBlockingManager::IndexSet* referred_indices, QuicByteCount* encoder_stream_sent_byte_count) { const QuicByteCount initial_encoder_stream_buffered_byte_count = encoder_stream_sender_.BufferedByteCount(); const bool can_write_to_encoder_stream = encoder_stream_sender_.CanWrite(); Representations representations; representations.reserve(header_list.size()); const uint64_t known_received_count = blocking_manager_.known_received_count(); uint64_t smallest_non_evictable_index = std::min( blocking_manager_.smallest_blocking_index(), known_received_count); const uint64_t draining_index = header_table_.draining_index(kDrainingFraction); const bool blocking_allowed = blocking_manager_.blocking_allowed_on_stream( stream_id, maximum_blocked_streams_); bool dynamic_table_insertion_blocked = false; bool blocked_stream_limit_exhausted = false; for (const auto& header : ValueSplittingHeaderList(&header_list)) { absl::string_view name = header.first; absl::string_view value = header.second; QpackEncoderHeaderTable::MatchResult match_result = header_table_.FindHeaderField(name, value); switch (match_result.match_type) { case QpackEncoderHeaderTable::MatchType::kNameAndValue: { if (match_result.is_static) { representations.push_back(EncodeIndexedHeaderField( match_result.is_static, match_result.index, referred_indices)); break; } if (match_result.index >= draining_index) { if (!blocking_allowed && match_result.index >= known_received_count) { blocked_stream_limit_exhausted = true; } else { representations.push_back(EncodeIndexedHeaderField( match_result.is_static, match_result.index, referred_indices)); smallest_non_evictable_index = std::min(smallest_non_evictable_index, match_result.index); header_table_.set_dynamic_table_entry_referenced(); break; } } else { if (!blocking_allowed) { blocked_stream_limit_exhausted = true; } else if (QpackEntry::Size(name, value) > header_table_.MaxInsertSizeWithoutEvictingGivenEntry( std::min(smallest_non_evictable_index, match_result.index))) { dynamic_table_insertion_blocked = true; } else { if (can_write_to_encoder_stream) { encoder_stream_sender_.SendDuplicate( QpackAbsoluteIndexToEncoderStreamRelativeIndex( match_result.index, header_table_.inserted_entry_count())); uint64_t new_index = header_table_.InsertEntry(name, value); representations.push_back(EncodeIndexedHeaderField( match_result.is_static, new_index, referred_indices)); smallest_non_evictable_index = std::min(smallest_non_evictable_index, match_result.index); header_table_.set_dynamic_table_entry_referenced(); break; } } } if (!better_compression_) { representations.push_back(EncodeLiteralHeaderField(name, value)); break; } QUIC_RELOADABLE_FLAG_COUNT(quic_better_qpack_compression); QpackEncoderHeaderTable::MatchResult match_result_name_only = header_table_.FindHeaderName(name); if (match_result_name_only.match_type != QpackEncoderHeaderTable::MatchType::kName || (match_result_name_only.is_static == match_result.is_static && match_result_name_only.index == match_result.index)) { representations.push_back(EncodeLiteralHeaderField(name, value)); break; } match_result = match_result_name_only; ABSL_FALLTHROUGH_INTENDED; } case QpackEncoderHeaderTable::MatchType::kName: { if (match_result.is_static) { if (blocking_allowed && QpackEntry::Size(name, value) <= header_table_.MaxInsertSizeWithoutEvictingGivenEntry( smallest_non_evictable_index)) { if (can_write_to_encoder_stream) { encoder_stream_sender_.SendInsertWithNameReference( match_result.is_static, match_result.index, value); uint64_t new_index = header_table_.InsertEntry(name, value); representations.push_back(EncodeIndexedHeaderField( false, new_index, referred_indices)); smallest_non_evictable_index = std::min<uint64_t>(smallest_non_evictable_index, new_index); break; } } representations.push_back(EncodeLiteralHeaderFieldWithNameReference( match_result.is_static, match_result.index, value, referred_indices)); break; } if (!blocking_allowed) { blocked_stream_limit_exhausted = true; } else if (QpackEntry::Size(name, value) > header_table_.MaxInsertSizeWithoutEvictingGivenEntry( std::min(smallest_non_evictable_index, match_result.index))) { dynamic_table_insertion_blocked = true; } else { if (can_write_to_encoder_stream) { encoder_stream_sender_.SendInsertWithNameReference( match_result.is_static, QpackAbsoluteIndexToEncoderStreamRelativeIndex( match_result.index, header_table_.inserted_entry_count()), value); uint64_t new_index = header_table_.InsertEntry(name, value); representations.push_back(EncodeIndexedHeaderField( match_result.is_static, new_index, referred_indices)); smallest_non_evictable_index = std::min(smallest_non_evictable_index, match_result.index); header_table_.set_dynamic_table_entry_referenced(); break; } } if ((blocking_allowed || match_result.index < known_received_count) && match_result.index >= draining_index) { representations.push_back(EncodeLiteralHeaderFieldWithNameReference( match_result.is_static, match_result.index, value, referred_indices)); smallest_non_evictable_index = std::min(smallest_non_evictable_index, match_result.index); header_table_.set_dynamic_table_entry_referenced(); break; } representations.push_back(EncodeLiteralHeaderField(name, value)); break; } case QpackEncoderHeaderTable::MatchType::kNoMatch: { if (!blocking_allowed) { blocked_stream_limit_exhausted = true; } else if (QpackEntry::Size(name, value) > header_table_.MaxInsertSizeWithoutEvictingGivenEntry( smallest_non_evictable_index)) { dynamic_table_insertion_blocked = true; } else { if (can_write_to_encoder_stream) { encoder_stream_sender_.SendInsertWithoutNameReference(name, value); uint64_t new_index = header_table_.InsertEntry(name, value); representations.push_back(EncodeIndexedHeaderField( false, new_index, referred_indices)); smallest_non_evictable_index = std::min<uint64_t>(smallest_non_evictable_index, new_index); break; } } representations.push_back(EncodeLiteralHeaderField(name, value)); break; } } } const QuicByteCount encoder_stream_buffered_byte_count = encoder_stream_sender_.BufferedByteCount(); QUICHE_DCHECK_GE(encoder_stream_buffered_byte_count, initial_encoder_stream_buffered_byte_count); if (encoder_stream_sent_byte_count) { *encoder_stream_sent_byte_count = encoder_stream_buffered_byte_count - initial_encoder_stream_buffered_byte_count; } if (can_write_to_encoder_stream) { encoder_stream_sender_.Flush(); } else { QUICHE_DCHECK_EQ(encoder_stream_buffered_byte_count, initial_encoder_stream_buffered_byte_count); } ++header_list_count_; if (dynamic_table_insertion_blocked) { QUIC_HISTOGRAM_COUNTS( "QuicSession.Qpack.HeaderListCountWhenInsertionBlocked", header_list_count_, 1, 1000, 50, "The ordinality of a header list within a connection during the " "encoding of which at least one dynamic table insertion was " "blocked."); } else { QUIC_HISTOGRAM_COUNTS( "QuicSession.Qpack.HeaderListCountWhenInsertionNotBlocked", header_list_count_, 1, 1000, 50, "The ordinality of a header list within a connection during the " "encoding of which no dynamic table insertion was blocked."); } if (blocked_stream_limit_exhausted) { QUIC_HISTOGRAM_COUNTS( "QuicSession.Qpack.HeaderListCountWhenBlockedStreamLimited", header_list_count_, 1, 1000, 50, "The ordinality of a header list within a connection during the " "encoding of which unacknowledged dynamic table entries could not be " "referenced due to the limit on the number of blocked streams."); } else { QUIC_HISTOGRAM_COUNTS( "QuicSession.Qpack.HeaderListCountWhenNotBlockedStreamLimited", header_list_count_, 1, 1000, 50, "The ordinality of a header list within a connection during the " "encoding of which the limit on the number of blocked streams did " "not " "prevent referencing unacknowledged dynamic table entries."); } return representations; } std::string QpackEncoder::SecondPassEncode( QpackEncoder::Representations representations, uint64_t required_insert_count) const { QpackInstructionEncoder instruction_encoder(huffman_encoding_); std::string encoded_headers; instruction_encoder.Encode( Representation::Prefix(QpackEncodeRequiredInsertCount( required_insert_count, header_table_.max_entries())), &encoded_headers); const uint64_t base = required_insert_count; for (auto& representation : representations) { if ((representation.instruction() == QpackIndexedHeaderFieldInstruction() || representation.instruction() == QpackLiteralHeaderFieldNameReferenceInstruction()) && !representation.s_bit()) { representation.set_varint(QpackAbsoluteIndexToRequestStreamRelativeIndex( representation.varint(), base)); } instruction_encoder.Encode(representation, &encoded_headers); } return encoded_headers; } std::string QpackEncoder::EncodeHeaderList( QuicStreamId stream_id, const spdy::Http2HeaderBlock& header_list, QuicByteCount* encoder_stream_sent_byte_count) { QpackBlockingManager::IndexSet referred_indices; Representations representations = FirstPassEncode(stream_id, header_list, &referred_indices, encoder_stream_sent_byte_count); const uint64_t required_insert_count = referred_indices.empty() ? 0 : QpackBlockingManager::RequiredInsertCount(referred_indices); if (!referred_indices.empty()) { blocking_manager_.OnHeaderBlockSent(stream_id, std::move(referred_indices)); } return SecondPassEncode(std::move(representations), required_insert_count); } bool QpackEncoder::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity) { return header_table_.SetMaximumDynamicTableCapacity( maximum_dynamic_table_capacity); } void QpackEncoder::SetDynamicTableCapacity(uint64_t dynamic_table_capacity) { encoder_stream_sender_.SendSetDynamicTableCapacity(dynamic_table_capacity); bool success = header_table_.SetDynamicTableCapacity(dynamic_table_capacity); QUICHE_DCHECK(success); } bool QpackEncoder::SetMaximumBlockedStreams(uint64_t maximum_blocked_streams) { if (maximum_blocked_streams < maximum_blocked_streams_) { return false; } maximum_blocked_streams_ = maximum_blocked_streams; return true; } void QpackEncoder::OnInsertCountIncrement(uint64_t increment) { if (increment == 0) { OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT, "Invalid increment value 0."); return; } if (!blocking_manager_.OnInsertCountIncrement(increment)) { OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW, "Insert Count Increment instruction causes overflow."); } if (blocking_manager_.known_received_count() > header_table_.inserted_entry_count()) { OnErrorDetected(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT, absl::StrCat("Increment value ", increment, " raises known received count to ", blocking_manager_.known_received_count(), " exceeding inserted entry count ", header_table_.inserted_entry_count())); } } void QpackEncoder::OnHeaderAcknowledgement(QuicStreamId stream_id) { if (!blocking_manager_.OnHeaderAcknowledgement(stream_id)) { OnErrorDetected( QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT, absl::StrCat("Header Acknowledgement received for stream ", stream_id, " with no outstanding header blocks.")); } } void QpackEncoder::OnStreamCancellation(QuicStreamId stream_id) { blocking_manager_.OnStreamCancellation(stream_id); } void QpackEncoder::OnErrorDetected(QuicErrorCode error_code, absl::string_view error_message) { decoder_stream_error_delegate_->OnDecoderStreamError(error_code, error_message); } }
#include "quiche/quic/core/qpack/qpack_encoder.h" #include <limits> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_encoder_peer.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::_; using ::testing::Eq; using ::testing::Return; using ::testing::StrictMock; namespace quic { namespace test { namespace { constexpr uint64_t kTooManyBytesBuffered = 1024 * 1024; std::string PrintToString(const testing::TestParamInfo<HuffmanEncoding>& info) { switch (info.param) { case HuffmanEncoding::kEnabled: return "HuffmanEnabled"; case HuffmanEncoding::kDisabled: return "HuffmanDisabled"; } QUICHE_NOTREACHED(); return "InvalidValue"; } class MockDecoderStreamErrorDelegate : public QpackEncoder::DecoderStreamErrorDelegate { public: ~MockDecoderStreamErrorDelegate() override = default; MOCK_METHOD(void, OnDecoderStreamError, (QuicErrorCode error_code, absl::string_view error_message), (override)); }; class QpackEncoderTest : public QuicTestWithParam<HuffmanEncoding> { protected: QpackEncoderTest() : huffman_encoding_(GetParam()), encoder_(&decoder_stream_error_delegate_, huffman_encoding_), encoder_stream_sent_byte_count_(0) { encoder_.set_qpack_stream_sender_delegate(&encoder_stream_sender_delegate_); encoder_.SetMaximumBlockedStreams(1); } ~QpackEncoderTest() override = default; bool HuffmanEnabled() const { return huffman_encoding_ == HuffmanEncoding::kEnabled; } std::string Encode(const spdy::Http2HeaderBlock& header_list) { return encoder_.EncodeHeaderList( 1, header_list, &encoder_stream_sent_byte_count_); } const HuffmanEncoding huffman_encoding_; StrictMock<MockDecoderStreamErrorDelegate> decoder_stream_error_delegate_; StrictMock<MockQpackStreamSenderDelegate> encoder_stream_sender_delegate_; QpackEncoder encoder_; QuicByteCount encoder_stream_sent_byte_count_; }; INSTANTIATE_TEST_SUITE_P(HuffmanEncoding, QpackEncoderTest, ::testing::ValuesIn({HuffmanEncoding::kEnabled, HuffmanEncoding::kDisabled}), PrintToString); TEST_P(QpackEncoderTest, Empty) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; std::string output = Encode(header_list); std::string expected_output; ASSERT_TRUE(absl::HexStringToBytes("0000", &expected_output)); EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, EmptyName) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list[""] = "foo"; std::string output = Encode(header_list); std::string expected_output; if (HuffmanEnabled()) { ASSERT_TRUE(absl::HexStringToBytes("0000208294e7", &expected_output)); } else { ASSERT_TRUE(absl::HexStringToBytes("00002003666f6f", &expected_output)); } EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, EmptyValue) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list["foo"] = ""; std::string output = Encode(header_list); std::string expected_output; if (HuffmanEnabled()) { ASSERT_TRUE(absl::HexStringToBytes("00002a94e700", &expected_output)); } else { ASSERT_TRUE(absl::HexStringToBytes("000023666f6f00", &expected_output)); } EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, EmptyNameAndValue) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list[""] = ""; std::string output = Encode(header_list); std::string expected_output; ASSERT_TRUE(absl::HexStringToBytes("00002000", &expected_output)); EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, Simple) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list["foo"] = "bar"; std::string output = Encode(header_list); std::string expected_output; if (HuffmanEnabled()) { ASSERT_TRUE(absl::HexStringToBytes("00002a94e703626172", &expected_output)); } else { ASSERT_TRUE( absl::HexStringToBytes("000023666f6f03626172", &expected_output)); } EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, Multiple) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list["foo"] = "bar"; header_list["ZZZZZZZ"] = std::string(127, 'Z'); std::string output = Encode(header_list); std::string expected_output_hex; if (HuffmanEnabled()) { expected_output_hex = "0000" "2a94e703626172"; } else { expected_output_hex = "0000" "23666f6f03626172"; } expected_output_hex += "27005a5a5a5a5a5a5a" "7f005a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a"; std::string expected_output; ASSERT_TRUE(absl::HexStringToBytes(expected_output_hex, &expected_output)); EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, StaticTable) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); { spdy::Http2HeaderBlock header_list; header_list[":method"] = "GET"; header_list["accept-encoding"] = "gzip, deflate, br"; header_list["location"] = ""; std::string output = Encode(header_list); std::string expected_output; ASSERT_TRUE(absl::HexStringToBytes("0000d1dfcc", &expected_output)); EXPECT_EQ(expected_output, output); } { spdy::Http2HeaderBlock header_list; header_list[":method"] = "POST"; header_list["accept-encoding"] = "compress"; header_list["location"] = "foo"; std::string output = Encode(header_list); std::string expected_output; if (HuffmanEnabled()) { ASSERT_TRUE(absl::HexStringToBytes("0000d45f108621e9aec2a11f5c8294e7", &expected_output)); } else { ASSERT_TRUE(absl::HexStringToBytes( "0000d45f1008636f6d70726573735c03666f6f", &expected_output)); } EXPECT_EQ(expected_output, output); } { spdy::Http2HeaderBlock header_list; header_list[":method"] = "TRACE"; header_list["accept-encoding"] = ""; std::string output = Encode(header_list); std::string expected_output; ASSERT_TRUE( absl::HexStringToBytes("00005f000554524143455f1000", &expected_output)); EXPECT_EQ(expected_output, output); } } TEST_P(QpackEncoderTest, DecoderStreamError) { EXPECT_CALL(decoder_stream_error_delegate_, OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE, Eq("Encoded integer too large."))); QpackEncoder encoder(&decoder_stream_error_delegate_, huffman_encoding_); encoder.set_qpack_stream_sender_delegate(&encoder_stream_sender_delegate_); std::string input; ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &input)); encoder.decoder_stream_receiver()->Decode(input); } TEST_P(QpackEncoderTest, SplitAlongNullCharacter) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list; header_list["foo"] = absl::string_view("bar\0bar\0baz", 11); std::string output = Encode(header_list); std::string expected_output; if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("0000" "2a94e703626172" "2a94e703626172" "2a94e70362617a", &expected_output)); } else { ASSERT_TRUE( absl::HexStringToBytes("0000" "23666f6f03626172" "23666f6f03626172" "23666f6f0362617a", &expected_output)); } EXPECT_EQ(expected_output, output); } TEST_P(QpackEncoderTest, ZeroInsertCountIncrement) { EXPECT_CALL( decoder_stream_error_delegate_, OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT, Eq("Invalid increment value 0."))); encoder_.OnInsertCountIncrement(0); } TEST_P(QpackEncoderTest, TooLargeInsertCountIncrement) { EXPECT_CALL( decoder_stream_error_delegate_, OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT, Eq("Increment value 1 raises known received count " "to 1 exceeding inserted entry count 0"))); encoder_.OnInsertCountIncrement(1); } TEST_P(QpackEncoderTest, InsertCountIncrementOverflow) { QpackEncoderHeaderTable* header_table = QpackEncoderPeer::header_table(&encoder_); header_table->SetMaximumDynamicTableCapacity(4096); header_table->SetDynamicTableCapacity(4096); header_table->InsertEntry("foo", "bar"); encoder_.OnInsertCountIncrement(1); EXPECT_CALL(decoder_stream_error_delegate_, OnDecoderStreamError( QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW, Eq("Insert Count Increment instruction causes overflow."))); encoder_.OnInsertCountIncrement(std::numeric_limits<uint64_t>::max()); } TEST_P(QpackEncoderTest, InvalidHeaderAcknowledgement) { EXPECT_CALL( decoder_stream_error_delegate_, OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT, Eq("Header Acknowledgement received for stream 0 " "with no outstanding header blocks."))); encoder_.OnHeaderAcknowledgement( 0); } TEST_P(QpackEncoderTest, DynamicTable) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); encoder_.SetMaximumBlockedStreams(1); encoder_.SetMaximumDynamicTableCapacity(4096); encoder_.SetDynamicTableCapacity(4096); spdy::Http2HeaderBlock header_list; header_list["foo"] = "bar"; header_list.AppendValueOrAddHeader("foo", "baz"); header_list["cookie"] = "baz"; std::string set_dyanamic_table_capacity; ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity)); std::string insert_entries_hex; if (HuffmanEnabled()) { insert_entries_hex = "62" "94e7"; } else { insert_entries_hex = "43" "666f6f"; } insert_entries_hex += "03626172" "80" "0362617a" "c5" "0362617a"; std::string insert_entries; ASSERT_TRUE(absl::HexStringToBytes(insert_entries_hex, &insert_entries)); EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(Eq( absl::StrCat(set_dyanamic_table_capacity, insert_entries)))); std::string expected_output; ASSERT_TRUE(absl::HexStringToBytes( "0400" "828180", &expected_output)); EXPECT_EQ(expected_output, Encode(header_list)); EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_); } TEST_P(QpackEncoderTest, SmallDynamicTable) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); encoder_.SetMaximumBlockedStreams(1); encoder_.SetMaximumDynamicTableCapacity(QpackEntry::Size("foo", "bar")); encoder_.SetDynamicTableCapacity(QpackEntry::Size("foo", "bar")); spdy::Http2HeaderBlock header_list; header_list["foo"] = "bar"; header_list.AppendValueOrAddHeader("foo", "baz"); header_list["cookie"] = "baz"; header_list["bar"] = "baz"; std::string set_dyanamic_table_capacity; ASSERT_TRUE(absl::HexStringToBytes("3f07", &set_dyanamic_table_capacity)); std::string insert_entry; if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("62" "94e7" "03626172", &insert_entry)); } else { ASSERT_TRUE( absl::HexStringToBytes("43" "666f6f" "03626172", &insert_entry)); } EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData( Eq(absl::StrCat(set_dyanamic_table_capacity, insert_entry)))); std::string expected_output; ASSERT_TRUE( absl::HexStringToBytes("0200" "80" "40" "0362617a" "55" "0362617a" "23626172" "0362617a", &expected_output)); EXPECT_EQ(expected_output, Encode(header_list)); EXPECT_EQ(insert_entry.size(), encoder_stream_sent_byte_count_); } TEST_P(QpackEncoderTest, BlockedStream) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); encoder_.SetMaximumBlockedStreams(1); encoder_.SetMaximumDynamicTableCapacity(4096); encoder_.SetDynamicTableCapacity(4096); spdy::Http2HeaderBlock header_list1; header_list1["foo"] = "bar"; std::string set_dyanamic_table_capacity; ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity)); std::string insert_entry1; if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("62" "94e7" "03626172", &insert_entry1)); } else { ASSERT_TRUE( absl::HexStringToBytes("43" "666f6f" "03626172", &insert_entry1)); } EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(Eq( absl::StrCat(set_dyanamic_table_capacity, insert_entry1)))); std::string expected_output; ASSERT_TRUE( absl::HexStringToBytes("0200" "80", &expected_output)); EXPECT_EQ(expected_output, encoder_.EncodeHeaderList( 1, header_list1, &encoder_stream_sent_byte_count_)); EXPECT_EQ(insert_entry1.size(), encoder_stream_sent_byte_count_); spdy::Http2HeaderBlock header_list2; header_list2["foo"] = "bar"; header_list2.AppendValueOrAddHeader("foo", "baz"); header_list2["cookie"] = "baz"; header_list2["bar"] = "baz"; std::string entries; if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("0000" "2a94e7" "03626172" "2a94e7" "0362617a" "55" "0362617a" "23626172" "0362617a", &entries)); } else { ASSERT_TRUE( absl::HexStringToBytes("0000" "23666f6f" "03626172" "23666f6f" "0362617a" "55" "0362617a" "23626172" "0362617a", &entries)); } EXPECT_EQ(entries, encoder_.EncodeHeaderList( 2, header_list2, &encoder_stream_sent_byte_count_)); EXPECT_EQ(0u, encoder_stream_sent_byte_count_); encoder_.OnInsertCountIncrement(1); std::string insert_entries; ASSERT_TRUE(absl::HexStringToBytes( "80" "0362617a" "c5" "0362617a" "43" "626172" "0362617a", &insert_entries)); EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(Eq(insert_entries))); ASSERT_TRUE( absl::HexStringToBytes("0500" "83828180", &expected_output)); EXPECT_EQ(expected_output, encoder_.EncodeHeaderList( 3, header_list2, &encoder_stream_sent_byte_count_)); EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_); std::string expected2; if (GetQuicReloadableFlag(quic_better_qpack_compression)) { if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("0200" "80" "2a94e7" "0362617a" "55" "0362617a" "23626172" "0362617a", &expected2)); } else { ASSERT_TRUE( absl::HexStringToBytes("0200" "80" "23666f6f" "0362617a" "55" "0362617a" "23626172" "0362617a", &expected2)); } } else { if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("0200" "80" "2a94e7" "0362617a" "2c21cfd4c5" "0362617a" "23626172" "0362617a", &expected2)); } else { ASSERT_TRUE( absl::HexStringToBytes("0200" "80" "23666f6f" "0362617a" "26636f6f6b6965" "0362617a" "23626172" "0362617a", &expected2)); } } EXPECT_EQ(expected2, encoder_.EncodeHeaderList( 4, header_list2, &encoder_stream_sent_byte_count_)); EXPECT_EQ(0u, encoder_stream_sent_byte_count_); encoder_.OnInsertCountIncrement(2); std::string expected3; ASSERT_TRUE( absl::HexStringToBytes("0400" "828180" "23626172" "0362617a", &expected3)); EXPECT_EQ(expected3, encoder_.EncodeHeaderList( 5, header_list2, &encoder_stream_sent_byte_count_)); EXPECT_EQ(0u, encoder_stream_sent_byte_count_); encoder_.OnHeaderAcknowledgement(3); std::string expected4; ASSERT_TRUE( absl::HexStringToBytes("0500" "83828180", &expected4)); EXPECT_EQ(expected4, encoder_.EncodeHeaderList( 6, header_list2, &encoder_stream_sent_byte_count_)); EXPECT_EQ(0u, encoder_stream_sent_byte_count_); } TEST_P(QpackEncoderTest, Draining) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list1; header_list1["one"] = "foo"; header_list1["two"] = "foo"; header_list1["three"] = "foo"; header_list1["four"] = "foo"; header_list1["five"] = "foo"; header_list1["six"] = "foo"; header_list1["seven"] = "foo"; header_list1["eight"] = "foo"; header_list1["nine"] = "foo"; header_list1["ten"] = "foo"; uint64_t maximum_dynamic_table_capacity = 0; for (const auto& header_field : header_list1) { maximum_dynamic_table_capacity += QpackEntry::Size(header_field.first, header_field.second); } maximum_dynamic_table_capacity += QpackEntry::Size("one", "foo"); encoder_.SetMaximumDynamicTableCapacity(maximum_dynamic_table_capacity); encoder_.SetDynamicTableCapacity(maximum_dynamic_table_capacity); EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(_)); std::string expected_output; ASSERT_TRUE( absl::HexStringToBytes("0b00" "89888786858483828180", &expected_output)); EXPECT_EQ(expected_output, Encode(header_list1)); spdy::Http2HeaderBlock header_list2; header_list2["one"] = "foo"; ASSERT_TRUE(absl::HexStringToBytes("09", &expected_output)); EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(Eq(expected_output))); ASSERT_TRUE( absl::HexStringToBytes("0c00" "80", &expected_output)); EXPECT_EQ(expected_output, Encode(header_list2)); spdy::Http2HeaderBlock header_list3; header_list3.AppendValueOrAddHeader("two", "foo"); header_list3.AppendValueOrAddHeader("two", "bar"); std::string entries = "0000" "2374776f"; if (HuffmanEnabled()) { entries += "8294e7"; } else { entries += "03666f6f"; } entries += "2374776f" "03626172"; ASSERT_TRUE(absl::HexStringToBytes(entries, &expected_output)); EXPECT_EQ(expected_output, Encode(header_list3)); } TEST_P(QpackEncoderTest, DynamicTableCapacityLessThanMaximum) { encoder_.SetMaximumDynamicTableCapacity(1024); encoder_.SetDynamicTableCapacity(30); QpackEncoderHeaderTable* header_table = QpackEncoderPeer::header_table(&encoder_); EXPECT_EQ(1024u, header_table->maximum_dynamic_table_capacity()); EXPECT_EQ(30u, header_table->dynamic_table_capacity()); } TEST_P(QpackEncoderTest, EncoderStreamWritesDisallowedThenAllowed) { EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(kTooManyBytesBuffered)); encoder_.SetMaximumBlockedStreams(1); encoder_.SetMaximumDynamicTableCapacity(4096); encoder_.SetDynamicTableCapacity(4096); spdy::Http2HeaderBlock header_list1; header_list1["foo"] = "bar"; header_list1.AppendValueOrAddHeader("foo", "baz"); header_list1["cookie"] = "baz"; std::string entries; if (HuffmanEnabled()) { ASSERT_TRUE( absl::HexStringToBytes("0000" "2a94e7" "03626172" "2a94e7" "0362617a" "55" "0362617a", &entries)); } else { ASSERT_TRUE( absl::HexStringToBytes("0000" "23666f6f" "03626172" "23666f6f" "0362617a" "55" "0362617a", &entries)); } EXPECT_EQ(entries, Encode(header_list1)); EXPECT_EQ(0u, encoder_stream_sent_byte_count_); ::testing::Mock::VerifyAndClearExpectations(&encoder_stream_sender_delegate_); EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered()) .WillRepeatedly(Return(0)); spdy::Http2HeaderBlock header_list2; header_list2["foo"] = "bar"; header_list2.AppendValueOrAddHeader("foo", "baz"); header_list2["cookie"] = "baz"; std::string set_dyanamic_table_capacity; ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity)); std::string insert_entries_hex; if (HuffmanEnabled()) { insert_entries_hex = "62" "94e7"; } else { insert_entries_hex = "43" "666f6f"; } insert_entries_hex += "03626172" "80" "0362617a" "c5" "0362617a"; std::string insert_entries; ASSERT_TRUE(absl::HexStringToBytes(insert_entries_hex, &insert