• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "quiche/quic/core/quic_dispatcher.h"
6 
7 #include <memory>
8 #include <string>
9 #include <utility>
10 
11 #include "absl/base/macros.h"
12 #include "absl/strings/str_cat.h"
13 #include "quiche/quic/core/chlo_extractor.h"
14 #include "quiche/quic/core/crypto/crypto_protocol.h"
15 #include "quiche/quic/core/crypto/quic_crypto_server_config.h"
16 #include "quiche/quic/core/crypto/quic_random.h"
17 #include "quiche/quic/core/quic_config.h"
18 #include "quiche/quic/core/quic_connection.h"
19 #include "quiche/quic/core/quic_connection_id.h"
20 #include "quiche/quic/core/quic_crypto_stream.h"
21 #include "quiche/quic/core/quic_packet_writer_wrapper.h"
22 #include "quiche/quic/core/quic_time_wait_list_manager.h"
23 #include "quiche/quic/core/quic_types.h"
24 #include "quiche/quic/core/quic_utils.h"
25 #include "quiche/quic/core/quic_versions.h"
26 #include "quiche/quic/platform/api/quic_expect_bug.h"
27 #include "quiche/quic/platform/api/quic_flags.h"
28 #include "quiche/quic/platform/api/quic_logging.h"
29 #include "quiche/quic/platform/api/quic_test.h"
30 #include "quiche/quic/test_tools/crypto_test_utils.h"
31 #include "quiche/quic/test_tools/first_flight.h"
32 #include "quiche/quic/test_tools/mock_connection_id_generator.h"
33 #include "quiche/quic/test_tools/mock_quic_time_wait_list_manager.h"
34 #include "quiche/quic/test_tools/quic_buffered_packet_store_peer.h"
35 #include "quiche/quic/test_tools/quic_connection_peer.h"
36 #include "quiche/quic/test_tools/quic_dispatcher_peer.h"
37 #include "quiche/quic/test_tools/quic_test_utils.h"
38 #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h"
39 #include "quiche/common/test_tools/quiche_test_utils.h"
40 
41 using testing::_;
42 using testing::ByMove;
43 using testing::Eq;
44 using testing::InSequence;
45 using testing::Invoke;
46 using testing::NiceMock;
47 using testing::Return;
48 using testing::WithArg;
49 using testing::WithoutArgs;
50 
51 static const size_t kDefaultMaxConnectionsInStore = 100;
52 static const size_t kMaxConnectionsWithoutCHLO =
53     kDefaultMaxConnectionsInStore / 2;
54 static const int16_t kMaxNumSessionsToCreate = 16;
55 
56 namespace quic {
57 namespace test {
58 namespace {
59 
60 const QuicConnectionId kReturnConnectionId{
61     {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}};
62 
63 class TestQuicSpdyServerSession : public QuicServerSessionBase {
64  public:
TestQuicSpdyServerSession(const QuicConfig & config,QuicConnection * connection,const QuicCryptoServerConfig * crypto_config,QuicCompressedCertsCache * compressed_certs_cache)65   TestQuicSpdyServerSession(const QuicConfig& config,
66                             QuicConnection* connection,
67                             const QuicCryptoServerConfig* crypto_config,
68                             QuicCompressedCertsCache* compressed_certs_cache)
69       : QuicServerSessionBase(config, CurrentSupportedVersions(), connection,
70                               nullptr, nullptr, crypto_config,
71                               compressed_certs_cache) {
72     Initialize();
73   }
74   TestQuicSpdyServerSession(const TestQuicSpdyServerSession&) = delete;
75   TestQuicSpdyServerSession& operator=(const TestQuicSpdyServerSession&) =
76       delete;
77 
~TestQuicSpdyServerSession()78   ~TestQuicSpdyServerSession() override { DeleteConnection(); }
79 
80   MOCK_METHOD(void, OnConnectionClosed,
81               (const QuicConnectionCloseFrame& frame,
82                ConnectionCloseSource source),
83               (override));
84   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id),
85               (override));
86   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*),
87               (override));
88   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (),
89               (override));
90   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (),
91               (override));
92 
CreateQuicCryptoServerStream(const QuicCryptoServerConfig * crypto_config,QuicCompressedCertsCache * compressed_certs_cache)93   std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream(
94       const QuicCryptoServerConfig* crypto_config,
95       QuicCompressedCertsCache* compressed_certs_cache) override {
96     return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this,
97                                     stream_helper());
98   }
99 
stream_helper()100   QuicCryptoServerStreamBase::Helper* stream_helper() {
101     return QuicServerSessionBase::stream_helper();
102   }
103 };
104 
105 class TestDispatcher : public QuicDispatcher {
106  public:
TestDispatcher(const QuicConfig * config,const QuicCryptoServerConfig * crypto_config,QuicVersionManager * version_manager,QuicRandom * random,ConnectionIdGeneratorInterface & generator)107   TestDispatcher(const QuicConfig* config,
108                  const QuicCryptoServerConfig* crypto_config,
109                  QuicVersionManager* version_manager, QuicRandom* random,
110                  ConnectionIdGeneratorInterface& generator)
111       : QuicDispatcher(config, crypto_config, version_manager,
112                        std::make_unique<MockQuicConnectionHelper>(),
113                        std::unique_ptr<QuicCryptoServerStreamBase::Helper>(
114                            new QuicSimpleCryptoServerStreamHelper()),
115                        std::make_unique<TestAlarmFactory>(),
116                        kQuicDefaultConnectionIdLength, generator),
117         random_(random) {}
118 
119   MOCK_METHOD(std::unique_ptr<QuicSession>, CreateQuicSession,
120               (QuicConnectionId connection_id,
121                const QuicSocketAddress& self_address,
122                const QuicSocketAddress& peer_address, absl::string_view alpn,
123                const ParsedQuicVersion& version,
124                const ParsedClientHello& parsed_chlo),
125               (override));
126 
127   struct TestQuicPerPacketContext : public QuicPerPacketContext {
128     std::string custom_packet_context;
129   };
130 
GetPerPacketContext() const131   std::unique_ptr<QuicPerPacketContext> GetPerPacketContext() const override {
132     auto test_context = std::make_unique<TestQuicPerPacketContext>();
133     test_context->custom_packet_context = custom_packet_context_;
134     return std::move(test_context);
135   }
136 
RestorePerPacketContext(std::unique_ptr<QuicPerPacketContext> context)137   void RestorePerPacketContext(
138       std::unique_ptr<QuicPerPacketContext> context) override {
139     TestQuicPerPacketContext* test_context =
140         static_cast<TestQuicPerPacketContext*>(context.get());
141     custom_packet_context_ = test_context->custom_packet_context;
142   }
143 
144   std::string custom_packet_context_;
145 
146   using QuicDispatcher::MaybeDispatchPacket;
147   using QuicDispatcher::SetAllowShortInitialServerConnectionIds;
148   using QuicDispatcher::writer;
149 
150   QuicRandom* random_;
151 };
152 
153 // A Connection class which unregisters the session from the dispatcher when
154 // sending connection close.
155 // It'd be slightly more realistic to do this from the Session but it would
156 // involve a lot more mocking.
157 class MockServerConnection : public MockQuicConnection {
158  public:
MockServerConnection(QuicConnectionId connection_id,MockQuicConnectionHelper * helper,MockAlarmFactory * alarm_factory,QuicDispatcher * dispatcher)159   MockServerConnection(QuicConnectionId connection_id,
160                        MockQuicConnectionHelper* helper,
161                        MockAlarmFactory* alarm_factory,
162                        QuicDispatcher* dispatcher)
163       : MockQuicConnection(connection_id, helper, alarm_factory,
164                            Perspective::IS_SERVER),
165         dispatcher_(dispatcher),
166         active_connection_ids_({connection_id}) {}
167 
AddNewConnectionId(QuicConnectionId id)168   void AddNewConnectionId(QuicConnectionId id) {
169     if (!dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(),
170                                             id)) {
171       return;
172     }
173     QuicConnectionPeer::SetServerConnectionId(this, id);
174     active_connection_ids_.push_back(id);
175   }
176 
UnconditionallyAddNewConnectionIdForTest(QuicConnectionId id)177   void UnconditionallyAddNewConnectionIdForTest(QuicConnectionId id) {
178     dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(), id);
179     active_connection_ids_.push_back(id);
180   }
181 
RetireConnectionId(QuicConnectionId id)182   void RetireConnectionId(QuicConnectionId id) {
183     auto it = std::find(active_connection_ids_.begin(),
184                         active_connection_ids_.end(), id);
185     QUICHE_DCHECK(it != active_connection_ids_.end());
186     dispatcher_->OnConnectionIdRetired(id);
187     active_connection_ids_.erase(it);
188   }
189 
GetActiveServerConnectionIds() const190   std::vector<QuicConnectionId> GetActiveServerConnectionIds() const override {
191     std::vector<QuicConnectionId> result;
192     for (const auto& cid : active_connection_ids_) {
193       result.push_back(cid);
194     }
195     auto original_connection_id = GetOriginalDestinationConnectionId();
196     if (std::find(result.begin(), result.end(), original_connection_id) ==
197         result.end()) {
198       result.push_back(original_connection_id);
199     }
200     return result;
201   }
202 
UnregisterOnConnectionClosed()203   void UnregisterOnConnectionClosed() {
204     QUIC_LOG(ERROR) << "Unregistering " << connection_id();
205     dispatcher_->OnConnectionClosed(connection_id(), QUIC_NO_ERROR,
206                                     "Unregistering.",
207                                     ConnectionCloseSource::FROM_SELF);
208   }
209 
210  private:
211   QuicDispatcher* dispatcher_;
212   std::vector<QuicConnectionId> active_connection_ids_;
213 };
214 
215 class QuicDispatcherTestBase : public QuicTestWithParam<ParsedQuicVersion> {
216  public:
QuicDispatcherTestBase()217   QuicDispatcherTestBase()
218       : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting()) {}
219 
QuicDispatcherTestBase(std::unique_ptr<ProofSource> proof_source)220   explicit QuicDispatcherTestBase(std::unique_ptr<ProofSource> proof_source)
221       : version_(GetParam()),
222         version_manager_(AllSupportedVersions()),
223         crypto_config_(QuicCryptoServerConfig::TESTING,
224                        QuicRandom::GetInstance(), std::move(proof_source),
225                        KeyExchangeSource::Default()),
226         server_address_(QuicIpAddress::Any4(), 5),
227         dispatcher_(new NiceMock<TestDispatcher>(
228             &config_, &crypto_config_, &version_manager_,
229             mock_helper_.GetRandomGenerator(), connection_id_generator_)),
230         time_wait_list_manager_(nullptr),
231         session1_(nullptr),
232         session2_(nullptr),
233         store_(nullptr),
234         connection_id_(1) {}
235 
SetUp()236   void SetUp() override {
237     dispatcher_->InitializeWithWriter(new NiceMock<MockPacketWriter>());
238     // Set the counter to some value to start with.
239     QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop(
240         dispatcher_.get(), kMaxNumSessionsToCreate);
241   }
242 
connection1()243   MockQuicConnection* connection1() {
244     if (session1_ == nullptr) {
245       return nullptr;
246     }
247     return reinterpret_cast<MockQuicConnection*>(session1_->connection());
248   }
249 
connection2()250   MockQuicConnection* connection2() {
251     if (session2_ == nullptr) {
252       return nullptr;
253     }
254     return reinterpret_cast<MockQuicConnection*>(session2_->connection());
255   }
256 
257   // Process a packet with an 8 byte connection id,
258   // 6 byte packet number, default path id, and packet number 1,
259   // using the version under test.
ProcessPacket(QuicSocketAddress peer_address,QuicConnectionId server_connection_id,bool has_version_flag,const std::string & data)260   void ProcessPacket(QuicSocketAddress peer_address,
261                      QuicConnectionId server_connection_id,
262                      bool has_version_flag, const std::string& data) {
263     ProcessPacket(peer_address, server_connection_id, has_version_flag, data,
264                   CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER);
265   }
266 
267   // Process a packet with a default path id, and packet number 1,
268   // using the version under test.
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)269   void ProcessPacket(QuicSocketAddress peer_address,
270                      QuicConnectionId server_connection_id,
271                      bool has_version_flag, const std::string& data,
272                      QuicConnectionIdIncluded server_connection_id_included,
273                      QuicPacketNumberLength packet_number_length) {
274     ProcessPacket(peer_address, server_connection_id, has_version_flag, data,
275                   server_connection_id_included, packet_number_length, 1);
276   }
277 
278   // Process a packet using the version under test.
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)279   void ProcessPacket(QuicSocketAddress peer_address,
280                      QuicConnectionId server_connection_id,
281                      bool has_version_flag, const std::string& data,
282                      QuicConnectionIdIncluded server_connection_id_included,
283                      QuicPacketNumberLength packet_number_length,
284                      uint64_t packet_number) {
285     ProcessPacket(peer_address, server_connection_id, has_version_flag,
286                   version_, data, true, server_connection_id_included,
287                   packet_number_length, packet_number);
288   }
289 
290   // Processes a packet.
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)291   void ProcessPacket(QuicSocketAddress peer_address,
292                      QuicConnectionId server_connection_id,
293                      bool has_version_flag, ParsedQuicVersion version,
294                      const std::string& data, bool full_padding,
295                      QuicConnectionIdIncluded server_connection_id_included,
296                      QuicPacketNumberLength packet_number_length,
297                      uint64_t packet_number) {
298     ProcessPacket(peer_address, server_connection_id, EmptyQuicConnectionId(),
299                   has_version_flag, version, data, full_padding,
300                   server_connection_id_included, CONNECTION_ID_ABSENT,
301                   packet_number_length, packet_number);
302   }
303 
304   // Processes a packet.
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)305   void ProcessPacket(QuicSocketAddress peer_address,
306                      QuicConnectionId server_connection_id,
307                      QuicConnectionId client_connection_id,
308                      bool has_version_flag, ParsedQuicVersion version,
309                      const std::string& data, bool full_padding,
310                      QuicConnectionIdIncluded server_connection_id_included,
311                      QuicConnectionIdIncluded client_connection_id_included,
312                      QuicPacketNumberLength packet_number_length,
313                      uint64_t packet_number) {
314     ParsedQuicVersionVector versions(SupportedVersions(version));
315     std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
316         server_connection_id, client_connection_id, has_version_flag, false,
317         packet_number, data, full_padding, server_connection_id_included,
318         client_connection_id_included, packet_number_length, &versions));
319     std::unique_ptr<QuicReceivedPacket> received_packet(
320         ConstructReceivedPacket(*packet, mock_helper_.GetClock()->Now()));
321     // Call ConnectionIdLength if the packet clears the Long Header bit, or
322     // if the test involves sending a connection ID that is too short
323     if (!has_version_flag || !version.AllowsVariableLengthConnectionIds() ||
324         server_connection_id.length() == 0 ||
325         server_connection_id_included == CONNECTION_ID_ABSENT) {
326       // Short headers will ask for the length
327       EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_))
328           .WillRepeatedly(Return(generated_connection_id_.has_value()
329                                      ? generated_connection_id_->length()
330                                      : kQuicDefaultConnectionIdLength));
331     }
332     ProcessReceivedPacket(std::move(received_packet), peer_address, version,
333                           server_connection_id);
334   }
335 
ProcessReceivedPacket(std::unique_ptr<QuicReceivedPacket> received_packet,const QuicSocketAddress & peer_address,const ParsedQuicVersion & version,const QuicConnectionId & server_connection_id)336   void ProcessReceivedPacket(
337       std::unique_ptr<QuicReceivedPacket> received_packet,
338       const QuicSocketAddress& peer_address, const ParsedQuicVersion& version,
339       const QuicConnectionId& server_connection_id) {
340     if (version.UsesQuicCrypto() &&
341         ChloExtractor::Extract(*received_packet, version, {}, nullptr,
342                                server_connection_id.length())) {
343       // Add CHLO packet to the beginning to be verified first, because it is
344       // also processed first by new session.
345       data_connection_map_[server_connection_id].push_front(
346           std::string(received_packet->data(), received_packet->length()));
347     } else {
348       // For non-CHLO, always append to last.
349       data_connection_map_[server_connection_id].push_back(
350           std::string(received_packet->data(), received_packet->length()));
351     }
352     dispatcher_->ProcessPacket(server_address_, peer_address, *received_packet);
353   }
354 
ValidatePacket(QuicConnectionId conn_id,const QuicEncryptedPacket & packet)355   void ValidatePacket(QuicConnectionId conn_id,
356                       const QuicEncryptedPacket& packet) {
357     EXPECT_EQ(data_connection_map_[conn_id].front().length(),
358               packet.AsStringPiece().length());
359     EXPECT_EQ(data_connection_map_[conn_id].front(), packet.AsStringPiece());
360     data_connection_map_[conn_id].pop_front();
361   }
362 
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)363   std::unique_ptr<QuicSession> CreateSession(
364       TestDispatcher* dispatcher, const QuicConfig& config,
365       QuicConnectionId connection_id, const QuicSocketAddress& /*peer_address*/,
366       MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory,
367       const QuicCryptoServerConfig* crypto_config,
368       QuicCompressedCertsCache* compressed_certs_cache,
369       TestQuicSpdyServerSession** session_ptr) {
370     MockServerConnection* connection = new MockServerConnection(
371         connection_id, helper, alarm_factory, dispatcher);
372     connection->SetQuicPacketWriter(dispatcher->writer(),
373                                     /*owns_writer=*/false);
374     auto session = std::make_unique<TestQuicSpdyServerSession>(
375         config, connection, crypto_config, compressed_certs_cache);
376     *session_ptr = session.get();
377     connection->set_visitor(session.get());
378     ON_CALL(*connection, CloseConnection(_, _, _))
379         .WillByDefault(WithoutArgs(Invoke(
380             connection, &MockServerConnection::UnregisterOnConnectionClosed)));
381     return session;
382   }
383 
CreateTimeWaitListManager()384   void CreateTimeWaitListManager() {
385     time_wait_list_manager_ = new MockTimeWaitListManager(
386         QuicDispatcherPeer::GetWriter(dispatcher_.get()), dispatcher_.get(),
387         mock_helper_.GetClock(), &mock_alarm_factory_);
388     // dispatcher_ takes the ownership of time_wait_list_manager_.
389     QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(),
390                                                time_wait_list_manager_);
391   }
392 
SerializeCHLO()393   std::string SerializeCHLO() {
394     CryptoHandshakeMessage client_hello;
395     client_hello.set_tag(kCHLO);
396     client_hello.SetStringPiece(kALPN, ExpectedAlpn());
397     return std::string(client_hello.GetSerialized().AsStringPiece());
398   }
399 
ProcessUndecryptableEarlyPacket(const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)400   void ProcessUndecryptableEarlyPacket(
401       const QuicSocketAddress& peer_address,
402       const QuicConnectionId& server_connection_id) {
403     ProcessUndecryptableEarlyPacket(version_, peer_address,
404                                     server_connection_id);
405   }
406 
ProcessUndecryptableEarlyPacket(const ParsedQuicVersion & version,const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)407   void ProcessUndecryptableEarlyPacket(
408       const ParsedQuicVersion& version, const QuicSocketAddress& peer_address,
409       const QuicConnectionId& server_connection_id) {
410     std::unique_ptr<QuicEncryptedPacket> encrypted_packet =
411         GetUndecryptableEarlyPacket(version, server_connection_id);
412     std::unique_ptr<QuicReceivedPacket> received_packet(ConstructReceivedPacket(
413         *encrypted_packet, mock_helper_.GetClock()->Now()));
414     ProcessReceivedPacket(std::move(received_packet), peer_address, version,
415                           server_connection_id);
416   }
417 
ProcessFirstFlight(const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)418   void ProcessFirstFlight(const QuicSocketAddress& peer_address,
419                           const QuicConnectionId& server_connection_id) {
420     ProcessFirstFlight(version_, peer_address, server_connection_id);
421   }
422 
ProcessFirstFlight(const ParsedQuicVersion & version,const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)423   void ProcessFirstFlight(const ParsedQuicVersion& version,
424                           const QuicSocketAddress& peer_address,
425                           const QuicConnectionId& server_connection_id) {
426     ProcessFirstFlight(version, peer_address, server_connection_id,
427                        EmptyQuicConnectionId());
428   }
429 
ProcessFirstFlight(const ParsedQuicVersion & version,const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id,const QuicConnectionId & client_connection_id)430   void ProcessFirstFlight(const ParsedQuicVersion& version,
431                           const QuicSocketAddress& peer_address,
432                           const QuicConnectionId& server_connection_id,
433                           const QuicConnectionId& client_connection_id) {
434     ProcessFirstFlight(version, peer_address, server_connection_id,
435                        client_connection_id, TestClientCryptoConfig());
436   }
437 
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)438   void ProcessFirstFlight(
439       const ParsedQuicVersion& version, const QuicSocketAddress& peer_address,
440       const QuicConnectionId& server_connection_id,
441       const QuicConnectionId& client_connection_id,
442       std::unique_ptr<QuicCryptoClientConfig> client_crypto_config) {
443     if (expect_generator_is_called_) {
444       if (version.AllowsVariableLengthConnectionIds()) {
445         EXPECT_CALL(connection_id_generator_,
446                     MaybeReplaceConnectionId(server_connection_id, version))
447             .WillOnce(Return(generated_connection_id_));
448       } else {
449         EXPECT_CALL(connection_id_generator_,
450                     MaybeReplaceConnectionId(server_connection_id, version))
451             .WillOnce(Return(absl::nullopt));
452       }
453     }
454     std::vector<std::unique_ptr<QuicReceivedPacket>> packets =
455         GetFirstFlightOfPackets(version, DefaultQuicConfig(),
456                                 server_connection_id, client_connection_id,
457                                 std::move(client_crypto_config));
458     for (auto&& packet : packets) {
459       ProcessReceivedPacket(std::move(packet), peer_address, version,
460                             server_connection_id);
461     }
462   }
463 
TestClientCryptoConfig()464   std::unique_ptr<QuicCryptoClientConfig> TestClientCryptoConfig() {
465     auto client_crypto_config = std::make_unique<QuicCryptoClientConfig>(
466         crypto_test_utils::ProofVerifierForTesting());
467     if (address_token_.has_value()) {
468       client_crypto_config->LookupOrCreate(TestServerId())
469           ->set_source_address_token(*address_token_);
470     }
471     return client_crypto_config;
472   }
473 
474   // If called, the first flight packets generated in |ProcessFirstFlight| will
475   // contain the given |address_token|.
SetAddressToken(std::string address_token)476   void SetAddressToken(std::string address_token) {
477     address_token_ = std::move(address_token);
478   }
479 
ExpectedAlpnForVersion(ParsedQuicVersion version)480   std::string ExpectedAlpnForVersion(ParsedQuicVersion version) {
481     return AlpnForVersion(version);
482   }
483 
ExpectedAlpn()484   std::string ExpectedAlpn() { return ExpectedAlpnForVersion(version_); }
485 
ParsedClientHelloForTest()486   ParsedClientHello ParsedClientHelloForTest() {
487     ParsedClientHello parsed_chlo;
488     parsed_chlo.alpns = {ExpectedAlpn()};
489     parsed_chlo.sni = TestHostname();
490     return parsed_chlo;
491   }
492 
MarkSession1Deleted()493   void MarkSession1Deleted() { session1_ = nullptr; }
494 
VerifyVersionSupported(ParsedQuicVersion version)495   void VerifyVersionSupported(ParsedQuicVersion version) {
496     expect_generator_is_called_ = true;
497     QuicConnectionId connection_id = TestConnectionId(++connection_id_);
498     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
499     EXPECT_CALL(*dispatcher_,
500                 CreateQuicSession(connection_id, _, client_address,
501                                   Eq(ExpectedAlpnForVersion(version)), _, _))
502         .WillOnce(Return(ByMove(CreateSession(
503             dispatcher_.get(), config_, connection_id, client_address,
504             &mock_helper_, &mock_alarm_factory_, &crypto_config_,
505             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
506     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
507                 ProcessUdpPacket(_, _, _))
508         .WillOnce(WithArg<2>(
509             Invoke([this, connection_id](const QuicEncryptedPacket& packet) {
510               ValidatePacket(connection_id, packet);
511             })));
512     ProcessFirstFlight(version, client_address, connection_id);
513   }
514 
VerifyVersionNotSupported(ParsedQuicVersion version)515   void VerifyVersionNotSupported(ParsedQuicVersion version) {
516     QuicConnectionId connection_id = TestConnectionId(++connection_id_);
517     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
518     EXPECT_CALL(*dispatcher_,
519                 CreateQuicSession(connection_id, _, client_address, _, _, _))
520         .Times(0);
521     expect_generator_is_called_ = false;
522     ProcessFirstFlight(version, client_address, connection_id);
523   }
524 
525   void TestTlsMultiPacketClientHello(bool add_reordering,
526                                      bool long_connection_id);
527 
528   void TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
529       const QuicConnectionId& server_connection_id,
530       const QuicConnectionId& client_connection_id);
531 
GetClearResetAddressesAlarm()532   TestAlarmFactory::TestAlarm* GetClearResetAddressesAlarm() {
533     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
534         QuicDispatcherPeer::GetClearResetAddressesAlarm(dispatcher_.get()));
535   }
536 
537   ParsedQuicVersion version_;
538   MockQuicConnectionHelper mock_helper_;
539   MockAlarmFactory mock_alarm_factory_;
540   QuicConfig config_;
541   QuicVersionManager version_manager_;
542   QuicCryptoServerConfig crypto_config_;
543   QuicSocketAddress server_address_;
544   // Set to false if the dispatcher won't create a session.
545   bool expect_generator_is_called_ = true;
546   // Set in conditions where the generator should return a different connection
547   // ID.
548   absl::optional<QuicConnectionId> generated_connection_id_;
549   MockConnectionIdGenerator connection_id_generator_;
550   std::unique_ptr<NiceMock<TestDispatcher>> dispatcher_;
551   MockTimeWaitListManager* time_wait_list_manager_;
552   TestQuicSpdyServerSession* session1_;
553   TestQuicSpdyServerSession* session2_;
554   std::map<QuicConnectionId, std::list<std::string>> data_connection_map_;
555   QuicBufferedPacketStore* store_;
556   uint64_t connection_id_;
557   absl::optional<std::string> address_token_;
558 };
559 
560 class QuicDispatcherTestAllVersions : public QuicDispatcherTestBase {};
561 class QuicDispatcherTestOneVersion : public QuicDispatcherTestBase {};
562 
563 INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsAllVersions,
564                          QuicDispatcherTestAllVersions,
565                          ::testing::ValuesIn(CurrentSupportedVersions()),
566                          ::testing::PrintToStringParamName());
567 
568 INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsOneVersion,
569                          QuicDispatcherTestOneVersion,
570                          ::testing::Values(CurrentSupportedVersions().front()),
571                          ::testing::PrintToStringParamName());
572 
TEST_P(QuicDispatcherTestAllVersions,TlsClientHelloCreatesSession)573 TEST_P(QuicDispatcherTestAllVersions, TlsClientHelloCreatesSession) {
574   if (version_.UsesQuicCrypto()) {
575     return;
576   }
577   SetAddressToken("hsdifghdsaifnasdpfjdsk");
578 
579   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
580 
581   EXPECT_CALL(
582       *dispatcher_,
583       CreateQuicSession(TestConnectionId(1), _, client_address,
584                         Eq(ExpectedAlpn()), _, Eq(ParsedClientHelloForTest())))
585       .WillOnce(Return(ByMove(CreateSession(
586           dispatcher_.get(), config_, TestConnectionId(1), client_address,
587           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
588           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
589   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
590               ProcessUdpPacket(_, _, _))
591       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
592         ValidatePacket(TestConnectionId(1), packet);
593       })));
594 
595   ProcessFirstFlight(client_address, TestConnectionId(1));
596 }
597 
TEST_P(QuicDispatcherTestAllVersions,VariableServerConnectionIdLength)598 TEST_P(QuicDispatcherTestAllVersions, VariableServerConnectionIdLength) {
599   QuicConnectionId old_id = TestConnectionId(1);
600   // Return a connection ID that is not expected_server_connection_id_length_
601   // bytes long.
602   if (version_.HasIetfQuicFrames()) {
603     generated_connection_id_ =
604         QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
605                           0x09, 0x0a, 0x0b});
606   }
607   QuicConnectionId new_id =
608       generated_connection_id_.has_value() ? *generated_connection_id_ : old_id;
609   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
610   EXPECT_CALL(*dispatcher_,
611               CreateQuicSession(new_id, _, client_address, Eq(ExpectedAlpn()),
612                                 _, Eq(ParsedClientHelloForTest())))
613       .WillOnce(Return(ByMove(CreateSession(
614           dispatcher_.get(), config_, new_id, client_address, &mock_helper_,
615           &mock_alarm_factory_, &crypto_config_,
616           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
617   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
618               ProcessUdpPacket(_, _, _))
619       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
620         ValidatePacket(TestConnectionId(1), packet);
621       })));
622   ProcessFirstFlight(client_address, old_id);
623 
624   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
625               ProcessUdpPacket(_, _, _))
626       .Times(1);
627   ProcessPacket(client_address, new_id, false, "foo");
628 }
629 
TestTlsMultiPacketClientHello(bool add_reordering,bool long_connection_id)630 void QuicDispatcherTestBase::TestTlsMultiPacketClientHello(
631     bool add_reordering, bool long_connection_id) {
632   if (!version_.UsesTls()) {
633     return;
634   }
635   SetAddressToken("857293462398");
636 
637   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
638   QuicConnectionId original_connection_id, new_connection_id;
639   if (long_connection_id) {
640     original_connection_id = TestConnectionIdNineBytesLong(1);
641     new_connection_id = kReturnConnectionId;
642     EXPECT_CALL(connection_id_generator_,
643                 MaybeReplaceConnectionId(original_connection_id, version_))
644         .WillOnce(Return(new_connection_id));
645 
646   } else {
647     original_connection_id = TestConnectionId();
648     new_connection_id = original_connection_id;
649     EXPECT_CALL(connection_id_generator_,
650                 MaybeReplaceConnectionId(original_connection_id, version_))
651         .WillOnce(Return(absl::nullopt));
652   }
653   QuicConfig client_config = DefaultQuicConfig();
654   // Add a 2000-byte custom parameter to increase the length of the CHLO.
655   constexpr auto kCustomParameterId =
656       static_cast<TransportParameters::TransportParameterId>(0xff33);
657   std::string kCustomParameterValue(2000, '-');
658   client_config.custom_transport_parameters_to_send()[kCustomParameterId] =
659       kCustomParameterValue;
660   std::vector<std::unique_ptr<QuicReceivedPacket>> packets =
661       GetFirstFlightOfPackets(version_, client_config, original_connection_id,
662                               EmptyQuicConnectionId(),
663                               TestClientCryptoConfig());
664   ASSERT_EQ(packets.size(), 2u);
665   if (add_reordering) {
666     std::swap(packets[0], packets[1]);
667   }
668 
669   // Processing the first packet should not create a new session.
670   ProcessReceivedPacket(std::move(packets[0]), client_address, version_,
671                         original_connection_id);
672 
673   EXPECT_EQ(dispatcher_->NumSessions(), 0u)
674       << "No session should be created before the rest of the CHLO arrives.";
675 
676   // Processing the second packet should create the new session.
677   EXPECT_CALL(
678       *dispatcher_,
679       CreateQuicSession(new_connection_id, _, client_address,
680                         Eq(ExpectedAlpn()), _, Eq(ParsedClientHelloForTest())))
681       .WillOnce(Return(ByMove(CreateSession(
682           dispatcher_.get(), config_, new_connection_id, client_address,
683           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
684           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
685   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
686               ProcessUdpPacket(_, _, _))
687       .Times(2);
688 
689   ProcessReceivedPacket(std::move(packets[1]), client_address, version_,
690                         original_connection_id);
691   EXPECT_EQ(dispatcher_->NumSessions(), 1u);
692 }
693 
TEST_P(QuicDispatcherTestAllVersions,TlsMultiPacketClientHello)694 TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHello) {
695   TestTlsMultiPacketClientHello(/*add_reordering=*/false,
696                                 /*long_connection_id=*/false);
697 }
698 
TEST_P(QuicDispatcherTestAllVersions,TlsMultiPacketClientHelloWithReordering)699 TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithReordering) {
700   TestTlsMultiPacketClientHello(/*add_reordering=*/true,
701                                 /*long_connection_id=*/false);
702 }
703 
TEST_P(QuicDispatcherTestAllVersions,TlsMultiPacketClientHelloWithLongId)704 TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithLongId) {
705   TestTlsMultiPacketClientHello(/*add_reordering=*/false,
706                                 /*long_connection_id=*/true);
707 }
708 
TEST_P(QuicDispatcherTestAllVersions,TlsMultiPacketClientHelloWithReorderingAndLongId)709 TEST_P(QuicDispatcherTestAllVersions,
710        TlsMultiPacketClientHelloWithReorderingAndLongId) {
711   TestTlsMultiPacketClientHello(/*add_reordering=*/true,
712                                 /*long_connection_id=*/true);
713 }
714 
TEST_P(QuicDispatcherTestAllVersions,ProcessPackets)715 TEST_P(QuicDispatcherTestAllVersions, ProcessPackets) {
716   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
717 
718   EXPECT_CALL(
719       *dispatcher_,
720       CreateQuicSession(TestConnectionId(1), _, client_address,
721                         Eq(ExpectedAlpn()), _, Eq(ParsedClientHelloForTest())))
722       .WillOnce(Return(ByMove(CreateSession(
723           dispatcher_.get(), config_, TestConnectionId(1), client_address,
724           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
725           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
726   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
727               ProcessUdpPacket(_, _, _))
728       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
729         ValidatePacket(TestConnectionId(1), packet);
730       })));
731   ProcessFirstFlight(client_address, TestConnectionId(1));
732 
733   EXPECT_CALL(
734       *dispatcher_,
735       CreateQuicSession(TestConnectionId(2), _, client_address,
736                         Eq(ExpectedAlpn()), _, Eq(ParsedClientHelloForTest())))
737       .WillOnce(Return(ByMove(CreateSession(
738           dispatcher_.get(), config_, TestConnectionId(2), client_address,
739           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
740           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))));
741   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()),
742               ProcessUdpPacket(_, _, _))
743       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
744         ValidatePacket(TestConnectionId(2), packet);
745       })));
746   ProcessFirstFlight(client_address, TestConnectionId(2));
747 
748   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
749               ProcessUdpPacket(_, _, _))
750       .Times(1)
751       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
752         ValidatePacket(TestConnectionId(1), packet);
753       })));
754   ProcessPacket(client_address, TestConnectionId(1), false, "data");
755 }
756 
757 // Regression test of b/93325907.
TEST_P(QuicDispatcherTestAllVersions,DispatcherDoesNotRejectPacketNumberZero)758 TEST_P(QuicDispatcherTestAllVersions, DispatcherDoesNotRejectPacketNumberZero) {
759   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
760 
761   EXPECT_CALL(*dispatcher_,
762               CreateQuicSession(TestConnectionId(1), _, client_address,
763                                 Eq(ExpectedAlpn()), _, _))
764       .WillOnce(Return(ByMove(CreateSession(
765           dispatcher_.get(), config_, TestConnectionId(1), client_address,
766           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
767           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
768   // Verify both packets 1 and 2 are processed by connection 1.
769   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
770               ProcessUdpPacket(_, _, _))
771       .Times(2)
772       .WillRepeatedly(
773           WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
774             ValidatePacket(TestConnectionId(1), packet);
775           })));
776   ProcessFirstFlight(client_address, TestConnectionId(1));
777   // Packet number 256 with packet number length 1 would be considered as 0 in
778   // dispatcher.
779   ProcessPacket(client_address, TestConnectionId(1), false, version_, "", true,
780                 CONNECTION_ID_PRESENT, PACKET_1BYTE_PACKET_NUMBER, 256);
781 }
782 
TEST_P(QuicDispatcherTestOneVersion,StatelessVersionNegotiation)783 TEST_P(QuicDispatcherTestOneVersion, StatelessVersionNegotiation) {
784   CreateTimeWaitListManager();
785   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
786 
787   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
788   EXPECT_CALL(
789       *time_wait_list_manager_,
790       SendVersionNegotiationPacket(TestConnectionId(1), _, _, _, _, _, _, _))
791       .Times(1);
792   expect_generator_is_called_ = false;
793   ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address,
794                      TestConnectionId(1));
795 }
796 
TEST_P(QuicDispatcherTestOneVersion,StatelessVersionNegotiationWithVeryLongConnectionId)797 TEST_P(QuicDispatcherTestOneVersion,
798        StatelessVersionNegotiationWithVeryLongConnectionId) {
799   QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(33);
800   CreateTimeWaitListManager();
801   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
802 
803   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
804   EXPECT_CALL(*time_wait_list_manager_,
805               SendVersionNegotiationPacket(connection_id, _, _, _, _, _, _, _))
806       .Times(1);
807   expect_generator_is_called_ = false;
808   ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address,
809                      connection_id);
810 }
811 
TEST_P(QuicDispatcherTestOneVersion,StatelessVersionNegotiationWithClientConnectionId)812 TEST_P(QuicDispatcherTestOneVersion,
813        StatelessVersionNegotiationWithClientConnectionId) {
814   CreateTimeWaitListManager();
815   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
816 
817   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
818   EXPECT_CALL(*time_wait_list_manager_,
819               SendVersionNegotiationPacket(
820                   TestConnectionId(1), TestConnectionId(2), _, _, _, _, _, _))
821       .Times(1);
822   expect_generator_is_called_ = false;
823   ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address,
824                      TestConnectionId(1), TestConnectionId(2));
825 }
826 
TEST_P(QuicDispatcherTestOneVersion,NoVersionNegotiationWithSmallPacket)827 TEST_P(QuicDispatcherTestOneVersion, NoVersionNegotiationWithSmallPacket) {
828   CreateTimeWaitListManager();
829   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
830 
831   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
832   EXPECT_CALL(*time_wait_list_manager_,
833               SendVersionNegotiationPacket(_, _, _, _, _, _, _, _))
834       .Times(0);
835   std::string chlo = SerializeCHLO() + std::string(1200, 'a');
836   // Truncate to 1100 bytes of payload which results in a packet just
837   // under 1200 bytes after framing, packet, and encryption overhead.
838   QUICHE_DCHECK_LE(1200u, chlo.length());
839   std::string truncated_chlo = chlo.substr(0, 1100);
840   QUICHE_DCHECK_EQ(1100u, truncated_chlo.length());
841   ProcessPacket(client_address, TestConnectionId(1), true,
842                 QuicVersionReservedForNegotiation(), truncated_chlo, false,
843                 CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1);
844 }
845 
846 // Disabling CHLO size validation allows the dispatcher to send version
847 // negotiation packets in response to a CHLO that is otherwise too small.
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationWithoutChloSizeValidation)848 TEST_P(QuicDispatcherTestOneVersion,
849        VersionNegotiationWithoutChloSizeValidation) {
850   crypto_config_.set_validate_chlo_size(false);
851 
852   CreateTimeWaitListManager();
853   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
854 
855   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
856   EXPECT_CALL(*time_wait_list_manager_,
857               SendVersionNegotiationPacket(_, _, _, _, _, _, _, _))
858       .Times(1);
859   std::string chlo = SerializeCHLO() + std::string(1200, 'a');
860   // Truncate to 1100 bytes of payload which results in a packet just
861   // under 1200 bytes after framing, packet, and encryption overhead.
862   QUICHE_DCHECK_LE(1200u, chlo.length());
863   std::string truncated_chlo = chlo.substr(0, 1100);
864   QUICHE_DCHECK_EQ(1100u, truncated_chlo.length());
865   ProcessPacket(client_address, TestConnectionId(1), true,
866                 QuicVersionReservedForNegotiation(), truncated_chlo, true,
867                 CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1);
868 }
869 
TEST_P(QuicDispatcherTestAllVersions,Shutdown)870 TEST_P(QuicDispatcherTestAllVersions, Shutdown) {
871   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
872 
873   EXPECT_CALL(*dispatcher_,
874               CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _))
875       .WillOnce(Return(ByMove(CreateSession(
876           dispatcher_.get(), config_, TestConnectionId(1), client_address,
877           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
878           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
879   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
880               ProcessUdpPacket(_, _, _))
881       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
882         ValidatePacket(TestConnectionId(1), packet);
883       })));
884 
885   ProcessFirstFlight(client_address, TestConnectionId(1));
886 
887   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
888               CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
889 
890   dispatcher_->Shutdown();
891 }
892 
TEST_P(QuicDispatcherTestAllVersions,TimeWaitListManager)893 TEST_P(QuicDispatcherTestAllVersions, TimeWaitListManager) {
894   CreateTimeWaitListManager();
895 
896   // Create a new session.
897   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
898   QuicConnectionId connection_id = TestConnectionId(1);
899   EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address,
900                                               Eq(ExpectedAlpn()), _, _))
901       .WillOnce(Return(ByMove(CreateSession(
902           dispatcher_.get(), config_, connection_id, client_address,
903           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
904           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
905   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
906               ProcessUdpPacket(_, _, _))
907       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
908         ValidatePacket(TestConnectionId(1), packet);
909       })));
910 
911   ProcessFirstFlight(client_address, connection_id);
912 
913   // Now close the connection, which should add it to the time wait list.
914   session1_->connection()->CloseConnection(
915       QUIC_INVALID_VERSION,
916       "Server: Packet 2 without version flag before version negotiated.",
917       ConnectionCloseBehavior::SILENT_CLOSE);
918   EXPECT_TRUE(time_wait_list_manager_->IsConnectionIdInTimeWait(connection_id));
919 
920   // Dispatcher forwards subsequent packets for this connection_id to the time
921   // wait list manager.
922   EXPECT_CALL(*time_wait_list_manager_,
923               ProcessPacket(_, _, connection_id, _, _, _))
924       .Times(1);
925   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
926       .Times(0);
927   ProcessPacket(client_address, connection_id, true, "data");
928 }
929 
TEST_P(QuicDispatcherTestAllVersions,NoVersionPacketToTimeWaitListManager)930 TEST_P(QuicDispatcherTestAllVersions, NoVersionPacketToTimeWaitListManager) {
931   CreateTimeWaitListManager();
932 
933   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
934   QuicConnectionId connection_id = TestConnectionId(1);
935   // Dispatcher forwards all packets for this connection_id to the time wait
936   // list manager.
937   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
938   EXPECT_CALL(*time_wait_list_manager_,
939               ProcessPacket(_, _, connection_id, _, _, _))
940       .Times(0);
941   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
942       .Times(0);
943   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
944       .Times(1);
945   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
946                 "data");
947 }
948 
TEST_P(QuicDispatcherTestAllVersions,DonotTimeWaitPacketsWithUnknownConnectionIdAndNoVersion)949 TEST_P(QuicDispatcherTestAllVersions,
950        DonotTimeWaitPacketsWithUnknownConnectionIdAndNoVersion) {
951   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
952   CreateTimeWaitListManager();
953 
954   uint8_t short_packet[22] = {0x70, 0xa7, 0x02, 0x6b};
955   uint8_t valid_size_packet[23] = {0x70, 0xa7, 0x02, 0x6c};
956   size_t short_packet_len;
957   if (version_.HasIetfInvariantHeader()) {
958     short_packet_len = 21;
959   } else {
960     short_packet_len = 22;
961     short_packet[0] = 0x0a;
962     valid_size_packet[0] = 0x0a;
963   }
964   QuicReceivedPacket packet(reinterpret_cast<char*>(short_packet),
965                             short_packet_len, QuicTime::Zero());
966   QuicReceivedPacket packet2(reinterpret_cast<char*>(valid_size_packet),
967                              short_packet_len + 1, QuicTime::Zero());
968   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
969   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
970       .Times(0);
971   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
972       .Times(0);
973   // Verify small packet is silently dropped.
974   if (version_.HasIetfInvariantHeader()) {
975     EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0xa7))
976         .WillOnce(Return(kQuicDefaultConnectionIdLength));
977   } else {
978     EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)).Times(0);
979   }
980   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
981       .Times(0);
982   dispatcher_->ProcessPacket(server_address_, client_address, packet);
983   if (version_.HasIetfInvariantHeader()) {
984     EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0xa7))
985         .WillOnce(Return(kQuicDefaultConnectionIdLength));
986   } else {
987     EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)).Times(0);
988   }
989   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
990       .Times(1);
991   dispatcher_->ProcessPacket(server_address_, client_address, packet2);
992 }
993 
TEST_P(QuicDispatcherTestOneVersion,DropPacketWithInvalidFlags)994 TEST_P(QuicDispatcherTestOneVersion, DropPacketWithInvalidFlags) {
995   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
996   CreateTimeWaitListManager();
997   uint8_t all_zero_packet[1200] = {};
998   QuicReceivedPacket packet(reinterpret_cast<char*>(all_zero_packet),
999                             sizeof(all_zero_packet), QuicTime::Zero());
1000   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1001   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1002       .Times(0);
1003   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1004       .Times(0);
1005   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1006       .Times(0);
1007   EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_))
1008       .WillOnce(Return(kQuicDefaultConnectionIdLength));
1009   dispatcher_->ProcessPacket(server_address_, client_address, packet);
1010 }
1011 
TEST_P(QuicDispatcherTestAllVersions,LimitResetsToSameClientAddress)1012 TEST_P(QuicDispatcherTestAllVersions, LimitResetsToSameClientAddress) {
1013   CreateTimeWaitListManager();
1014 
1015   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1016   QuicSocketAddress client_address2(QuicIpAddress::Loopback4(), 2);
1017   QuicSocketAddress client_address3(QuicIpAddress::Loopback6(), 1);
1018   QuicConnectionId connection_id = TestConnectionId(1);
1019 
1020   // Verify only one reset is sent to the address, although multiple packets
1021   // are received.
1022   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1023       .Times(1);
1024   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
1025                 "data");
1026   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
1027                 "data2");
1028   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
1029                 "data3");
1030 
1031   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1032       .Times(2);
1033   ProcessPacket(client_address2, connection_id, /*has_version_flag=*/false,
1034                 "data");
1035   ProcessPacket(client_address3, connection_id, /*has_version_flag=*/false,
1036                 "data");
1037 }
1038 
TEST_P(QuicDispatcherTestAllVersions,StopSendingResetOnTooManyRecentAddresses)1039 TEST_P(QuicDispatcherTestAllVersions,
1040        StopSendingResetOnTooManyRecentAddresses) {
1041   SetQuicFlag(quic_max_recent_stateless_reset_addresses, 2);
1042   const size_t kTestLifeTimeMs = 10;
1043   SetQuicFlag(quic_recent_stateless_reset_addresses_lifetime_ms,
1044               kTestLifeTimeMs);
1045   CreateTimeWaitListManager();
1046 
1047   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1048   QuicSocketAddress client_address2(QuicIpAddress::Loopback4(), 2);
1049   QuicSocketAddress client_address3(QuicIpAddress::Loopback6(), 1);
1050   QuicConnectionId connection_id = TestConnectionId(1);
1051 
1052   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1053       .Times(2);
1054   EXPECT_FALSE(GetClearResetAddressesAlarm()->IsSet());
1055   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
1056                 "data");
1057   const QuicTime expected_deadline =
1058       mock_helper_.GetClock()->Now() +
1059       QuicTime::Delta::FromMilliseconds(kTestLifeTimeMs);
1060   ASSERT_TRUE(GetClearResetAddressesAlarm()->IsSet());
1061   EXPECT_EQ(expected_deadline, GetClearResetAddressesAlarm()->deadline());
1062   // Received no version packet 2 after 5ms.
1063   mock_helper_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
1064   ProcessPacket(client_address2, connection_id, /*has_version_flag=*/false,
1065                 "data");
1066   ASSERT_TRUE(GetClearResetAddressesAlarm()->IsSet());
1067   // Verify deadline does not change.
1068   EXPECT_EQ(expected_deadline, GetClearResetAddressesAlarm()->deadline());
1069   // Verify reset gets throttled since there are too many recent addresses.
1070   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1071       .Times(0);
1072   ProcessPacket(client_address3, connection_id, /*has_version_flag=*/false,
1073                 "data");
1074 
1075   mock_helper_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
1076   GetClearResetAddressesAlarm()->Fire();
1077   EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _))
1078       .Times(2);
1079   ProcessPacket(client_address, connection_id, /*has_version_flag=*/false,
1080                 "data");
1081   ProcessPacket(client_address2, connection_id, /*has_version_flag=*/false,
1082                 "data");
1083   ProcessPacket(client_address3, connection_id, /*has_version_flag=*/false,
1084                 "data");
1085 }
1086 
1087 // Makes sure nine-byte connection IDs are replaced by 8-byte ones.
TEST_P(QuicDispatcherTestAllVersions,LongConnectionIdLengthReplaced)1088 TEST_P(QuicDispatcherTestAllVersions, LongConnectionIdLengthReplaced) {
1089   if (!version_.AllowsVariableLengthConnectionIds()) {
1090     // When variable length connection IDs are not supported, the connection
1091     // fails. See StrayPacketTruncatedConnectionId.
1092     return;
1093   }
1094   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1095 
1096   QuicConnectionId bad_connection_id = TestConnectionIdNineBytesLong(2);
1097   generated_connection_id_ = kReturnConnectionId;
1098 
1099   EXPECT_CALL(*dispatcher_,
1100               CreateQuicSession(*generated_connection_id_, _, client_address,
1101                                 Eq(ExpectedAlpn()), _, _))
1102       .WillOnce(Return(ByMove(CreateSession(
1103           dispatcher_.get(), config_, *generated_connection_id_, client_address,
1104           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1105           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1106   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1107               ProcessUdpPacket(_, _, _))
1108       .WillOnce(WithArg<2>(
1109           Invoke([this, bad_connection_id](const QuicEncryptedPacket& packet) {
1110             ValidatePacket(bad_connection_id, packet);
1111           })));
1112   ProcessFirstFlight(client_address, bad_connection_id);
1113 }
1114 
1115 // Makes sure zero-byte connection IDs are replaced by 8-byte ones.
TEST_P(QuicDispatcherTestAllVersions,InvalidShortConnectionIdLengthReplaced)1116 TEST_P(QuicDispatcherTestAllVersions, InvalidShortConnectionIdLengthReplaced) {
1117   if (!version_.AllowsVariableLengthConnectionIds()) {
1118     // When variable length connection IDs are not supported, the connection
1119     // fails. See StrayPacketTruncatedConnectionId.
1120     return;
1121   }
1122   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1123 
1124   QuicConnectionId bad_connection_id = EmptyQuicConnectionId();
1125   generated_connection_id_ = kReturnConnectionId;
1126 
1127   // Disable validation of invalid short connection IDs.
1128   dispatcher_->SetAllowShortInitialServerConnectionIds(true);
1129   // Note that StrayPacketTruncatedConnectionId covers the case where the
1130   // validation is still enabled.
1131   EXPECT_CALL(*dispatcher_,
1132               CreateQuicSession(*generated_connection_id_, _, client_address,
1133                                 Eq(ExpectedAlpn()), _, _))
1134       .WillOnce(Return(ByMove(CreateSession(
1135           dispatcher_.get(), config_, *generated_connection_id_, client_address,
1136           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1137           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1138   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1139               ProcessUdpPacket(_, _, _))
1140       .WillOnce(WithArg<2>(
1141           Invoke([this, bad_connection_id](const QuicEncryptedPacket& packet) {
1142             ValidatePacket(bad_connection_id, packet);
1143           })));
1144   ProcessFirstFlight(client_address, bad_connection_id);
1145 }
1146 
1147 // Makes sure TestConnectionId(1) creates a new connection and
1148 // TestConnectionIdNineBytesLong(2) gets replaced.
TEST_P(QuicDispatcherTestAllVersions,MixGoodAndBadConnectionIdLengthPackets)1149 TEST_P(QuicDispatcherTestAllVersions, MixGoodAndBadConnectionIdLengthPackets) {
1150   if (!version_.AllowsVariableLengthConnectionIds()) {
1151     return;
1152   }
1153 
1154   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1155   QuicConnectionId bad_connection_id = TestConnectionIdNineBytesLong(2);
1156 
1157   EXPECT_CALL(*dispatcher_,
1158               CreateQuicSession(TestConnectionId(1), _, client_address,
1159                                 Eq(ExpectedAlpn()), _, _))
1160       .WillOnce(Return(ByMove(CreateSession(
1161           dispatcher_.get(), config_, TestConnectionId(1), client_address,
1162           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1163           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1164   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1165               ProcessUdpPacket(_, _, _))
1166       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1167         ValidatePacket(TestConnectionId(1), packet);
1168       })));
1169   ProcessFirstFlight(client_address, TestConnectionId(1));
1170 
1171   generated_connection_id_ = kReturnConnectionId;
1172   EXPECT_CALL(*dispatcher_,
1173               CreateQuicSession(*generated_connection_id_, _, client_address,
1174                                 Eq(ExpectedAlpn()), _, _))
1175       .WillOnce(Return(ByMove(CreateSession(
1176           dispatcher_.get(), config_, *generated_connection_id_, client_address,
1177           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1178           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))));
1179   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()),
1180               ProcessUdpPacket(_, _, _))
1181       .WillOnce(WithArg<2>(
1182           Invoke([this, bad_connection_id](const QuicEncryptedPacket& packet) {
1183             ValidatePacket(bad_connection_id, packet);
1184           })));
1185   ProcessFirstFlight(client_address, bad_connection_id);
1186 
1187   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1188               ProcessUdpPacket(_, _, _))
1189       .Times(1)
1190       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1191         ValidatePacket(TestConnectionId(1), packet);
1192       })));
1193   ProcessPacket(client_address, TestConnectionId(1), false, "data");
1194 }
1195 
TEST_P(QuicDispatcherTestAllVersions,ProcessPacketWithZeroPort)1196 TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithZeroPort) {
1197   CreateTimeWaitListManager();
1198 
1199   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 0);
1200 
1201   // dispatcher_ should drop this packet.
1202   EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _,
1203                                               client_address, _, _, _))
1204       .Times(0);
1205   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1206       .Times(0);
1207   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1208       .Times(0);
1209   ProcessPacket(client_address, TestConnectionId(1), /*has_version_flag=*/true,
1210                 "data");
1211 }
1212 
TEST_P(QuicDispatcherTestAllVersions,ProcessPacketWithBlockedPort)1213 TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithBlockedPort) {
1214   CreateTimeWaitListManager();
1215 
1216   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 17);
1217 
1218   // dispatcher_ should drop this packet.
1219   EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _,
1220                                               client_address, _, _, _))
1221       .Times(0);
1222   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1223       .Times(0);
1224   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1225       .Times(0);
1226   ProcessPacket(client_address, TestConnectionId(1), /*has_version_flag=*/true,
1227                 "data");
1228 }
1229 
TEST_P(QuicDispatcherTestAllVersions,ProcessPacketWithNonBlockedPort)1230 TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithNonBlockedPort) {
1231   CreateTimeWaitListManager();
1232 
1233   // Port 443 must not be blocked because it might be useful for proxies to send
1234   // proxied traffic with source port 443 as that allows building a full QUIC
1235   // proxy using a single UDP socket.
1236   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 443);
1237 
1238   // dispatcher_ should not drop this packet.
1239   EXPECT_CALL(*dispatcher_,
1240               CreateQuicSession(TestConnectionId(1), _, client_address,
1241                                 Eq(ExpectedAlpn()), _, _))
1242       .WillOnce(Return(ByMove(CreateSession(
1243           dispatcher_.get(), config_, TestConnectionId(1), client_address,
1244           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1245           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1246   ProcessFirstFlight(client_address, TestConnectionId(1));
1247 }
1248 
TEST_P(QuicDispatcherTestAllVersions,DropPacketWithKnownVersionAndInvalidShortInitialConnectionId)1249 TEST_P(QuicDispatcherTestAllVersions,
1250        DropPacketWithKnownVersionAndInvalidShortInitialConnectionId) {
1251   if (!version_.AllowsVariableLengthConnectionIds()) {
1252     return;
1253   }
1254   CreateTimeWaitListManager();
1255 
1256   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1257 
1258   // dispatcher_ should drop this packet.
1259   EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0x00))
1260       .WillOnce(Return(10));
1261   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1262   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1263       .Times(0);
1264   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1265       .Times(0);
1266   expect_generator_is_called_ = false;
1267   ProcessFirstFlight(client_address, EmptyQuicConnectionId());
1268 }
1269 
TEST_P(QuicDispatcherTestAllVersions,DropPacketWithKnownVersionAndInvalidInitialConnectionId)1270 TEST_P(QuicDispatcherTestAllVersions,
1271        DropPacketWithKnownVersionAndInvalidInitialConnectionId) {
1272   CreateTimeWaitListManager();
1273 
1274   QuicSocketAddress server_address;
1275   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1276 
1277   // dispatcher_ should drop this packet with invalid connection ID.
1278   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1279   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1280       .Times(0);
1281   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1282       .Times(0);
1283   absl::string_view cid_str = "123456789abcdefg123456789abcdefg";
1284   QuicConnectionId invalid_connection_id(cid_str.data(), cid_str.length());
1285   QuicReceivedPacket packet("packet", 6, QuicTime::Zero());
1286   ReceivedPacketInfo packet_info(server_address, client_address, packet);
1287   packet_info.version_flag = true;
1288   packet_info.version = version_;
1289   packet_info.destination_connection_id = invalid_connection_id;
1290 
1291   ASSERT_TRUE(dispatcher_->MaybeDispatchPacket(packet_info));
1292 }
1293 
1294 void QuicDispatcherTestBase::
TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(const QuicConnectionId & server_connection_id,const QuicConnectionId & client_connection_id)1295     TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
1296         const QuicConnectionId& server_connection_id,
1297         const QuicConnectionId& client_connection_id) {
1298   CreateTimeWaitListManager();
1299 
1300   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1301 
1302   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1303   EXPECT_CALL(*time_wait_list_manager_,
1304               SendVersionNegotiationPacket(
1305                   server_connection_id, client_connection_id,
1306                   /*ietf_quic=*/true,
1307                   /*use_length_prefix=*/true, _, _, client_address, _))
1308       .Times(1);
1309   expect_generator_is_called_ = false;
1310   EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)).Times(0);
1311   ProcessFirstFlight(ParsedQuicVersion::ReservedForNegotiation(),
1312                      client_address, server_connection_id,
1313                      client_connection_id);
1314 }
1315 
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId)1316 TEST_P(QuicDispatcherTestOneVersion,
1317        VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId) {
1318   TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
1319       EmptyQuicConnectionId(), EmptyQuicConnectionId());
1320 }
1321 
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId2)1322 TEST_P(QuicDispatcherTestOneVersion,
1323        VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId2) {
1324   char server_connection_id_bytes[3] = {1, 2, 3};
1325   QuicConnectionId server_connection_id(server_connection_id_bytes,
1326                                         sizeof(server_connection_id_bytes));
1327   TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
1328       server_connection_id, EmptyQuicConnectionId());
1329 }
1330 
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId3)1331 TEST_P(QuicDispatcherTestOneVersion,
1332        VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId3) {
1333   char client_connection_id_bytes[8] = {1, 2, 3, 4, 5, 6, 7, 8};
1334   QuicConnectionId client_connection_id(client_connection_id_bytes,
1335                                         sizeof(client_connection_id_bytes));
1336   TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId(
1337       EmptyQuicConnectionId(), client_connection_id);
1338 }
1339 
TEST_P(QuicDispatcherTestOneVersion,VersionsChangeInFlight)1340 TEST_P(QuicDispatcherTestOneVersion, VersionsChangeInFlight) {
1341   VerifyVersionNotSupported(QuicVersionReservedForNegotiation());
1342   for (ParsedQuicVersion version : CurrentSupportedVersions()) {
1343     VerifyVersionSupported(version);
1344     QuicDisableVersion(version);
1345     VerifyVersionNotSupported(version);
1346     QuicEnableVersion(version);
1347     VerifyVersionSupported(version);
1348   }
1349 }
1350 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionDraft28WithVersionNegotiation)1351 TEST_P(QuicDispatcherTestOneVersion,
1352        RejectDeprecatedVersionDraft28WithVersionNegotiation) {
1353   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1354   CreateTimeWaitListManager();
1355   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1356       0xC0, 0xFF, 0x00, 0x00, 28, /*destination connection ID length*/ 0x08};
1357   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1358                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1359   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1360   EXPECT_CALL(
1361       *time_wait_list_manager_,
1362       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1363                                    /*use_length_prefix=*/true, _, _, _, _))
1364       .Times(1);
1365   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1366 }
1367 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionDraft27WithVersionNegotiation)1368 TEST_P(QuicDispatcherTestOneVersion,
1369        RejectDeprecatedVersionDraft27WithVersionNegotiation) {
1370   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1371   CreateTimeWaitListManager();
1372   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1373       0xC0, 0xFF, 0x00, 0x00, 27, /*destination connection ID length*/ 0x08};
1374   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1375                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1376   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1377   EXPECT_CALL(
1378       *time_wait_list_manager_,
1379       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1380                                    /*use_length_prefix=*/true, _, _, _, _))
1381       .Times(1);
1382   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1383 }
1384 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionDraft25WithVersionNegotiation)1385 TEST_P(QuicDispatcherTestOneVersion,
1386        RejectDeprecatedVersionDraft25WithVersionNegotiation) {
1387   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1388   CreateTimeWaitListManager();
1389   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1390       0xC0, 0xFF, 0x00, 0x00, 25, /*destination connection ID length*/ 0x08};
1391   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1392                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1393   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1394   EXPECT_CALL(
1395       *time_wait_list_manager_,
1396       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1397                                    /*use_length_prefix=*/true, _, _, _, _))
1398       .Times(1);
1399   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1400 }
1401 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionT050WithVersionNegotiation)1402 TEST_P(QuicDispatcherTestOneVersion,
1403        RejectDeprecatedVersionT050WithVersionNegotiation) {
1404   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1405   CreateTimeWaitListManager();
1406   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1407       0xC0, 'T', '0', '5', '0', /*destination connection ID length*/ 0x08};
1408   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1409                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1410   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1411   EXPECT_CALL(
1412       *time_wait_list_manager_,
1413       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1414                                    /*use_length_prefix=*/true, _, _, _, _))
1415       .Times(1);
1416   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1417 }
1418 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionQ049WithVersionNegotiation)1419 TEST_P(QuicDispatcherTestOneVersion,
1420        RejectDeprecatedVersionQ049WithVersionNegotiation) {
1421   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1422   CreateTimeWaitListManager();
1423   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1424       0xC0, 'Q', '0', '4', '9', /*destination connection ID length*/ 0x08};
1425   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1426                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1427   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1428   EXPECT_CALL(
1429       *time_wait_list_manager_,
1430       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1431                                    /*use_length_prefix=*/true, _, _, _, _))
1432       .Times(1);
1433   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1434 }
1435 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionQ048WithVersionNegotiation)1436 TEST_P(QuicDispatcherTestOneVersion,
1437        RejectDeprecatedVersionQ048WithVersionNegotiation) {
1438   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1439   CreateTimeWaitListManager();
1440   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1441       0xC0, 'Q', '0', '4', '8', /*connection ID length byte*/ 0x50};
1442   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1443                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1444   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1445   EXPECT_CALL(
1446       *time_wait_list_manager_,
1447       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1448                                    /*use_length_prefix=*/false, _, _, _, _))
1449       .Times(1);
1450   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1451 }
1452 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionQ047WithVersionNegotiation)1453 TEST_P(QuicDispatcherTestOneVersion,
1454        RejectDeprecatedVersionQ047WithVersionNegotiation) {
1455   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1456   CreateTimeWaitListManager();
1457   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1458       0xC0, 'Q', '0', '4', '7', /*connection ID length byte*/ 0x50};
1459   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1460                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1461   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1462   EXPECT_CALL(
1463       *time_wait_list_manager_,
1464       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1465                                    /*use_length_prefix=*/false, _, _, _, _))
1466       .Times(1);
1467   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1468 }
1469 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionQ045WithVersionNegotiation)1470 TEST_P(QuicDispatcherTestOneVersion,
1471        RejectDeprecatedVersionQ045WithVersionNegotiation) {
1472   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1473   CreateTimeWaitListManager();
1474   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1475       0xC0, 'Q', '0', '4', '5', /*connection ID length byte*/ 0x50};
1476   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1477                                      ABSL_ARRAYSIZE(packet), QuicTime::Zero());
1478   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1479   EXPECT_CALL(
1480       *time_wait_list_manager_,
1481       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1482                                    /*use_length_prefix=*/false, _, _, _, _))
1483       .Times(1);
1484   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1485 }
1486 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionQ044WithVersionNegotiation)1487 TEST_P(QuicDispatcherTestOneVersion,
1488        RejectDeprecatedVersionQ044WithVersionNegotiation) {
1489   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1490   CreateTimeWaitListManager();
1491   uint8_t packet44[kMinPacketSizeForVersionNegotiation] = {
1492       0xFF, 'Q', '0', '4', '4', /*connection ID length byte*/ 0x50};
1493   QuicReceivedPacket received_packet44(reinterpret_cast<char*>(packet44),
1494                                        kMinPacketSizeForVersionNegotiation,
1495                                        QuicTime::Zero());
1496   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1497   EXPECT_CALL(
1498       *time_wait_list_manager_,
1499       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1500                                    /*use_length_prefix=*/false, _, _, _, _))
1501       .Times(1);
1502   dispatcher_->ProcessPacket(server_address_, client_address,
1503                              received_packet44);
1504 }
1505 
TEST_P(QuicDispatcherTestOneVersion,RejectDeprecatedVersionT051WithVersionNegotiation)1506 TEST_P(QuicDispatcherTestOneVersion,
1507        RejectDeprecatedVersionT051WithVersionNegotiation) {
1508   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1509   CreateTimeWaitListManager();
1510   uint8_t packet[kMinPacketSizeForVersionNegotiation] = {
1511       0xFF, 'T', '0', '5', '1', /*destination connection ID length*/ 0x08};
1512   QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet),
1513                                      kMinPacketSizeForVersionNegotiation,
1514                                      QuicTime::Zero());
1515   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1516   EXPECT_CALL(
1517       *time_wait_list_manager_,
1518       SendVersionNegotiationPacket(_, _, /*ietf_quic=*/true,
1519                                    /*use_length_prefix=*/true, _, _, _, _))
1520       .Times(1);
1521   dispatcher_->ProcessPacket(server_address_, client_address, received_packet);
1522 }
1523 
1524 static_assert(quic::SupportedVersions().size() == 6u,
1525               "Please add new RejectDeprecatedVersion tests above this assert "
1526               "when deprecating versions");
1527 
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationProbe)1528 TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationProbe) {
1529   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1530   CreateTimeWaitListManager();
1531   char packet[1200];
1532   char destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70,
1533                                             0x6c, 0x7a, 0x20, 0x21};
1534   EXPECT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket(
1535       packet, sizeof(packet), destination_connection_id_bytes,
1536       sizeof(destination_connection_id_bytes)));
1537   QuicEncryptedPacket encrypted(packet, sizeof(packet), false);
1538   std::unique_ptr<QuicReceivedPacket> received_packet(
1539       ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now()));
1540   QuicConnectionId client_connection_id = EmptyQuicConnectionId();
1541   QuicConnectionId server_connection_id(
1542       destination_connection_id_bytes, sizeof(destination_connection_id_bytes));
1543   EXPECT_CALL(*time_wait_list_manager_,
1544               SendVersionNegotiationPacket(
1545                   server_connection_id, client_connection_id,
1546                   /*ietf_quic=*/true, /*use_length_prefix=*/true, _, _, _, _))
1547       .Times(1);
1548   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1549 
1550   dispatcher_->ProcessPacket(server_address_, client_address, *received_packet);
1551 }
1552 
1553 // Testing packet writer that saves all packets instead of sending them.
1554 // Useful for tests that need access to sent packets.
1555 class SavingWriter : public QuicPacketWriterWrapper {
1556  public:
IsWriteBlocked() const1557   bool IsWriteBlocked() const override { return false; }
1558 
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress &,const QuicSocketAddress &,PerPacketOptions *)1559   WriteResult WritePacket(const char* buffer, size_t buf_len,
1560                           const QuicIpAddress& /*self_client_address*/,
1561                           const QuicSocketAddress& /*peer_client_address*/,
1562                           PerPacketOptions* /*options*/) override {
1563     packets_.push_back(
1564         QuicEncryptedPacket(buffer, buf_len, /*owns_buffer=*/false).Clone());
1565     return WriteResult(WRITE_STATUS_OK, buf_len);
1566   }
1567 
packets()1568   std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets() {
1569     return &packets_;
1570   }
1571 
1572  private:
1573   std::vector<std::unique_ptr<QuicEncryptedPacket>> packets_;
1574 };
1575 
TEST_P(QuicDispatcherTestOneVersion,VersionNegotiationProbeEndToEnd)1576 TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationProbeEndToEnd) {
1577   SavingWriter* saving_writer = new SavingWriter();
1578   // dispatcher_ takes ownership of saving_writer.
1579   QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer);
1580 
1581   QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager(
1582       saving_writer, dispatcher_.get(), mock_helper_.GetClock(),
1583       &mock_alarm_factory_);
1584   // dispatcher_ takes ownership of time_wait_list_manager.
1585   QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(),
1586                                              time_wait_list_manager);
1587   char packet[1200] = {};
1588   char destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70,
1589                                             0x6c, 0x7a, 0x20, 0x21};
1590   EXPECT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket(
1591       packet, sizeof(packet), destination_connection_id_bytes,
1592       sizeof(destination_connection_id_bytes)));
1593   QuicEncryptedPacket encrypted(packet, sizeof(packet), false);
1594   std::unique_ptr<QuicReceivedPacket> received_packet(
1595       ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now()));
1596   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1597 
1598   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1599   dispatcher_->ProcessPacket(server_address_, client_address, *received_packet);
1600   ASSERT_EQ(1u, saving_writer->packets()->size());
1601 
1602   char source_connection_id_bytes[255] = {};
1603   uint8_t source_connection_id_length = sizeof(source_connection_id_bytes);
1604   std::string detailed_error = "foobar";
1605   EXPECT_TRUE(QuicFramer::ParseServerVersionNegotiationProbeResponse(
1606       (*(saving_writer->packets()))[0]->data(),
1607       (*(saving_writer->packets()))[0]->length(), source_connection_id_bytes,
1608       &source_connection_id_length, &detailed_error));
1609   EXPECT_EQ("", detailed_error);
1610 
1611   // The source connection ID of the probe response should match the
1612   // destination connection ID of the probe request.
1613   quiche::test::CompareCharArraysWithHexError(
1614       "parsed probe", source_connection_id_bytes, source_connection_id_length,
1615       destination_connection_id_bytes, sizeof(destination_connection_id_bytes));
1616 }
1617 
TEST_P(QuicDispatcherTestOneVersion,AndroidConformanceTest)1618 TEST_P(QuicDispatcherTestOneVersion, AndroidConformanceTest) {
1619   // WARNING: do not remove or modify this test without making sure that we
1620   // still have adequate coverage for the Android conformance test.
1621   SavingWriter* saving_writer = new SavingWriter();
1622   // dispatcher_ takes ownership of saving_writer.
1623   QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer);
1624 
1625   QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager(
1626       saving_writer, dispatcher_.get(), mock_helper_.GetClock(),
1627       &mock_alarm_factory_);
1628   // dispatcher_ takes ownership of time_wait_list_manager.
1629   QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(),
1630                                              time_wait_list_manager);
1631   // clang-format off
1632   static const unsigned char packet[1200] = {
1633     // Android UDP network conformance test packet as it was after this change:
1634     // https://android-review.googlesource.com/c/platform/cts/+/1454515
1635     0xc0,  // long header
1636     0xaa, 0xda, 0xca, 0xca,  // reserved-space version number
1637     0x08,  // destination connection ID length
1638     0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,  // 8-byte connection ID
1639     0x00,  // source connection ID length
1640   };
1641   // clang-format on
1642 
1643   QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet),
1644                                 sizeof(packet), false);
1645   std::unique_ptr<QuicReceivedPacket> received_packet(
1646       ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now()));
1647   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1648 
1649   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1650   dispatcher_->ProcessPacket(server_address_, client_address, *received_packet);
1651   ASSERT_EQ(1u, saving_writer->packets()->size());
1652 
1653   // The Android UDP network conformance test directly checks that these bytes
1654   // of the response match the connection ID that was sent.
1655   ASSERT_GE((*(saving_writer->packets()))[0]->length(), 15u);
1656   quiche::test::CompareCharArraysWithHexError(
1657       "response connection ID", &(*(saving_writer->packets()))[0]->data()[7], 8,
1658       reinterpret_cast<const char*>(&packet[6]), 8);
1659 }
1660 
TEST_P(QuicDispatcherTestOneVersion,AndroidConformanceTestOld)1661 TEST_P(QuicDispatcherTestOneVersion, AndroidConformanceTestOld) {
1662   // WARNING: this test covers an old Android Conformance Test that has now been
1663   // changed, but it'll take time for the change to propagate through the
1664   // Android ecosystem. The Android team has asked us to keep this test
1665   // supported until at least 2021-03-31. After that date, and when we drop
1666   // support for sending QUIC version negotiation packets using the legacy
1667   // Google QUIC format (Q001-Q043), then we can delete this test.
1668   // TODO(dschinazi) delete this test after 2021-03-31
1669   SavingWriter* saving_writer = new SavingWriter();
1670   // dispatcher_ takes ownership of saving_writer.
1671   QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer);
1672 
1673   QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager(
1674       saving_writer, dispatcher_.get(), mock_helper_.GetClock(),
1675       &mock_alarm_factory_);
1676   // dispatcher_ takes ownership of time_wait_list_manager.
1677   QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(),
1678                                              time_wait_list_manager);
1679   // clang-format off
1680   static const unsigned char packet[1200] = {
1681     // Android UDP network conformance test packet as it was after this change:
1682     // https://android-review.googlesource.com/c/platform/cts/+/1104285
1683     // but before this change:
1684     // https://android-review.googlesource.com/c/platform/cts/+/1454515
1685     0x0d,  // public flags: version, 8-byte connection ID, 1-byte packet number
1686     0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,  // 8-byte connection ID
1687     0xaa, 0xda, 0xca, 0xaa,  // reserved-space version number
1688     0x01,  // 1-byte packet number
1689     0x00,  // private flags
1690     0x07,  // PING frame
1691   };
1692   // clang-format on
1693 
1694   QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet),
1695                                 sizeof(packet), false);
1696   std::unique_ptr<QuicReceivedPacket> received_packet(
1697       ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now()));
1698   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1699 
1700   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1701   dispatcher_->ProcessPacket(server_address_, client_address, *received_packet);
1702   ASSERT_EQ(1u, saving_writer->packets()->size());
1703 
1704   // The Android UDP network conformance test directly checks that bytes 1-9
1705   // of the response match the connection ID that was sent.
1706   static const char connection_id_bytes[] = {0x71, 0x72, 0x73, 0x74,
1707                                              0x75, 0x76, 0x77, 0x78};
1708   ASSERT_GE((*(saving_writer->packets()))[0]->length(),
1709             1u + sizeof(connection_id_bytes));
1710   quiche::test::CompareCharArraysWithHexError(
1711       "response connection ID", &(*(saving_writer->packets()))[0]->data()[1],
1712       sizeof(connection_id_bytes), connection_id_bytes,
1713       sizeof(connection_id_bytes));
1714 }
1715 
TEST_P(QuicDispatcherTestAllVersions,DoNotProcessSmallPacket)1716 TEST_P(QuicDispatcherTestAllVersions, DoNotProcessSmallPacket) {
1717   CreateTimeWaitListManager();
1718   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1719 
1720   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1721   EXPECT_CALL(*time_wait_list_manager_, SendPacket(_, _, _)).Times(0);
1722   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1723       .Times(0);
1724   ProcessPacket(client_address, TestConnectionId(1), /*has_version_flag=*/true,
1725                 version_, SerializeCHLO(), /*full_padding=*/false,
1726                 CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1);
1727 }
1728 
TEST_P(QuicDispatcherTestAllVersions,ProcessSmallCoalescedPacket)1729 TEST_P(QuicDispatcherTestAllVersions, ProcessSmallCoalescedPacket) {
1730   CreateTimeWaitListManager();
1731   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1732 
1733   EXPECT_CALL(*time_wait_list_manager_, SendPacket(_, _, _)).Times(0);
1734 
1735   // clang-format off
1736   uint8_t coalesced_packet[1200] = {
1737     // first coalesced packet
1738       // public flags (long header with packet type INITIAL and
1739       // 4-byte packet number)
1740       0xC3,
1741       // version
1742       'Q', '0', '9', '9',
1743       // destination connection ID length
1744       0x08,
1745       // destination connection ID
1746       0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
1747       // source connection ID length
1748       0x00,
1749       // long header packet length
1750       0x05,
1751       // packet number
1752       0x12, 0x34, 0x56, 0x78,
1753       // Padding
1754       0x00,
1755     // second coalesced packet
1756       // public flags (long header with packet type ZERO_RTT_PROTECTED and
1757       // 4-byte packet number)
1758       0xC3,
1759       // version
1760       'Q', '0', '9', '9',
1761       // destination connection ID length
1762       0x08,
1763       // destination connection ID
1764       0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
1765       // source connection ID length
1766       0x00,
1767       // long header packet length
1768       0x1E,
1769       // packet number
1770       0x12, 0x34, 0x56, 0x79,
1771   };
1772   // clang-format on
1773   QuicReceivedPacket packet(reinterpret_cast<char*>(coalesced_packet), 1200,
1774                             QuicTime::Zero());
1775   dispatcher_->ProcessPacket(server_address_, client_address, packet);
1776 }
1777 
TEST_P(QuicDispatcherTestAllVersions,StopAcceptingNewConnections)1778 TEST_P(QuicDispatcherTestAllVersions, StopAcceptingNewConnections) {
1779   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1780 
1781   EXPECT_CALL(*dispatcher_,
1782               CreateQuicSession(TestConnectionId(1), _, client_address,
1783                                 Eq(ExpectedAlpn()), _, _))
1784       .WillOnce(Return(ByMove(CreateSession(
1785           dispatcher_.get(), config_, TestConnectionId(1), client_address,
1786           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1787           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1788   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1789               ProcessUdpPacket(_, _, _))
1790       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1791         ValidatePacket(TestConnectionId(1), packet);
1792       })));
1793   ProcessFirstFlight(client_address, TestConnectionId(1));
1794 
1795   dispatcher_->StopAcceptingNewConnections();
1796   EXPECT_FALSE(dispatcher_->accept_new_connections());
1797 
1798   // No more new connections afterwards.
1799   EXPECT_CALL(*dispatcher_,
1800               CreateQuicSession(TestConnectionId(2), _, client_address,
1801                                 Eq(ExpectedAlpn()), _, _))
1802       .Times(0u);
1803   expect_generator_is_called_ = false;
1804   ProcessFirstFlight(client_address, TestConnectionId(2));
1805 
1806   // Existing connections should be able to continue.
1807   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1808               ProcessUdpPacket(_, _, _))
1809       .Times(1u)
1810       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1811         ValidatePacket(TestConnectionId(1), packet);
1812       })));
1813   ProcessPacket(client_address, TestConnectionId(1), false, "data");
1814 }
1815 
TEST_P(QuicDispatcherTestAllVersions,StartAcceptingNewConnections)1816 TEST_P(QuicDispatcherTestAllVersions, StartAcceptingNewConnections) {
1817   dispatcher_->StopAcceptingNewConnections();
1818   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1819 
1820   // No more new connections afterwards.
1821   EXPECT_CALL(*dispatcher_,
1822               CreateQuicSession(TestConnectionId(2), _, client_address,
1823                                 Eq(ExpectedAlpn()), _, _))
1824       .Times(0u);
1825   expect_generator_is_called_ = false;
1826   ProcessFirstFlight(client_address, TestConnectionId(2));
1827 
1828   dispatcher_->StartAcceptingNewConnections();
1829   EXPECT_TRUE(dispatcher_->accept_new_connections());
1830 
1831   expect_generator_is_called_ = true;
1832   EXPECT_CALL(*dispatcher_,
1833               CreateQuicSession(TestConnectionId(1), _, client_address,
1834                                 Eq(ExpectedAlpn()), _, _))
1835       .WillOnce(Return(ByMove(CreateSession(
1836           dispatcher_.get(), config_, TestConnectionId(1), client_address,
1837           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
1838           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1839   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1840               ProcessUdpPacket(_, _, _))
1841       .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1842         ValidatePacket(TestConnectionId(1), packet);
1843       })));
1844   ProcessFirstFlight(client_address, TestConnectionId(1));
1845 }
1846 
TEST_P(QuicDispatcherTestOneVersion,SelectAlpn)1847 TEST_P(QuicDispatcherTestOneVersion, SelectAlpn) {
1848   EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {}), "");
1849   EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {""}), "");
1850   EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {"hq"}), "hq");
1851   // Q033 is no longer supported but Q050 is.
1852   QuicEnableVersion(ParsedQuicVersion::Q050());
1853   EXPECT_EQ(
1854       QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {"h3-Q033", "h3-Q050"}),
1855       "h3-Q050");
1856 }
1857 
1858 // Verify the stopgap test: Packets with truncated connection IDs should be
1859 // dropped.
1860 class QuicDispatcherTestStrayPacketConnectionId
1861     : public QuicDispatcherTestBase {};
1862 
1863 INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsStrayPacketConnectionId,
1864                          QuicDispatcherTestStrayPacketConnectionId,
1865                          ::testing::ValuesIn(CurrentSupportedVersions()),
1866                          ::testing::PrintToStringParamName());
1867 
1868 // Packets with truncated connection IDs should be dropped.
TEST_P(QuicDispatcherTestStrayPacketConnectionId,StrayPacketTruncatedConnectionId)1869 TEST_P(QuicDispatcherTestStrayPacketConnectionId,
1870        StrayPacketTruncatedConnectionId) {
1871   CreateTimeWaitListManager();
1872 
1873   QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1874   QuicConnectionId connection_id = TestConnectionId(1);
1875   EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _)).Times(0);
1876   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _))
1877       .Times(0);
1878   EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _))
1879       .Times(0);
1880 
1881   ProcessPacket(client_address, connection_id, true, "data",
1882                 CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER);
1883 }
1884 
1885 class BlockingWriter : public QuicPacketWriterWrapper {
1886  public:
BlockingWriter()1887   BlockingWriter() : write_blocked_(false) {}
1888 
IsWriteBlocked() const1889   bool IsWriteBlocked() const override { return write_blocked_; }
SetWritable()1890   void SetWritable() override { write_blocked_ = false; }
1891 
WritePacket(const char *,size_t,const QuicIpAddress &,const QuicSocketAddress &,PerPacketOptions *)1892   WriteResult WritePacket(const char* /*buffer*/, size_t /*buf_len*/,
1893                           const QuicIpAddress& /*self_client_address*/,
1894                           const QuicSocketAddress& /*peer_client_address*/,
1895                           PerPacketOptions* /*options*/) override {
1896     // It would be quite possible to actually implement this method here with
1897     // the fake blocked status, but it would be significantly more work in
1898     // Chromium, and since it's not called anyway, don't bother.
1899     QUIC_LOG(DFATAL) << "Not supported";
1900     return WriteResult();
1901   }
1902 
1903   bool write_blocked_;
1904 };
1905 
1906 class QuicDispatcherWriteBlockedListTest : public QuicDispatcherTestBase {
1907  public:
SetUp()1908   void SetUp() override {
1909     QuicDispatcherTestBase::SetUp();
1910     writer_ = new BlockingWriter;
1911     QuicDispatcherPeer::UseWriter(dispatcher_.get(), writer_);
1912 
1913     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
1914 
1915     EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address,
1916                                                 Eq(ExpectedAlpn()), _, _))
1917         .WillOnce(Return(ByMove(CreateSession(
1918             dispatcher_.get(), config_, TestConnectionId(1), client_address,
1919             &helper_, &alarm_factory_, &crypto_config_,
1920             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
1921     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
1922                 ProcessUdpPacket(_, _, _))
1923         .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1924           ValidatePacket(TestConnectionId(1), packet);
1925         })));
1926     ProcessFirstFlight(client_address, TestConnectionId(1));
1927 
1928     EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address,
1929                                                 Eq(ExpectedAlpn()), _, _))
1930         .WillOnce(Return(ByMove(CreateSession(
1931             dispatcher_.get(), config_, TestConnectionId(2), client_address,
1932             &helper_, &alarm_factory_, &crypto_config_,
1933             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))));
1934     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()),
1935                 ProcessUdpPacket(_, _, _))
1936         .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
1937           ValidatePacket(TestConnectionId(2), packet);
1938         })));
1939     ProcessFirstFlight(client_address, TestConnectionId(2));
1940 
1941     blocked_list_ = QuicDispatcherPeer::GetWriteBlockedList(dispatcher_.get());
1942   }
1943 
TearDown()1944   void TearDown() override {
1945     if (connection1() != nullptr) {
1946       EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
1947     }
1948 
1949     if (connection2() != nullptr) {
1950       EXPECT_CALL(*connection2(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
1951     }
1952     dispatcher_->Shutdown();
1953   }
1954 
1955   // Set the dispatcher's writer to be blocked. By default, all connections use
1956   // the same writer as the dispatcher in this test.
SetBlocked()1957   void SetBlocked() {
1958     QUIC_LOG(INFO) << "set writer " << writer_ << " to blocked";
1959     writer_->write_blocked_ = true;
1960   }
1961 
1962   // Simulate what happens when connection1 gets blocked when writing.
BlockConnection1()1963   void BlockConnection1() {
1964     Connection1Writer()->write_blocked_ = true;
1965     dispatcher_->OnWriteBlocked(connection1());
1966   }
1967 
Connection1Writer()1968   BlockingWriter* Connection1Writer() {
1969     return static_cast<BlockingWriter*>(connection1()->writer());
1970   }
1971 
1972   // Simulate what happens when connection2 gets blocked when writing.
BlockConnection2()1973   void BlockConnection2() {
1974     Connection2Writer()->write_blocked_ = true;
1975     dispatcher_->OnWriteBlocked(connection2());
1976   }
1977 
Connection2Writer()1978   BlockingWriter* Connection2Writer() {
1979     return static_cast<BlockingWriter*>(connection2()->writer());
1980   }
1981 
1982  protected:
1983   MockQuicConnectionHelper helper_;
1984   MockAlarmFactory alarm_factory_;
1985   BlockingWriter* writer_;
1986   QuicDispatcher::WriteBlockedList* blocked_list_;
1987 };
1988 
1989 INSTANTIATE_TEST_SUITE_P(QuicDispatcherWriteBlockedListTests,
1990                          QuicDispatcherWriteBlockedListTest,
1991                          ::testing::Values(CurrentSupportedVersions().front()),
1992                          ::testing::PrintToStringParamName());
1993 
TEST_P(QuicDispatcherWriteBlockedListTest,BasicOnCanWrite)1994 TEST_P(QuicDispatcherWriteBlockedListTest, BasicOnCanWrite) {
1995   // No OnCanWrite calls because no connections are blocked.
1996   dispatcher_->OnCanWrite();
1997 
1998   // Register connection 1 for events, and make sure it's notified.
1999   SetBlocked();
2000   dispatcher_->OnWriteBlocked(connection1());
2001   EXPECT_CALL(*connection1(), OnCanWrite());
2002   dispatcher_->OnCanWrite();
2003 
2004   // It should get only one notification.
2005   EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
2006   dispatcher_->OnCanWrite();
2007   EXPECT_FALSE(dispatcher_->HasPendingWrites());
2008 }
2009 
TEST_P(QuicDispatcherWriteBlockedListTest,OnCanWriteOrder)2010 TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteOrder) {
2011   // Make sure we handle events in order.
2012   InSequence s;
2013   SetBlocked();
2014   dispatcher_->OnWriteBlocked(connection1());
2015   dispatcher_->OnWriteBlocked(connection2());
2016   EXPECT_CALL(*connection1(), OnCanWrite());
2017   EXPECT_CALL(*connection2(), OnCanWrite());
2018   dispatcher_->OnCanWrite();
2019 
2020   // Check the other ordering.
2021   SetBlocked();
2022   dispatcher_->OnWriteBlocked(connection2());
2023   dispatcher_->OnWriteBlocked(connection1());
2024   EXPECT_CALL(*connection2(), OnCanWrite());
2025   EXPECT_CALL(*connection1(), OnCanWrite());
2026   dispatcher_->OnCanWrite();
2027 }
2028 
TEST_P(QuicDispatcherWriteBlockedListTest,OnCanWriteRemove)2029 TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteRemove) {
2030   // Add and remove one connction.
2031   SetBlocked();
2032   dispatcher_->OnWriteBlocked(connection1());
2033   blocked_list_->erase(connection1());
2034   EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
2035   dispatcher_->OnCanWrite();
2036 
2037   // Add and remove one connction and make sure it doesn't affect others.
2038   SetBlocked();
2039   dispatcher_->OnWriteBlocked(connection1());
2040   dispatcher_->OnWriteBlocked(connection2());
2041   blocked_list_->erase(connection1());
2042   EXPECT_CALL(*connection2(), OnCanWrite());
2043   dispatcher_->OnCanWrite();
2044 
2045   // Add it, remove it, and add it back and make sure things are OK.
2046   SetBlocked();
2047   dispatcher_->OnWriteBlocked(connection1());
2048   blocked_list_->erase(connection1());
2049   dispatcher_->OnWriteBlocked(connection1());
2050   EXPECT_CALL(*connection1(), OnCanWrite()).Times(1);
2051   dispatcher_->OnCanWrite();
2052 }
2053 
TEST_P(QuicDispatcherWriteBlockedListTest,DoubleAdd)2054 TEST_P(QuicDispatcherWriteBlockedListTest, DoubleAdd) {
2055   // Make sure a double add does not necessitate a double remove.
2056   SetBlocked();
2057   dispatcher_->OnWriteBlocked(connection1());
2058   dispatcher_->OnWriteBlocked(connection1());
2059   blocked_list_->erase(connection1());
2060   EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
2061   dispatcher_->OnCanWrite();
2062 
2063   // Make sure a double add does not result in two OnCanWrite calls.
2064   SetBlocked();
2065   dispatcher_->OnWriteBlocked(connection1());
2066   dispatcher_->OnWriteBlocked(connection1());
2067   EXPECT_CALL(*connection1(), OnCanWrite()).Times(1);
2068   dispatcher_->OnCanWrite();
2069 }
2070 
TEST_P(QuicDispatcherWriteBlockedListTest,OnCanWriteHandleBlockConnection1)2071 TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteHandleBlockConnection1) {
2072   // If the 1st blocked writer gets blocked in OnCanWrite, it will be added back
2073   // into the write blocked list.
2074   InSequence s;
2075   SetBlocked();
2076   dispatcher_->OnWriteBlocked(connection1());
2077   dispatcher_->OnWriteBlocked(connection2());
2078   EXPECT_CALL(*connection1(), OnCanWrite())
2079       .WillOnce(
2080           Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection1));
2081   EXPECT_CALL(*connection2(), OnCanWrite());
2082   dispatcher_->OnCanWrite();
2083 
2084   // connection1 should be still in the write blocked list.
2085   EXPECT_TRUE(dispatcher_->HasPendingWrites());
2086 
2087   // Now call OnCanWrite again, connection1 should get its second chance.
2088   EXPECT_CALL(*connection1(), OnCanWrite());
2089   EXPECT_CALL(*connection2(), OnCanWrite()).Times(0);
2090   dispatcher_->OnCanWrite();
2091   EXPECT_FALSE(dispatcher_->HasPendingWrites());
2092 }
2093 
TEST_P(QuicDispatcherWriteBlockedListTest,OnCanWriteHandleBlockConnection2)2094 TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteHandleBlockConnection2) {
2095   // If the 2nd blocked writer gets blocked in OnCanWrite, it will be added back
2096   // into the write blocked list.
2097   InSequence s;
2098   SetBlocked();
2099   dispatcher_->OnWriteBlocked(connection1());
2100   dispatcher_->OnWriteBlocked(connection2());
2101   EXPECT_CALL(*connection1(), OnCanWrite());
2102   EXPECT_CALL(*connection2(), OnCanWrite())
2103       .WillOnce(
2104           Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection2));
2105   dispatcher_->OnCanWrite();
2106 
2107   // connection2 should be still in the write blocked list.
2108   EXPECT_TRUE(dispatcher_->HasPendingWrites());
2109 
2110   // Now call OnCanWrite again, connection2 should get its second chance.
2111   EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
2112   EXPECT_CALL(*connection2(), OnCanWrite());
2113   dispatcher_->OnCanWrite();
2114   EXPECT_FALSE(dispatcher_->HasPendingWrites());
2115 }
2116 
TEST_P(QuicDispatcherWriteBlockedListTest,OnCanWriteHandleBlockBothConnections)2117 TEST_P(QuicDispatcherWriteBlockedListTest,
2118        OnCanWriteHandleBlockBothConnections) {
2119   // Both connections get blocked in OnCanWrite, and added back into the write
2120   // blocked list.
2121   InSequence s;
2122   SetBlocked();
2123   dispatcher_->OnWriteBlocked(connection1());
2124   dispatcher_->OnWriteBlocked(connection2());
2125   EXPECT_CALL(*connection1(), OnCanWrite())
2126       .WillOnce(
2127           Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection1));
2128   EXPECT_CALL(*connection2(), OnCanWrite())
2129       .WillOnce(
2130           Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection2));
2131   dispatcher_->OnCanWrite();
2132 
2133   // Both connections should be still in the write blocked list.
2134   EXPECT_TRUE(dispatcher_->HasPendingWrites());
2135 
2136   // Now call OnCanWrite again, both connections should get its second chance.
2137   EXPECT_CALL(*connection1(), OnCanWrite());
2138   EXPECT_CALL(*connection2(), OnCanWrite());
2139   dispatcher_->OnCanWrite();
2140   EXPECT_FALSE(dispatcher_->HasPendingWrites());
2141 }
2142 
TEST_P(QuicDispatcherWriteBlockedListTest,PerConnectionWriterBlocked)2143 TEST_P(QuicDispatcherWriteBlockedListTest, PerConnectionWriterBlocked) {
2144   // By default, all connections share the same packet writer with the
2145   // dispatcher.
2146   EXPECT_EQ(dispatcher_->writer(), connection1()->writer());
2147   EXPECT_EQ(dispatcher_->writer(), connection2()->writer());
2148 
2149   // Test the case where connection1 shares the same packet writer as the
2150   // dispatcher, whereas connection2 owns it's packet writer.
2151   // Change connection2's writer.
2152   connection2()->SetQuicPacketWriter(new BlockingWriter, /*owns_writer=*/true);
2153   EXPECT_NE(dispatcher_->writer(), connection2()->writer());
2154 
2155   BlockConnection2();
2156   EXPECT_TRUE(dispatcher_->HasPendingWrites());
2157 
2158   EXPECT_CALL(*connection2(), OnCanWrite());
2159   dispatcher_->OnCanWrite();
2160   EXPECT_FALSE(dispatcher_->HasPendingWrites());
2161 }
2162 
TEST_P(QuicDispatcherWriteBlockedListTest,RemoveConnectionFromWriteBlockedListWhenDeletingSessions)2163 TEST_P(QuicDispatcherWriteBlockedListTest,
2164        RemoveConnectionFromWriteBlockedListWhenDeletingSessions) {
2165   EXPECT_QUIC_BUG(
2166       {
2167         dispatcher_->OnConnectionClosed(
2168             connection1()->connection_id(), QUIC_PACKET_WRITE_ERROR,
2169             "Closed by test.", ConnectionCloseSource::FROM_SELF);
2170 
2171         SetBlocked();
2172 
2173         ASSERT_FALSE(dispatcher_->HasPendingWrites());
2174         SetBlocked();
2175         dispatcher_->OnWriteBlocked(connection1());
2176         ASSERT_TRUE(dispatcher_->HasPendingWrites());
2177 
2178         dispatcher_->DeleteSessions();
2179         MarkSession1Deleted();
2180       },
2181       "QuicConnection was in WriteBlockedList before destruction");
2182 }
2183 
2184 class QuicDispatcherSupportMultipleConnectionIdPerConnectionTest
2185     : public QuicDispatcherTestBase {
2186  public:
QuicDispatcherSupportMultipleConnectionIdPerConnectionTest()2187   QuicDispatcherSupportMultipleConnectionIdPerConnectionTest()
2188       : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting()) {
2189     dispatcher_ = std::make_unique<NiceMock<TestDispatcher>>(
2190         &config_, &crypto_config_, &version_manager_,
2191         mock_helper_.GetRandomGenerator(), connection_id_generator_);
2192   }
AddConnection1()2193   void AddConnection1() {
2194     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1);
2195     EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address,
2196                                                 Eq(ExpectedAlpn()), _, _))
2197         .WillOnce(Return(ByMove(CreateSession(
2198             dispatcher_.get(), config_, TestConnectionId(1), client_address,
2199             &helper_, &alarm_factory_, &crypto_config_,
2200             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2201     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2202                 ProcessUdpPacket(_, _, _))
2203         .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
2204           ValidatePacket(TestConnectionId(1), packet);
2205         })));
2206     ProcessFirstFlight(client_address, TestConnectionId(1));
2207   }
2208 
AddConnection2()2209   void AddConnection2() {
2210     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 2);
2211     EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address,
2212                                                 Eq(ExpectedAlpn()), _, _))
2213         .WillOnce(Return(ByMove(CreateSession(
2214             dispatcher_.get(), config_, TestConnectionId(2), client_address,
2215             &helper_, &alarm_factory_, &crypto_config_,
2216             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_))));
2217     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()),
2218                 ProcessUdpPacket(_, _, _))
2219         .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) {
2220           ValidatePacket(TestConnectionId(2), packet);
2221         })));
2222     ProcessFirstFlight(client_address, TestConnectionId(2));
2223   }
2224 
2225  protected:
2226   MockQuicConnectionHelper helper_;
2227   MockAlarmFactory alarm_factory_;
2228 };
2229 
2230 INSTANTIATE_TEST_SUITE_P(
2231     QuicDispatcherSupportMultipleConnectionIdPerConnectionTests,
2232     QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2233     ::testing::Values(CurrentSupportedVersions().front()),
2234     ::testing::PrintToStringParamName());
2235 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,FailToAddExistingConnectionId)2236 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2237        FailToAddExistingConnectionId) {
2238   AddConnection1();
2239   EXPECT_FALSE(dispatcher_->TryAddNewConnectionId(TestConnectionId(1),
2240                                                   TestConnectionId(1)));
2241 }
2242 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,TryAddNewConnectionId)2243 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2244        TryAddNewConnectionId) {
2245   AddConnection1();
2246   ASSERT_EQ(dispatcher_->NumSessions(), 1u);
2247   ASSERT_THAT(session1_, testing::NotNull());
2248   MockServerConnection* mock_server_connection1 =
2249       reinterpret_cast<MockServerConnection*>(connection1());
2250 
2251   {
2252     mock_server_connection1->AddNewConnectionId(TestConnectionId(3));
2253     EXPECT_EQ(dispatcher_->NumSessions(), 1u);
2254     auto* session =
2255         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(3));
2256     ASSERT_EQ(session, session1_);
2257   }
2258 
2259   {
2260     mock_server_connection1->AddNewConnectionId(TestConnectionId(4));
2261     EXPECT_EQ(dispatcher_->NumSessions(), 1u);
2262     auto* session =
2263         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(4));
2264     ASSERT_EQ(session, session1_);
2265   }
2266 
2267   EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
2268   // Would timed out unless all sessions have been removed from the session map.
2269   dispatcher_->Shutdown();
2270 }
2271 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,TryAddNewConnectionIdWithCollision)2272 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2273        TryAddNewConnectionIdWithCollision) {
2274   AddConnection1();
2275   AddConnection2();
2276   ASSERT_EQ(dispatcher_->NumSessions(), 2u);
2277   ASSERT_THAT(session1_, testing::NotNull());
2278   ASSERT_THAT(session2_, testing::NotNull());
2279   MockServerConnection* mock_server_connection1 =
2280       reinterpret_cast<MockServerConnection*>(connection1());
2281   MockServerConnection* mock_server_connection2 =
2282       reinterpret_cast<MockServerConnection*>(connection2());
2283 
2284   {
2285     // TestConnectionId(2) is already claimed by connection2 but connection1
2286     // still thinks it owns it.
2287     mock_server_connection1->UnconditionallyAddNewConnectionIdForTest(
2288         TestConnectionId(2));
2289     EXPECT_EQ(dispatcher_->NumSessions(), 2u);
2290     auto* session =
2291         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2));
2292     ASSERT_EQ(session, session2_);
2293     EXPECT_THAT(mock_server_connection1->GetActiveServerConnectionIds(),
2294                 testing::ElementsAre(TestConnectionId(1), TestConnectionId(2)));
2295   }
2296 
2297   {
2298     mock_server_connection2->AddNewConnectionId(TestConnectionId(3));
2299     EXPECT_EQ(dispatcher_->NumSessions(), 2u);
2300     auto* session =
2301         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(3));
2302     ASSERT_EQ(session, session2_);
2303     EXPECT_THAT(mock_server_connection2->GetActiveServerConnectionIds(),
2304                 testing::ElementsAre(TestConnectionId(2), TestConnectionId(3)));
2305   }
2306 
2307   // Connection2 removes both TestConnectionId(2) & TestConnectionId(3) from the
2308   // session map.
2309   dispatcher_->OnConnectionClosed(TestConnectionId(2),
2310                                   QuicErrorCode::QUIC_NO_ERROR, "detail",
2311                                   quic::ConnectionCloseSource::FROM_SELF);
2312   // QUICHE_BUG fires when connection1 tries to remove TestConnectionId(2)
2313   // again from the session_map.
2314   EXPECT_QUICHE_BUG(dispatcher_->OnConnectionClosed(
2315                         TestConnectionId(1), QuicErrorCode::QUIC_NO_ERROR,
2316                         "detail", quic::ConnectionCloseSource::FROM_SELF),
2317                     "Missing session for cid");
2318 }
2319 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,MismatchedSessionAfterAddingCollidedConnectionId)2320 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2321        MismatchedSessionAfterAddingCollidedConnectionId) {
2322   AddConnection1();
2323   AddConnection2();
2324   MockServerConnection* mock_server_connection1 =
2325       reinterpret_cast<MockServerConnection*>(connection1());
2326 
2327   {
2328     // TestConnectionId(2) is already claimed by connection2 but connection1
2329     // still thinks it owns it.
2330     mock_server_connection1->UnconditionallyAddNewConnectionIdForTest(
2331         TestConnectionId(2));
2332     EXPECT_EQ(dispatcher_->NumSessions(), 2u);
2333     auto* session =
2334         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2));
2335     ASSERT_EQ(session, session2_);
2336     EXPECT_THAT(mock_server_connection1->GetActiveServerConnectionIds(),
2337                 testing::ElementsAre(TestConnectionId(1), TestConnectionId(2)));
2338   }
2339 
2340   // Connection1 tries to remove both Cid1 & Cid2, but they point to different
2341   // sessions.
2342   EXPECT_QUIC_BUG(dispatcher_->OnConnectionClosed(
2343                       TestConnectionId(1), QuicErrorCode::QUIC_NO_ERROR,
2344                       "detail", quic::ConnectionCloseSource::FROM_SELF),
2345                   "Session is mismatched in the map");
2346 }
2347 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,RetireConnectionIdFromSingleConnection)2348 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2349        RetireConnectionIdFromSingleConnection) {
2350   AddConnection1();
2351   ASSERT_EQ(dispatcher_->NumSessions(), 1u);
2352   ASSERT_THAT(session1_, testing::NotNull());
2353   MockServerConnection* mock_server_connection1 =
2354       reinterpret_cast<MockServerConnection*>(connection1());
2355 
2356   // Adds 1 new connection id every turn and retires 2 connection ids every
2357   // other turn.
2358   for (int i = 2; i < 10; ++i) {
2359     mock_server_connection1->AddNewConnectionId(TestConnectionId(i));
2360     ASSERT_EQ(
2361         QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(i)),
2362         session1_);
2363     ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(),
2364                                               TestConnectionId(i - 1)),
2365               session1_);
2366     EXPECT_EQ(dispatcher_->NumSessions(), 1u);
2367     if (i % 2 == 1) {
2368       mock_server_connection1->RetireConnectionId(TestConnectionId(i - 2));
2369       mock_server_connection1->RetireConnectionId(TestConnectionId(i - 1));
2370     }
2371   }
2372 
2373   EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
2374   // Would timed out unless all sessions have been removed from the session map.
2375   dispatcher_->Shutdown();
2376 }
2377 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,RetireConnectionIdFromMultipleConnections)2378 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2379        RetireConnectionIdFromMultipleConnections) {
2380   AddConnection1();
2381   AddConnection2();
2382   ASSERT_EQ(dispatcher_->NumSessions(), 2u);
2383   MockServerConnection* mock_server_connection1 =
2384       reinterpret_cast<MockServerConnection*>(connection1());
2385   MockServerConnection* mock_server_connection2 =
2386       reinterpret_cast<MockServerConnection*>(connection2());
2387 
2388   for (int i = 2; i < 10; ++i) {
2389     mock_server_connection1->AddNewConnectionId(TestConnectionId(2 * i - 1));
2390     mock_server_connection2->AddNewConnectionId(TestConnectionId(2 * i));
2391     ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(),
2392                                               TestConnectionId(2 * i - 1)),
2393               session1_);
2394     ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(),
2395                                               TestConnectionId(2 * i)),
2396               session2_);
2397     EXPECT_EQ(dispatcher_->NumSessions(), 2u);
2398     mock_server_connection1->RetireConnectionId(TestConnectionId(2 * i - 3));
2399     mock_server_connection2->RetireConnectionId(TestConnectionId(2 * i - 2));
2400   }
2401 
2402   mock_server_connection1->AddNewConnectionId(TestConnectionId(19));
2403   mock_server_connection2->AddNewConnectionId(TestConnectionId(20));
2404   EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
2405   EXPECT_CALL(*connection2(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
2406   // Would timed out unless all sessions have been removed from the session map.
2407   dispatcher_->Shutdown();
2408 }
2409 
TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,TimeWaitListPoplulateCorrectly)2410 TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest,
2411        TimeWaitListPoplulateCorrectly) {
2412   QuicTimeWaitListManager* time_wait_list_manager =
2413       QuicDispatcherPeer::GetTimeWaitListManager(dispatcher_.get());
2414   AddConnection1();
2415   MockServerConnection* mock_server_connection1 =
2416       reinterpret_cast<MockServerConnection*>(connection1());
2417 
2418   mock_server_connection1->AddNewConnectionId(TestConnectionId(2));
2419   mock_server_connection1->AddNewConnectionId(TestConnectionId(3));
2420   mock_server_connection1->AddNewConnectionId(TestConnectionId(4));
2421   mock_server_connection1->RetireConnectionId(TestConnectionId(1));
2422   mock_server_connection1->RetireConnectionId(TestConnectionId(2));
2423 
2424   EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _));
2425   connection1()->CloseConnection(
2426       QUIC_PEER_GOING_AWAY, "Close for testing",
2427       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2428 
2429   EXPECT_FALSE(
2430       time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(1)));
2431   EXPECT_FALSE(
2432       time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(2)));
2433   EXPECT_TRUE(
2434       time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(3)));
2435   EXPECT_TRUE(
2436       time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(4)));
2437 
2438   dispatcher_->Shutdown();
2439 }
2440 
2441 class BufferedPacketStoreTest : public QuicDispatcherTestBase {
2442  public:
BufferedPacketStoreTest()2443   BufferedPacketStoreTest()
2444       : QuicDispatcherTestBase(),
2445         client_addr_(QuicIpAddress::Loopback4(), 1234) {}
2446 
ProcessFirstFlight(const ParsedQuicVersion & version,const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)2447   void ProcessFirstFlight(const ParsedQuicVersion& version,
2448                           const QuicSocketAddress& peer_address,
2449                           const QuicConnectionId& server_connection_id) {
2450     QuicDispatcherTestBase::ProcessFirstFlight(version, peer_address,
2451                                                server_connection_id);
2452   }
2453 
ProcessFirstFlight(const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)2454   void ProcessFirstFlight(const QuicSocketAddress& peer_address,
2455                           const QuicConnectionId& server_connection_id) {
2456     ProcessFirstFlight(version_, peer_address, server_connection_id);
2457   }
2458 
ProcessFirstFlight(const QuicConnectionId & server_connection_id)2459   void ProcessFirstFlight(const QuicConnectionId& server_connection_id) {
2460     ProcessFirstFlight(client_addr_, server_connection_id);
2461   }
2462 
ProcessFirstFlight(const ParsedQuicVersion & version,const QuicConnectionId & server_connection_id)2463   void ProcessFirstFlight(const ParsedQuicVersion& version,
2464                           const QuicConnectionId& server_connection_id) {
2465     ProcessFirstFlight(version, client_addr_, server_connection_id);
2466   }
2467 
ProcessUndecryptableEarlyPacket(const ParsedQuicVersion & version,const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)2468   void ProcessUndecryptableEarlyPacket(
2469       const ParsedQuicVersion& version, const QuicSocketAddress& peer_address,
2470       const QuicConnectionId& server_connection_id) {
2471     QuicDispatcherTestBase::ProcessUndecryptableEarlyPacket(
2472         version, peer_address, server_connection_id);
2473   }
2474 
ProcessUndecryptableEarlyPacket(const QuicSocketAddress & peer_address,const QuicConnectionId & server_connection_id)2475   void ProcessUndecryptableEarlyPacket(
2476       const QuicSocketAddress& peer_address,
2477       const QuicConnectionId& server_connection_id) {
2478     ProcessUndecryptableEarlyPacket(version_, peer_address,
2479                                     server_connection_id);
2480   }
2481 
ProcessUndecryptableEarlyPacket(const QuicConnectionId & server_connection_id)2482   void ProcessUndecryptableEarlyPacket(
2483       const QuicConnectionId& server_connection_id) {
2484     ProcessUndecryptableEarlyPacket(version_, client_addr_,
2485                                     server_connection_id);
2486   }
2487 
2488  protected:
2489   QuicSocketAddress client_addr_;
2490 };
2491 
2492 INSTANTIATE_TEST_SUITE_P(BufferedPacketStoreTests, BufferedPacketStoreTest,
2493                          ::testing::ValuesIn(CurrentSupportedVersions()),
2494                          ::testing::PrintToStringParamName());
2495 
TEST_P(BufferedPacketStoreTest,ProcessNonChloPacketBeforeChlo)2496 TEST_P(BufferedPacketStoreTest, ProcessNonChloPacketBeforeChlo) {
2497   InSequence s;
2498   QuicConnectionId conn_id = TestConnectionId(1);
2499   // Process non-CHLO packet.
2500   ProcessUndecryptableEarlyPacket(conn_id);
2501   EXPECT_EQ(0u, dispatcher_->NumSessions())
2502       << "No session should be created before CHLO arrives.";
2503 
2504   // When CHLO arrives, a new session should be created, and all packets
2505   // buffered should be delivered to the session.
2506   EXPECT_CALL(connection_id_generator_,
2507               MaybeReplaceConnectionId(conn_id, version_))
2508       .WillOnce(Return(absl::nullopt));
2509   EXPECT_CALL(*dispatcher_,
2510               CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _,
2511                                 Eq(ParsedClientHelloForTest())))
2512       .WillOnce(Return(ByMove(CreateSession(
2513           dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_,
2514           &mock_alarm_factory_, &crypto_config_,
2515           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2516   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2517               ProcessUdpPacket(_, _, _))
2518       .Times(2)  // non-CHLO + CHLO.
2519       .WillRepeatedly(
2520           WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2521             if (version_.UsesQuicCrypto()) {
2522               ValidatePacket(conn_id, packet);
2523             }
2524           })));
2525   expect_generator_is_called_ = false;
2526   ProcessFirstFlight(conn_id);
2527 }
2528 
TEST_P(BufferedPacketStoreTest,ProcessNonChloPacketsUptoLimitAndProcessChlo)2529 TEST_P(BufferedPacketStoreTest, ProcessNonChloPacketsUptoLimitAndProcessChlo) {
2530   InSequence s;
2531   QuicConnectionId conn_id = TestConnectionId(1);
2532   for (size_t i = 1; i <= kDefaultMaxUndecryptablePackets + 1; ++i) {
2533     ProcessUndecryptableEarlyPacket(conn_id);
2534   }
2535   EXPECT_EQ(0u, dispatcher_->NumSessions())
2536       << "No session should be created before CHLO arrives.";
2537 
2538   // Pop out the last packet as it is also be dropped by the store.
2539   data_connection_map_[conn_id].pop_back();
2540   // When CHLO arrives, a new session should be created, and all packets
2541   // buffered should be delivered to the session.
2542   EXPECT_CALL(connection_id_generator_,
2543               MaybeReplaceConnectionId(conn_id, version_))
2544       .WillOnce(Return(absl::nullopt));
2545   EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_,
2546                                               Eq(ExpectedAlpn()), _, _))
2547       .WillOnce(Return(ByMove(CreateSession(
2548           dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_,
2549           &mock_alarm_factory_, &crypto_config_,
2550           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2551 
2552   // Only |kDefaultMaxUndecryptablePackets| packets were buffered, and they
2553   // should be delivered in arrival order.
2554   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2555               ProcessUdpPacket(_, _, _))
2556       .Times(kDefaultMaxUndecryptablePackets + 1)  // + 1 for CHLO.
2557       .WillRepeatedly(
2558           WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2559             if (version_.UsesQuicCrypto()) {
2560               ValidatePacket(conn_id, packet);
2561             }
2562           })));
2563   expect_generator_is_called_ = false;
2564   ProcessFirstFlight(conn_id);
2565 }
2566 
TEST_P(BufferedPacketStoreTest,ProcessNonChloPacketsForDifferentConnectionsUptoLimit)2567 TEST_P(BufferedPacketStoreTest,
2568        ProcessNonChloPacketsForDifferentConnectionsUptoLimit) {
2569   InSequence s;
2570   // A bunch of non-CHLO should be buffered upon arrival.
2571   size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1;
2572   for (size_t i = 1; i <= kNumConnections; ++i) {
2573     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 20000 + i);
2574     QuicConnectionId conn_id = TestConnectionId(i);
2575     ProcessUndecryptableEarlyPacket(client_address, conn_id);
2576   }
2577 
2578   // Pop out the packet on last connection as it shouldn't be enqueued in store
2579   // as well.
2580   data_connection_map_[TestConnectionId(kNumConnections)].pop_front();
2581 
2582   // Reset session creation counter to ensure processing CHLO can always
2583   // create session.
2584   QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop(dispatcher_.get(),
2585                                                               kNumConnections);
2586   // Deactivate the EXPECT_CALL in ProcessFirstFlight() because we have to be
2587   // in sequence, so the EXPECT_CALL has to explicitly be in order here.
2588   expect_generator_is_called_ = false;
2589   // Process CHLOs to create session for these connections.
2590   for (size_t i = 1; i <= kNumConnections; ++i) {
2591     QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 20000 + i);
2592     QuicConnectionId conn_id = TestConnectionId(i);
2593     EXPECT_CALL(connection_id_generator_,
2594                 MaybeReplaceConnectionId(conn_id, version_))
2595         .WillOnce(Return(absl::nullopt));
2596     EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_address,
2597                                                 Eq(ExpectedAlpn()), _, _))
2598         .WillOnce(Return(ByMove(CreateSession(
2599             dispatcher_.get(), config_, conn_id, client_address, &mock_helper_,
2600             &mock_alarm_factory_, &crypto_config_,
2601             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2602     // First |kNumConnections| - 1 connections should have buffered
2603     // a packet in store. The rest should have been dropped.
2604     size_t num_packet_to_process = i <= kMaxConnectionsWithoutCHLO ? 2u : 1u;
2605     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2606                 ProcessUdpPacket(_, client_address, _))
2607         .Times(num_packet_to_process)
2608         .WillRepeatedly(WithArg<2>(
2609             Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2610               if (version_.UsesQuicCrypto()) {
2611                 ValidatePacket(conn_id, packet);
2612               }
2613             })));
2614     ProcessFirstFlight(client_address, conn_id);
2615   }
2616 }
2617 
2618 // Tests that store delivers empty packet list if CHLO arrives firstly.
TEST_P(BufferedPacketStoreTest,DeliverEmptyPackets)2619 TEST_P(BufferedPacketStoreTest, DeliverEmptyPackets) {
2620   QuicConnectionId conn_id = TestConnectionId(1);
2621   EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_,
2622                                               Eq(ExpectedAlpn()), _, _))
2623       .WillOnce(Return(ByMove(CreateSession(
2624           dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_,
2625           &mock_alarm_factory_, &crypto_config_,
2626           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2627   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2628               ProcessUdpPacket(_, client_addr_, _));
2629   ProcessFirstFlight(conn_id);
2630 }
2631 
2632 // Tests that a retransmitted CHLO arrives after a connection for the
2633 // CHLO has been created.
TEST_P(BufferedPacketStoreTest,ReceiveRetransmittedCHLO)2634 TEST_P(BufferedPacketStoreTest, ReceiveRetransmittedCHLO) {
2635   InSequence s;
2636   QuicConnectionId conn_id = TestConnectionId(1);
2637   ProcessUndecryptableEarlyPacket(conn_id);
2638 
2639   // When CHLO arrives, a new session should be created, and all packets
2640   // buffered should be delivered to the session.
2641   EXPECT_CALL(connection_id_generator_,
2642               MaybeReplaceConnectionId(conn_id, version_))
2643       .WillOnce(Return(absl::nullopt));
2644   EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_,
2645                                               Eq(ExpectedAlpn()), _, _))
2646       .Times(1)  // Only triggered by 1st CHLO.
2647       .WillOnce(Return(ByMove(CreateSession(
2648           dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_,
2649           &mock_alarm_factory_, &crypto_config_,
2650           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2651   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2652               ProcessUdpPacket(_, _, _))
2653       .Times(3)  // Triggered by 1 data packet and 2 CHLOs.
2654       .WillRepeatedly(
2655           WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2656             if (version_.UsesQuicCrypto()) {
2657               ValidatePacket(conn_id, packet);
2658             }
2659           })));
2660 
2661   std::vector<std::unique_ptr<QuicReceivedPacket>> packets =
2662       GetFirstFlightOfPackets(version_, conn_id);
2663   ASSERT_EQ(packets.size(), 1u);
2664   // Receive the CHLO once.
2665   ProcessReceivedPacket(packets[0]->Clone(), client_addr_, version_, conn_id);
2666   // Receive the CHLO a second time to simulate retransmission.
2667   ProcessReceivedPacket(std::move(packets[0]), client_addr_, version_, conn_id);
2668 }
2669 
2670 // Tests that expiration of a connection add connection id to time wait list.
TEST_P(BufferedPacketStoreTest,ReceiveCHLOAfterExpiration)2671 TEST_P(BufferedPacketStoreTest, ReceiveCHLOAfterExpiration) {
2672   InSequence s;
2673   CreateTimeWaitListManager();
2674   QuicBufferedPacketStore* store =
2675       QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get());
2676   QuicBufferedPacketStorePeer::set_clock(store, mock_helper_.GetClock());
2677 
2678   QuicConnectionId conn_id = TestConnectionId(1);
2679   ProcessPacket(client_addr_, conn_id, true, absl::StrCat("data packet ", 2),
2680                 CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER,
2681                 /*packet_number=*/2);
2682 
2683   mock_helper_.AdvanceTime(
2684       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs));
2685   QuicAlarm* alarm = QuicBufferedPacketStorePeer::expiration_alarm(store);
2686   // Cancel alarm as if it had been fired.
2687   alarm->Cancel();
2688   store->OnExpirationTimeout();
2689   // New arrived CHLO will be dropped because this connection is in time wait
2690   // list.
2691   ASSERT_TRUE(time_wait_list_manager_->IsConnectionIdInTimeWait(conn_id));
2692   EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, conn_id, _, _, _));
2693   expect_generator_is_called_ = false;
2694   ProcessFirstFlight(conn_id);
2695 }
2696 
TEST_P(BufferedPacketStoreTest,ProcessCHLOsUptoLimitAndBufferTheRest)2697 TEST_P(BufferedPacketStoreTest, ProcessCHLOsUptoLimitAndBufferTheRest) {
2698   // Process more than (|kMaxNumSessionsToCreate| +
2699   // |kDefaultMaxConnectionsInStore|) CHLOs,
2700   // the first |kMaxNumSessionsToCreate| should create connections immediately,
2701   // the next |kDefaultMaxConnectionsInStore| should be buffered,
2702   // the rest should be dropped.
2703   QuicBufferedPacketStore* store =
2704       QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get());
2705   const size_t kNumCHLOs =
2706       kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore + 1;
2707   for (uint64_t conn_id = 1; conn_id <= kNumCHLOs; ++conn_id) {
2708     if (conn_id <= kMaxNumSessionsToCreate) {
2709       EXPECT_CALL(connection_id_generator_,
2710                   MaybeReplaceConnectionId(TestConnectionId(conn_id), version_))
2711           .WillOnce(Return(absl::nullopt));
2712       EXPECT_CALL(*dispatcher_,
2713                   CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2714                                     Eq(ExpectedAlpn()), _,
2715                                     Eq(ParsedClientHelloForTest())))
2716           .WillOnce(Return(ByMove(CreateSession(
2717               dispatcher_.get(), config_, TestConnectionId(conn_id),
2718               client_addr_, &mock_helper_, &mock_alarm_factory_,
2719               &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()),
2720               &session1_))));
2721       EXPECT_CALL(
2722           *reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2723           ProcessUdpPacket(_, _, _))
2724           .WillOnce(WithArg<2>(
2725               Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2726                 if (version_.UsesQuicCrypto()) {
2727                   ValidatePacket(TestConnectionId(conn_id), packet);
2728                 }
2729               })));
2730     }
2731     expect_generator_is_called_ = false;
2732     ProcessFirstFlight(TestConnectionId(conn_id));
2733     if (conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore &&
2734         conn_id > kMaxNumSessionsToCreate) {
2735       EXPECT_TRUE(store->HasChloForConnection(TestConnectionId(conn_id)));
2736     } else {
2737       // First |kMaxNumSessionsToCreate| CHLOs should be passed to new
2738       // connections immediately, and the last CHLO should be dropped as the
2739       // store is full.
2740       EXPECT_FALSE(store->HasChloForConnection(TestConnectionId(conn_id)));
2741     }
2742   }
2743 
2744   // Graduately consume buffered CHLOs. The buffered connections should be
2745   // created but the dropped one shouldn't.
2746   for (uint64_t conn_id = kMaxNumSessionsToCreate + 1;
2747        conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore;
2748        ++conn_id) {
2749     EXPECT_CALL(connection_id_generator_,
2750                 MaybeReplaceConnectionId(TestConnectionId(conn_id), version_))
2751         .WillOnce(Return(absl::nullopt));
2752     EXPECT_CALL(*dispatcher_,
2753                 CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2754                                   Eq(ExpectedAlpn()), _,
2755                                   Eq(ParsedClientHelloForTest())))
2756         .WillOnce(Return(ByMove(CreateSession(
2757             dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_,
2758             &mock_helper_, &mock_alarm_factory_, &crypto_config_,
2759             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2760     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2761                 ProcessUdpPacket(_, _, _))
2762         .WillOnce(WithArg<2>(
2763             Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2764               if (version_.UsesQuicCrypto()) {
2765                 ValidatePacket(TestConnectionId(conn_id), packet);
2766               }
2767             })));
2768   }
2769   EXPECT_CALL(connection_id_generator_,
2770               MaybeReplaceConnectionId(TestConnectionId(kNumCHLOs), version_))
2771       .Times(0);
2772   EXPECT_CALL(*dispatcher_,
2773               CreateQuicSession(TestConnectionId(kNumCHLOs), _, client_addr_,
2774                                 Eq(ExpectedAlpn()), _, _))
2775       .Times(0);
2776 
2777   while (store->HasChlosBuffered()) {
2778     dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate);
2779   }
2780 
2781   EXPECT_EQ(TestConnectionId(static_cast<size_t>(kMaxNumSessionsToCreate) +
2782                              kDefaultMaxConnectionsInStore),
2783             session1_->connection_id());
2784 }
2785 
2786 // Duplicated CHLO shouldn't be buffered.
TEST_P(BufferedPacketStoreTest,BufferDuplicatedCHLO)2787 TEST_P(BufferedPacketStoreTest, BufferDuplicatedCHLO) {
2788   for (uint64_t conn_id = 1; conn_id <= kMaxNumSessionsToCreate + 1;
2789        ++conn_id) {
2790     // Last CHLO will be buffered. Others will create connection right away.
2791     if (conn_id <= kMaxNumSessionsToCreate) {
2792       EXPECT_CALL(*dispatcher_,
2793                   CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2794                                     Eq(ExpectedAlpn()), _, _))
2795           .WillOnce(Return(ByMove(CreateSession(
2796               dispatcher_.get(), config_, TestConnectionId(conn_id),
2797               client_addr_, &mock_helper_, &mock_alarm_factory_,
2798               &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()),
2799               &session1_))));
2800       EXPECT_CALL(
2801           *reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2802           ProcessUdpPacket(_, _, _))
2803           .WillOnce(WithArg<2>(
2804               Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2805                 if (version_.UsesQuicCrypto()) {
2806                   ValidatePacket(TestConnectionId(conn_id), packet);
2807                 }
2808               })));
2809     }
2810     ProcessFirstFlight(TestConnectionId(conn_id));
2811   }
2812   // Retransmit CHLO on last connection should be dropped.
2813   QuicConnectionId last_connection =
2814       TestConnectionId(kMaxNumSessionsToCreate + 1);
2815   expect_generator_is_called_ = false;
2816   ProcessFirstFlight(last_connection);
2817 
2818   size_t packets_buffered = 2;
2819 
2820   // Reset counter and process buffered CHLO.
2821   EXPECT_CALL(*dispatcher_, CreateQuicSession(last_connection, _, client_addr_,
2822                                               Eq(ExpectedAlpn()), _, _))
2823       .WillOnce(Return(ByMove(CreateSession(
2824           dispatcher_.get(), config_, last_connection, client_addr_,
2825           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
2826           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2827   // Only one packet(CHLO) should be process.
2828   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2829               ProcessUdpPacket(_, _, _))
2830       .Times(packets_buffered)
2831       .WillRepeatedly(WithArg<2>(
2832           Invoke([this, last_connection](const QuicEncryptedPacket& packet) {
2833             if (version_.UsesQuicCrypto()) {
2834               ValidatePacket(last_connection, packet);
2835             }
2836           })));
2837   dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate);
2838 }
2839 
TEST_P(BufferedPacketStoreTest,BufferNonChloPacketsUptoLimitWithChloBuffered)2840 TEST_P(BufferedPacketStoreTest, BufferNonChloPacketsUptoLimitWithChloBuffered) {
2841   uint64_t last_conn_id = kMaxNumSessionsToCreate + 1;
2842   QuicConnectionId last_connection_id = TestConnectionId(last_conn_id);
2843   for (uint64_t conn_id = 1; conn_id <= last_conn_id; ++conn_id) {
2844     // Last CHLO will be buffered. Others will create connection right away.
2845     if (conn_id <= kMaxNumSessionsToCreate) {
2846       EXPECT_CALL(*dispatcher_,
2847                   CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2848                                     Eq(ExpectedAlpn()), _, _))
2849           .WillOnce(Return(ByMove(CreateSession(
2850               dispatcher_.get(), config_, TestConnectionId(conn_id),
2851               client_addr_, &mock_helper_, &mock_alarm_factory_,
2852               &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()),
2853               &session1_))));
2854       EXPECT_CALL(
2855           *reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2856           ProcessUdpPacket(_, _, _))
2857           .WillRepeatedly(WithArg<2>(
2858               Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2859                 if (version_.UsesQuicCrypto()) {
2860                   ValidatePacket(TestConnectionId(conn_id), packet);
2861                 }
2862               })));
2863     }
2864     ProcessFirstFlight(TestConnectionId(conn_id));
2865   }
2866 
2867   // Process another |kDefaultMaxUndecryptablePackets| + 1 data packets. The
2868   // last one should be dropped.
2869   for (uint64_t packet_number = 2;
2870        packet_number <= kDefaultMaxUndecryptablePackets + 2; ++packet_number) {
2871     ProcessPacket(client_addr_, last_connection_id, true, "data packet");
2872   }
2873 
2874   // Reset counter and process buffered CHLO.
2875   EXPECT_CALL(*dispatcher_,
2876               CreateQuicSession(last_connection_id, _, client_addr_,
2877                                 Eq(ExpectedAlpn()), _, _))
2878       .WillOnce(Return(ByMove(CreateSession(
2879           dispatcher_.get(), config_, last_connection_id, client_addr_,
2880           &mock_helper_, &mock_alarm_factory_, &crypto_config_,
2881           QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2882   // Only CHLO and following |kDefaultMaxUndecryptablePackets| data packets
2883   // should be process.
2884   EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2885               ProcessUdpPacket(_, _, _))
2886       .Times(kDefaultMaxUndecryptablePackets + 1)
2887       .WillRepeatedly(WithArg<2>(
2888           Invoke([this, last_connection_id](const QuicEncryptedPacket& packet) {
2889             if (version_.UsesQuicCrypto()) {
2890               ValidatePacket(last_connection_id, packet);
2891             }
2892           })));
2893   dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate);
2894 }
2895 
2896 // Tests that when dispatcher's packet buffer is full, a CHLO on connection
2897 // which doesn't have buffered CHLO should be buffered.
TEST_P(BufferedPacketStoreTest,ReceiveCHLOForBufferedConnection)2898 TEST_P(BufferedPacketStoreTest, ReceiveCHLOForBufferedConnection) {
2899   QuicBufferedPacketStore* store =
2900       QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get());
2901 
2902   uint64_t conn_id = 1;
2903   ProcessUndecryptableEarlyPacket(TestConnectionId(conn_id));
2904   // Fill packet buffer to full with CHLOs on other connections. Need to feed
2905   // extra CHLOs because the first |kMaxNumSessionsToCreate| are going to create
2906   // session directly.
2907   for (conn_id = 2;
2908        conn_id <= kDefaultMaxConnectionsInStore + kMaxNumSessionsToCreate;
2909        ++conn_id) {
2910     if (conn_id <= kMaxNumSessionsToCreate + 1) {
2911       EXPECT_CALL(*dispatcher_,
2912                   CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2913                                     Eq(ExpectedAlpn()), _, _))
2914           .WillOnce(Return(ByMove(CreateSession(
2915               dispatcher_.get(), config_, TestConnectionId(conn_id),
2916               client_addr_, &mock_helper_, &mock_alarm_factory_,
2917               &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()),
2918               &session1_))));
2919       EXPECT_CALL(
2920           *reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2921           ProcessUdpPacket(_, _, _))
2922           .WillOnce(WithArg<2>(
2923               Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2924                 if (version_.UsesQuicCrypto()) {
2925                   ValidatePacket(TestConnectionId(conn_id), packet);
2926                 }
2927               })));
2928     } else {
2929       expect_generator_is_called_ = false;
2930     }
2931     ProcessFirstFlight(TestConnectionId(conn_id));
2932   }
2933   EXPECT_FALSE(store->HasChloForConnection(
2934       /*connection_id=*/TestConnectionId(1)));
2935 
2936   // CHLO on connection 1 should still be buffered.
2937   ProcessFirstFlight(TestConnectionId(1));
2938   EXPECT_TRUE(store->HasChloForConnection(
2939       /*connection_id=*/TestConnectionId(1)));
2940 }
2941 
2942 // Regression test for b/117874922.
TEST_P(BufferedPacketStoreTest,ProcessBufferedChloWithDifferentVersion)2943 TEST_P(BufferedPacketStoreTest, ProcessBufferedChloWithDifferentVersion) {
2944   // Ensure the preferred version is not supported by the server.
2945   QuicDisableVersion(AllSupportedVersions().front());
2946 
2947   uint64_t last_connection_id = kMaxNumSessionsToCreate + 5;
2948   ParsedQuicVersionVector supported_versions = CurrentSupportedVersions();
2949   for (uint64_t conn_id = 1; conn_id <= last_connection_id; ++conn_id) {
2950     // Last 5 CHLOs will be buffered. Others will create connection right away.
2951     ParsedQuicVersion version =
2952         supported_versions[(conn_id - 1) % supported_versions.size()];
2953     if (conn_id <= kMaxNumSessionsToCreate) {
2954       EXPECT_CALL(
2955           *dispatcher_,
2956           CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2957                             Eq(ExpectedAlpnForVersion(version)), version, _))
2958           .WillOnce(Return(ByMove(CreateSession(
2959               dispatcher_.get(), config_, TestConnectionId(conn_id),
2960               client_addr_, &mock_helper_, &mock_alarm_factory_,
2961               &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()),
2962               &session1_))));
2963       EXPECT_CALL(
2964           *reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2965           ProcessUdpPacket(_, _, _))
2966           .WillRepeatedly(WithArg<2>(
2967               Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2968                 if (version_.UsesQuicCrypto()) {
2969                   ValidatePacket(TestConnectionId(conn_id), packet);
2970                 }
2971               })));
2972     }
2973     ProcessFirstFlight(version, TestConnectionId(conn_id));
2974   }
2975 
2976   // Process buffered CHLOs. Verify the version is correct.
2977   for (uint64_t conn_id = kMaxNumSessionsToCreate + 1;
2978        conn_id <= last_connection_id; ++conn_id) {
2979     ParsedQuicVersion version =
2980         supported_versions[(conn_id - 1) % supported_versions.size()];
2981     EXPECT_CALL(
2982         *dispatcher_,
2983         CreateQuicSession(TestConnectionId(conn_id), _, client_addr_,
2984                           Eq(ExpectedAlpnForVersion(version)), version, _))
2985         .WillOnce(Return(ByMove(CreateSession(
2986             dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_,
2987             &mock_helper_, &mock_alarm_factory_, &crypto_config_,
2988             QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_))));
2989     EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()),
2990                 ProcessUdpPacket(_, _, _))
2991         .WillRepeatedly(WithArg<2>(
2992             Invoke([this, conn_id](const QuicEncryptedPacket& packet) {
2993               if (version_.UsesQuicCrypto()) {
2994                 ValidatePacket(TestConnectionId(conn_id), packet);
2995               }
2996             })));
2997   }
2998   dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate);
2999 }
3000 
3001 }  // namespace
3002 }  // namespace test
3003 }  // namespace quic
3004