blob: 8dd8f6759b5ba915acc42c471f3fa43d5a32b77e [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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 "net/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <errno.h>
zhongyi546cc452019-04-12 15:27:49 -07008
QUICHE teama6ef0a62019-03-07 20:34:33 -05009#include <memory>
10#include <ostream>
zhongyi9e843642019-04-12 09:04:54 -070011#include <string>
zhongyi546cc452019-04-12 15:27:49 -070012#include <utility>
zhongyi9e843642019-04-12 09:04:54 -070013
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/congestion_control/loss_detection_interface.h"
15#include "net/third_party/quiche/src/quic/core/congestion_control/send_algorithm_interface.h"
zhongyi546cc452019-04-12 15:27:49 -070016#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
21#include "net/third_party/quiche/src/quic/core/quic_packets.h"
22#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
23#include "net/third_party/quiche/src/quic/core/quic_types.h"
24#include "net/third_party/quiche/src/quic/core/quic_utils.h"
25#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
26#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
27#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050029#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050030#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
31#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
32#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
33#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
34#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
35#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050037#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
39#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
40#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
41#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080042#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
43#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050044
45using testing::_;
46using testing::AnyNumber;
47using testing::AtLeast;
48using testing::DoAll;
49using testing::Exactly;
50using testing::Ge;
51using testing::IgnoreResult;
52using testing::InSequence;
53using testing::Invoke;
54using testing::InvokeWithoutArgs;
55using testing::Lt;
56using testing::Ref;
57using testing::Return;
58using testing::SaveArg;
59using testing::SetArgPointee;
60using testing::StrictMock;
61
62namespace quic {
63namespace test {
64namespace {
65
nharper55fa6132019-05-07 19:37:21 -070066const char data1[] = "foo data";
67const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050068
69const bool kHasStopWaiting = true;
70
71const int kDefaultRetransmissionTimeMs = 500;
72
QUICHE team548d51b2019-03-14 10:06:54 -070073DiversificationNonce kTestDiversificationNonce = {
74 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
75 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
76 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
77};
78
QUICHE teama6ef0a62019-03-07 20:34:33 -050079const QuicSocketAddress kPeerAddress =
80 QuicSocketAddress(QuicIpAddress::Loopback6(),
81 /*port=*/12345);
82const QuicSocketAddress kSelfAddress =
83 QuicSocketAddress(QuicIpAddress::Loopback6(),
84 /*port=*/443);
85
QUICHE teama6ef0a62019-03-07 20:34:33 -050086QuicStreamId GetNthClientInitiatedStreamId(int n,
87 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070088 return QuicUtils::GetFirstBidirectionalStreamId(version,
89 Perspective::IS_CLIENT) +
90 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050091}
92
QUICHE team8c1daa22019-03-13 08:33:41 -070093QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
94 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070095 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070096 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -070097 case ENCRYPTION_HANDSHAKE:
98 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -070099 case ENCRYPTION_ZERO_RTT:
100 return ZERO_RTT_PROTECTED;
101 case ENCRYPTION_FORWARD_SECURE:
102 DCHECK(false);
103 return INVALID_PACKET_TYPE;
104 default:
105 DCHECK(false);
106 return INVALID_PACKET_TYPE;
107 }
108}
109
QUICHE teama6ef0a62019-03-07 20:34:33 -0500110// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
111class TaggingEncrypter : public QuicEncrypter {
112 public:
113 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
114 TaggingEncrypter(const TaggingEncrypter&) = delete;
115 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
116
117 ~TaggingEncrypter() override {}
118
119 // QuicEncrypter interface.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800120 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500121
dmcardlecf0bfcf2019-12-13 08:08:21 -0800122 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700123 return true;
124 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500125
dmcardlecf0bfcf2019-12-13 08:08:21 -0800126 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127
dmcardlecf0bfcf2019-12-13 08:08:21 -0800128 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
129 return true;
130 }
QUICHE team2d187972019-03-19 16:23:47 -0700131
dschinazi17d42422019-06-18 16:35:07 -0700132 bool EncryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800133 quiche::QuicheStringPiece /*associated_data*/,
134 quiche::QuicheStringPiece plaintext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500135 char* output,
136 size_t* output_length,
137 size_t max_output_length) override {
138 const size_t len = plaintext.size() + kTagSize;
139 if (max_output_length < len) {
140 return false;
141 }
142 // Memmove is safe for inplace encryption.
143 memmove(output, plaintext.data(), plaintext.size());
144 output += plaintext.size();
145 memset(output, tag_, kTagSize);
146 *output_length = len;
147 return true;
148 }
149
dschinazi17d42422019-06-18 16:35:07 -0700150 std::string GenerateHeaderProtectionMask(
dmcardlecf0bfcf2019-12-13 08:08:21 -0800151 quiche::QuicheStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700152 return std::string(5, 0);
153 }
154
QUICHE teama6ef0a62019-03-07 20:34:33 -0500155 size_t GetKeySize() const override { return 0; }
156 size_t GetNoncePrefixSize() const override { return 0; }
157 size_t GetIVSize() const override { return 0; }
158
159 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
160 return ciphertext_size - kTagSize;
161 }
162
163 size_t GetCiphertextSize(size_t plaintext_size) const override {
164 return plaintext_size + kTagSize;
165 }
166
dmcardlecf0bfcf2019-12-13 08:08:21 -0800167 quiche::QuicheStringPiece GetKey() const override {
168 return quiche::QuicheStringPiece();
169 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500170
dmcardlecf0bfcf2019-12-13 08:08:21 -0800171 quiche::QuicheStringPiece GetNoncePrefix() const override {
172 return quiche::QuicheStringPiece();
173 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500174
175 private:
176 enum {
177 kTagSize = 12,
178 };
179
180 const uint8_t tag_;
181};
182
183// TaggingDecrypter ensures that the final kTagSize bytes of the message all
184// have the same value and then removes them.
185class TaggingDecrypter : public QuicDecrypter {
186 public:
187 ~TaggingDecrypter() override {}
188
189 // QuicDecrypter interface
dmcardlecf0bfcf2019-12-13 08:08:21 -0800190 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500191
dmcardlecf0bfcf2019-12-13 08:08:21 -0800192 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700193 return true;
194 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500195
dmcardlecf0bfcf2019-12-13 08:08:21 -0800196 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500197
dmcardlecf0bfcf2019-12-13 08:08:21 -0800198 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
199 return true;
200 }
QUICHE team2d187972019-03-19 16:23:47 -0700201
dmcardlecf0bfcf2019-12-13 08:08:21 -0800202 bool SetPreliminaryKey(quiche::QuicheStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500203 QUIC_BUG << "should not be called";
204 return false;
205 }
206
dschinazi17d42422019-06-18 16:35:07 -0700207 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500208 return true;
209 }
210
dschinazi17d42422019-06-18 16:35:07 -0700211 bool DecryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800212 quiche::QuicheStringPiece /*associated_data*/,
213 quiche::QuicheStringPiece ciphertext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500214 char* output,
215 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700216 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217 if (ciphertext.size() < kTagSize) {
218 return false;
219 }
220 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
221 return false;
222 }
223 *output_length = ciphertext.size() - kTagSize;
224 memcpy(output, ciphertext.data(), *output_length);
225 return true;
226 }
227
QUICHE team2d187972019-03-19 16:23:47 -0700228 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700229 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700230 return std::string(5, 0);
231 }
232
QUICHE teama6ef0a62019-03-07 20:34:33 -0500233 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700234 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500235 size_t GetIVSize() const override { return 0; }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800236 quiche::QuicheStringPiece GetKey() const override {
237 return quiche::QuicheStringPiece();
238 }
239 quiche::QuicheStringPiece GetNoncePrefix() const override {
240 return quiche::QuicheStringPiece();
241 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500242 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
243 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
244
245 protected:
dmcardlecf0bfcf2019-12-13 08:08:21 -0800246 virtual uint8_t GetTag(quiche::QuicheStringPiece ciphertext) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500247 return ciphertext.data()[ciphertext.size() - 1];
248 }
249
250 private:
251 enum {
252 kTagSize = 12,
253 };
254
dmcardlecf0bfcf2019-12-13 08:08:21 -0800255 bool CheckTag(quiche::QuicheStringPiece ciphertext, uint8_t tag) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500256 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
257 if (ciphertext.data()[i] != tag) {
258 return false;
259 }
260 }
261
262 return true;
263 }
264};
265
266// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
267// match the expected value.
268class StrictTaggingDecrypter : public TaggingDecrypter {
269 public:
270 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
271 ~StrictTaggingDecrypter() override {}
272
273 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800274 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
275 return tag_;
276 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500277
278 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
279 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
280
281 private:
282 const uint8_t tag_;
283};
284
285class TestConnectionHelper : public QuicConnectionHelperInterface {
286 public:
287 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
288 : clock_(clock), random_generator_(random_generator) {
289 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
290 }
291 TestConnectionHelper(const TestConnectionHelper&) = delete;
292 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
293
294 // QuicConnectionHelperInterface
295 const QuicClock* GetClock() const override { return clock_; }
296
297 QuicRandom* GetRandomGenerator() override { return random_generator_; }
298
299 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
300 return &buffer_allocator_;
301 }
302
303 private:
304 MockClock* clock_;
305 MockRandom* random_generator_;
306 SimpleBufferAllocator buffer_allocator_;
307};
308
309class TestAlarmFactory : public QuicAlarmFactory {
310 public:
311 class TestAlarm : public QuicAlarm {
312 public:
313 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
314 : QuicAlarm(std::move(delegate)) {}
315
316 void SetImpl() override {}
317 void CancelImpl() override {}
318 using QuicAlarm::Fire;
319 };
320
321 TestAlarmFactory() {}
322 TestAlarmFactory(const TestAlarmFactory&) = delete;
323 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
324
325 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
326 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
327 }
328
329 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
330 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
331 QuicConnectionArena* arena) override {
332 return arena->New<TestAlarm>(std::move(delegate));
333 }
334};
335
336class TestPacketWriter : public QuicPacketWriter {
337 public:
338 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
339 : version_(version),
340 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
341 last_packet_size_(0),
342 write_blocked_(false),
343 write_should_fail_(false),
344 block_on_next_flush_(false),
345 block_on_next_write_(false),
346 next_packet_too_large_(false),
347 always_get_packet_too_large_(false),
348 is_write_blocked_data_buffered_(false),
349 is_batch_mode_(false),
350 final_bytes_of_last_packet_(0),
351 final_bytes_of_previous_packet_(0),
352 use_tagging_decrypter_(false),
353 packets_write_attempts_(0),
rchd672c6d2019-11-27 15:30:54 -0800354 connection_close_packets_(0),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500355 clock_(clock),
356 write_pause_time_delta_(QuicTime::Delta::Zero()),
dschinazi66dea072019-04-09 11:41:06 -0700357 max_packet_size_(kMaxOutgoingPacketSize),
dschinazib953d022019-08-01 18:05:58 -0700358 supports_release_time_(false) {
359 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
360 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700361 framer_.framer()->SetInitialObfuscators(TestConnectionId());
dschinazib953d022019-08-01 18:05:58 -0700362 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500363 TestPacketWriter(const TestPacketWriter&) = delete;
364 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
365
366 // QuicPacketWriter interface
367 WriteResult WritePacket(const char* buffer,
368 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700369 const QuicIpAddress& /*self_address*/,
370 const QuicSocketAddress& /*peer_address*/,
371 PerPacketOptions* /*options*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500372 QuicEncryptedPacket packet(buffer, buf_len);
373 ++packets_write_attempts_;
374
375 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
376 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
377 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
378 sizeof(final_bytes_of_last_packet_));
379 }
380
381 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700382 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700383 framer_.framer()->InstallDecrypter(
384 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
385 framer_.framer()->InstallDecrypter(
386 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
387 framer_.framer()->InstallDecrypter(
388 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700389 } else {
390 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700391 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700392 }
393 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
394 framer_.framer()->InstallDecrypter(
395 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700396 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500397 }
398 EXPECT_TRUE(framer_.ProcessPacket(packet));
399 if (block_on_next_write_) {
400 write_blocked_ = true;
401 block_on_next_write_ = false;
402 }
403 if (next_packet_too_large_) {
404 next_packet_too_large_ = false;
405 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
406 }
407 if (always_get_packet_too_large_) {
408 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
409 }
410 if (IsWriteBlocked()) {
411 return WriteResult(is_write_blocked_data_buffered_
412 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
413 : WRITE_STATUS_BLOCKED,
414 0);
415 }
416
417 if (ShouldWriteFail()) {
418 return WriteResult(WRITE_STATUS_ERROR, 0);
419 }
420
421 last_packet_size_ = packet.length();
422 last_packet_header_ = framer_.header();
rchd672c6d2019-11-27 15:30:54 -0800423 if (!framer_.connection_close_frames().empty()) {
424 ++connection_close_packets_;
425 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500426 if (!write_pause_time_delta_.IsZero()) {
427 clock_->AdvanceTime(write_pause_time_delta_);
428 }
429 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
430 }
431
432 bool ShouldWriteFail() { return write_should_fail_; }
433
434 bool IsWriteBlocked() const override { return write_blocked_; }
435
436 void SetWriteBlocked() { write_blocked_ = true; }
437
438 void SetWritable() override { write_blocked_ = false; }
439
440 void SetShouldWriteFail() { write_should_fail_ = true; }
441
442 QuicByteCount GetMaxPacketSize(
443 const QuicSocketAddress& /*peer_address*/) const override {
444 return max_packet_size_;
445 }
446
dschinazi61eb6432019-06-14 16:27:16 -0700447 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500448
449 bool IsBatchMode() const override { return is_batch_mode_; }
450
dschinazi17d42422019-06-18 16:35:07 -0700451 char* GetNextWriteLocation(
452 const QuicIpAddress& /*self_address*/,
453 const QuicSocketAddress& /*peer_address*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500454 return nullptr;
455 }
456
457 WriteResult Flush() override {
458 if (block_on_next_flush_) {
459 block_on_next_flush_ = false;
460 SetWriteBlocked();
461 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
462 }
463 return WriteResult(WRITE_STATUS_OK, 0);
464 }
465
466 void BlockOnNextFlush() { block_on_next_flush_ = true; }
467
468 void BlockOnNextWrite() { block_on_next_write_ = true; }
469
470 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
471
472 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
473
474 // Sets the amount of time that the writer should before the actual write.
475 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
476 write_pause_time_delta_ = delta;
477 }
478
479 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
480
481 const QuicPacketHeader& header() { return framer_.header(); }
482
483 size_t frame_count() const { return framer_.num_frames(); }
484
485 const std::vector<QuicAckFrame>& ack_frames() const {
486 return framer_.ack_frames();
487 }
488
489 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
490 return framer_.stop_waiting_frames();
491 }
492
493 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
494 return framer_.connection_close_frames();
495 }
496
497 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
498 return framer_.rst_stream_frames();
499 }
500
501 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
502 return framer_.stream_frames();
503 }
504
505 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
506 return framer_.crypto_frames();
507 }
508
509 const std::vector<QuicPingFrame>& ping_frames() const {
510 return framer_.ping_frames();
511 }
512
513 const std::vector<QuicMessageFrame>& message_frames() const {
514 return framer_.message_frames();
515 }
516
517 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
518 return framer_.window_update_frames();
519 }
520
521 const std::vector<QuicPaddingFrame>& padding_frames() const {
522 return framer_.padding_frames();
523 }
524
525 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
526 return framer_.path_challenge_frames();
527 }
528
529 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
530 return framer_.path_response_frames();
531 }
532
fayang58f71072019-11-05 08:47:02 -0800533 const QuicEncryptedPacket* coalesced_packet() const {
534 return framer_.coalesced_packet();
535 }
536
QUICHE teama6ef0a62019-03-07 20:34:33 -0500537 size_t last_packet_size() { return last_packet_size_; }
538
539 const QuicPacketHeader& last_packet_header() const {
540 return last_packet_header_;
541 }
542
543 const QuicVersionNegotiationPacket* version_negotiation_packet() {
544 return framer_.version_negotiation_packet();
545 }
546
547 void set_is_write_blocked_data_buffered(bool buffered) {
548 is_write_blocked_data_buffered_ = buffered;
549 }
550
551 void set_perspective(Perspective perspective) {
552 // We invert perspective here, because the framer needs to parse packets
553 // we send.
554 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700555 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500556 }
557
558 // final_bytes_of_last_packet_ returns the last four bytes of the previous
559 // packet as a little-endian, uint32_t. This is intended to be used with a
560 // TaggingEncrypter so that tests can determine which encrypter was used for
561 // a given packet.
562 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
563
564 // Returns the final bytes of the second to last packet.
565 uint32_t final_bytes_of_previous_packet() {
566 return final_bytes_of_previous_packet_;
567 }
568
569 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
570
571 uint32_t packets_write_attempts() { return packets_write_attempts_; }
572
rchd672c6d2019-11-27 15:30:54 -0800573 uint32_t connection_close_packets() const {
574 return connection_close_packets_;
575 }
576
QUICHE teama6ef0a62019-03-07 20:34:33 -0500577 void Reset() { framer_.Reset(); }
578
579 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
580 framer_.SetSupportedVersions(versions);
581 }
582
583 void set_max_packet_size(QuicByteCount max_packet_size) {
584 max_packet_size_ = max_packet_size;
585 }
586
587 void set_supports_release_time(bool supports_release_time) {
588 supports_release_time_ = supports_release_time;
589 }
590
591 SimpleQuicFramer* framer() { return &framer_; }
592
593 private:
594 ParsedQuicVersion version_;
595 SimpleQuicFramer framer_;
596 size_t last_packet_size_;
597 QuicPacketHeader last_packet_header_;
598 bool write_blocked_;
599 bool write_should_fail_;
600 bool block_on_next_flush_;
601 bool block_on_next_write_;
602 bool next_packet_too_large_;
603 bool always_get_packet_too_large_;
604 bool is_write_blocked_data_buffered_;
605 bool is_batch_mode_;
606 uint32_t final_bytes_of_last_packet_;
607 uint32_t final_bytes_of_previous_packet_;
608 bool use_tagging_decrypter_;
609 uint32_t packets_write_attempts_;
rchd672c6d2019-11-27 15:30:54 -0800610 uint32_t connection_close_packets_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500611 MockClock* clock_;
612 // If non-zero, the clock will pause during WritePacket for this amount of
613 // time.
614 QuicTime::Delta write_pause_time_delta_;
615 QuicByteCount max_packet_size_;
616 bool supports_release_time_;
617};
618
619class TestConnection : public QuicConnection {
620 public:
621 TestConnection(QuicConnectionId connection_id,
622 QuicSocketAddress address,
623 TestConnectionHelper* helper,
624 TestAlarmFactory* alarm_factory,
625 TestPacketWriter* writer,
626 Perspective perspective,
627 ParsedQuicVersion version)
628 : QuicConnection(connection_id,
629 address,
630 helper,
631 alarm_factory,
632 writer,
633 /* owns_writer= */ false,
634 perspective,
635 SupportedVersions(version)),
636 notifier_(nullptr) {
637 writer->set_perspective(perspective);
638 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700639 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500640 SetDataProducer(&producer_);
641 }
642 TestConnection(const TestConnection&) = delete;
643 TestConnection& operator=(const TestConnection&) = delete;
644
QUICHE teama6ef0a62019-03-07 20:34:33 -0500645 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
646 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
647 }
648
649 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
650 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
651 }
652
dschinazi17d42422019-06-18 16:35:07 -0700653 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500654 uint64_t packet_number,
655 std::unique_ptr<QuicPacket> packet,
656 HasRetransmittableData retransmittable,
657 bool has_ack,
658 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800659 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700660 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500661 size_t encrypted_length =
662 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700663 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700664 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500665 SerializedPacket serialized_packet(
666 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
667 encrypted_length, has_ack, has_pending_frames);
668 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
669 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800670 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500671 }
672 OnSerializedPacket(&serialized_packet);
673 }
674
675 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
676 const struct iovec* iov,
677 int iov_count,
678 size_t total_length,
679 QuicStreamOffset offset,
680 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700681 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500682 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
683 if (notifier_ != nullptr) {
684 return notifier_->WriteOrBufferData(id, total_length, state);
685 }
686 return QuicConnection::SendStreamData(id, total_length, offset, state);
687 }
688
689 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800690 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500691 QuicStreamOffset offset,
692 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700693 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700694 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700695 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500696 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800697 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700698 OnHandshakeComplete();
699 }
700 if (version().SupportsAntiAmplificationLimit()) {
701 QuicConnectionPeer::SetAddressValidated(this);
702 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500703 }
704 struct iovec iov;
705 MakeIOVector(data, &iov);
706 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
707 }
708
QUICHE teamcd098022019-03-22 18:49:55 -0700709 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
710 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800711 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700712 QuicStreamOffset offset,
713 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700714 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700715 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700716 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700717 SetDefaultEncryptionLevel(encryption_level);
718 struct iovec iov;
719 MakeIOVector(data, &iov);
720 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
721 }
722
QUICHE teama6ef0a62019-03-07 20:34:33 -0500723 QuicConsumedData SendStreamData3() {
724 return SendStreamDataWithString(
725 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
726 NO_FIN);
727 }
728
729 QuicConsumedData SendStreamData5() {
730 return SendStreamDataWithString(
731 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
732 NO_FIN);
733 }
734
735 // Ensures the connection can write stream data before writing.
736 QuicConsumedData EnsureWritableAndSendStreamData5() {
737 EXPECT_TRUE(CanWriteStreamData());
738 return SendStreamData5();
739 }
740
741 // The crypto stream has special semantics so that it is not blocked by a
742 // congestion window limitation, and also so that it gets put into a separate
743 // packet (so that it is easier to reason about a crypto frame not being
744 // split needlessly across packet boundaries). As a result, we have separate
745 // tests for some cases for this stream.
746 QuicConsumedData SendCryptoStreamData() {
747 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800748 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700749 if (!QuicVersionUsesCryptoFrames(transport_version())) {
750 return SendCryptoDataWithString(data, offset);
751 }
752 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
753 size_t bytes_written;
754 if (notifier_) {
755 bytes_written =
756 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
757 } else {
758 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
759 data.length(), offset);
760 }
761 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700762 }
763
dmcardlecf0bfcf2019-12-13 08:08:21 -0800764 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700765 QuicStreamOffset offset) {
QUICHE teamea740082019-03-11 17:58:43 -0700766 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500767 return SendStreamDataWithString(
768 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
769 NO_FIN);
770 }
QUICHE team6987b4a2019-03-15 16:23:04 -0700771 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500772 size_t bytes_written;
773 if (notifier_) {
774 bytes_written =
QUICHE team6987b4a2019-03-15 16:23:04 -0700775 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500776 } else {
QUICHE team6987b4a2019-03-15 16:23:04 -0700777 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500778 data.length(), offset);
779 }
780 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
781 }
782
783 void set_version(ParsedQuicVersion version) {
784 QuicConnectionPeer::GetFramer(this)->set_version(version);
785 }
786
787 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
788 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500789 writer()->SetSupportedVersions(versions);
790 }
791
792 void set_perspective(Perspective perspective) {
793 writer()->set_perspective(perspective);
794 QuicConnectionPeer::SetPerspective(this, perspective);
795 }
796
797 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800798 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500799 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800800 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500801
802 QuicConfig config;
803 QuicTagVector connection_options;
804 connection_options.push_back(kMTUH);
wub031d47c2019-11-21 08:04:07 -0800805 config.SetInitialReceivedConnectionOptions(connection_options);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500806 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
807 SetFromConfig(config);
808
809 // Normally, the pacing would be disabled in the test, but calling
810 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
811 // pacing algorithm work.
812 EXPECT_CALL(*send_algorithm, PacingRate(_))
813 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
814 }
815
816 TestAlarmFactory::TestAlarm* GetAckAlarm() {
817 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
818 QuicConnectionPeer::GetAckAlarm(this));
819 }
820
821 TestAlarmFactory::TestAlarm* GetPingAlarm() {
822 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
823 QuicConnectionPeer::GetPingAlarm(this));
824 }
825
826 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
827 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
828 QuicConnectionPeer::GetRetransmissionAlarm(this));
829 }
830
831 TestAlarmFactory::TestAlarm* GetSendAlarm() {
832 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
833 QuicConnectionPeer::GetSendAlarm(this));
834 }
835
836 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
837 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
838 QuicConnectionPeer::GetTimeoutAlarm(this));
839 }
840
841 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
842 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
843 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
844 }
845
846 TestAlarmFactory::TestAlarm* GetPathDegradingAlarm() {
847 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
848 QuicConnectionPeer::GetPathDegradingAlarm(this));
849 }
850
851 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
852 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
853 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
854 }
855
856 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
857 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
858 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
859 }
860
861 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700862 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500863 }
864
865 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
866
867 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700868 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500869 }
870
fayang5f135052019-08-22 17:59:40 -0700871 bool PtoEnabled() {
872 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
873 // PTO mode is default enabled for T099. And TLP/RTO related tests are
874 // stale.
875 DCHECK_EQ(ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_99), version());
876 return true;
877 }
878 return false;
879 }
880
nharper46833c32019-05-15 21:33:05 -0700881 SimpleDataProducer* producer() { return &producer_; }
882
QUICHE teama6ef0a62019-03-07 20:34:33 -0500883 using QuicConnection::active_effective_peer_migration_type;
884 using QuicConnection::IsCurrentPacketConnectivityProbing;
885 using QuicConnection::SelectMutualVersion;
886 using QuicConnection::SendProbingRetransmissions;
887 using QuicConnection::set_defer_send_in_response_to_packets;
888
889 protected:
890 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
891 if (next_effective_peer_addr_) {
892 return *std::move(next_effective_peer_addr_);
893 }
894 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
895 }
896
897 private:
898 TestPacketWriter* writer() {
899 return static_cast<TestPacketWriter*>(QuicConnection::writer());
900 }
901
902 SimpleDataProducer producer_;
903
904 SimpleSessionNotifier* notifier_;
905
906 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
907};
908
909enum class AckResponse { kDefer, kImmediate };
910
911// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
912struct TestParams {
913 TestParams(ParsedQuicVersion version,
914 AckResponse ack_response,
915 bool no_stop_waiting)
916 : version(version),
917 ack_response(ack_response),
918 no_stop_waiting(no_stop_waiting) {}
919
QUICHE teama6ef0a62019-03-07 20:34:33 -0500920 ParsedQuicVersion version;
921 AckResponse ack_response;
922 bool no_stop_waiting;
923};
924
dschinazi142051a2019-09-18 18:17:29 -0700925// Used by ::testing::PrintToStringParamName().
926std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -0800927 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -0700928 ParsedQuicVersionToString(p.version), "_",
929 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
930 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
931}
932
QUICHE teama6ef0a62019-03-07 20:34:33 -0500933// Constructs various test permutations.
934std::vector<TestParams> GetTestParams() {
935 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500936 std::vector<TestParams> params;
937 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
938 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
939 for (AckResponse ack_response :
940 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -0700941 params.push_back(
942 TestParams(all_supported_versions[i], ack_response, true));
943 if (!VersionHasIetfInvariantHeader(
944 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -0700945 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -0700946 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500947 }
948 }
949 }
950 return params;
951}
952
953class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -0700954 public:
955 // For tests that do silent connection closes, no such packet is generated. In
956 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
957 // should invoke this method, saving the frame, and then the test can verify
958 // the contents.
959 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
960 ConnectionCloseSource /*source*/) {
961 saved_connection_close_frame_ = frame;
962 connection_close_frame_count_++;
963 }
964
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 protected:
966 QuicConnectionTest()
967 : connection_id_(TestConnectionId()),
968 framer_(SupportedVersions(version()),
969 QuicTime::Zero(),
970 Perspective::IS_CLIENT,
971 connection_id_.length()),
972 send_algorithm_(new StrictMock<MockSendAlgorithm>),
973 loss_algorithm_(new MockLossAlgorithm()),
974 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
975 alarm_factory_(new TestAlarmFactory()),
976 peer_framer_(SupportedVersions(version()),
977 QuicTime::Zero(),
978 Perspective::IS_SERVER,
979 connection_id_.length()),
980 peer_creator_(connection_id_,
981 &peer_framer_,
982 /*delegate=*/nullptr),
983 writer_(new TestPacketWriter(version(), &clock_)),
984 connection_(connection_id_,
985 kPeerAddress,
986 helper_.get(),
987 alarm_factory_.get(),
988 writer_.get(),
989 Perspective::IS_CLIENT,
990 version()),
991 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500992 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -0800993 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
994 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
995 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500996 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
997 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -0700998 notifier_(&connection_),
999 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001000 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001001 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1002 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001003 framer_.SetInitialObfuscators(TestConnectionId());
1004 connection_.InstallInitialCrypters(TestConnectionId());
1005 CrypterPair crypters;
1006 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1007 TestConnectionId(), &crypters);
1008 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1009 std::move(crypters.encrypter));
1010 if (version().KnowsWhichDecrypterToUse()) {
1011 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1012 std::move(crypters.decrypter));
1013 } else {
1014 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1015 std::move(crypters.decrypter));
1016 }
nharper2c9f02a2019-05-08 10:25:50 -07001017 for (EncryptionLevel level :
1018 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1019 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001020 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001021 }
dschinazi7b9278c2019-05-20 07:36:21 -07001022 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001023 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001024 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1025 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001026 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001027 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1028 } else {
1029 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1030 GetParam().no_stop_waiting);
1031 }
nharper46833c32019-05-15 21:33:05 -07001032 QuicStreamId stream_id;
1033 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1034 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1035 version().transport_version, Perspective::IS_CLIENT);
1036 } else {
1037 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1038 }
1039 frame1_.stream_id = stream_id;
1040 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001041 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001042 connection_.SetSessionNotifier(&notifier_);
1043 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001044 connection_.SetSendAlgorithm(send_algorithm_);
1045 connection_.SetLossAlgorithm(loss_algorithm_.get());
1046 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1047 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1048 .Times(AnyNumber());
1049 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1050 .WillRepeatedly(Return(kDefaultTCPMSS));
1051 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1052 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1053 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
1054 .Times(AnyNumber());
1055 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1056 .Times(AnyNumber())
1057 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001058 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1059 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001060 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1061 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1062 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1063 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001064 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001065 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001066 EXPECT_CALL(visitor_, OnCanWrite())
1067 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001068 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1069 .WillRepeatedly(Return(false));
1070 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001071 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001072 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001073 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001074
1075 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1076 .WillRepeatedly(Return(QuicTime::Zero()));
1077 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1078 .Times(AnyNumber());
zhongyi546cc452019-04-12 15:27:49 -07001079
1080 if (connection_.version().KnowsWhichDecrypterToUse()) {
1081 connection_.InstallDecrypter(
1082 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001083 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001084 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 }
1086
1087 QuicConnectionTest(const QuicConnectionTest&) = delete;
1088 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1089
1090 ParsedQuicVersion version() { return GetParam().version; }
1091
QUICHE teama6ef0a62019-03-07 20:34:33 -05001092 QuicStopWaitingFrame* stop_waiting() {
1093 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1094 return &stop_waiting_;
1095 }
1096
1097 QuicPacketNumber least_unacked() {
1098 if (writer_->stop_waiting_frames().empty()) {
1099 return QuicPacketNumber();
1100 }
1101 return writer_->stop_waiting_frames()[0].least_unacked;
1102 }
1103
1104 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1105
zhongyi546cc452019-04-12 15:27:49 -07001106 void SetDecrypter(EncryptionLevel level,
1107 std::unique_ptr<QuicDecrypter> decrypter) {
1108 if (connection_.version().KnowsWhichDecrypterToUse()) {
1109 connection_.InstallDecrypter(level, std::move(decrypter));
1110 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1111 } else {
1112 connection_.SetDecrypter(level, std::move(decrypter));
1113 }
1114 }
1115
QUICHE teama6ef0a62019-03-07 20:34:33 -05001116 void ProcessPacket(uint64_t number) {
1117 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1118 ProcessDataPacket(number);
1119 if (connection_.GetSendAlarm()->IsSet()) {
1120 connection_.GetSendAlarm()->Fire();
1121 }
1122 }
1123
1124 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1125 const QuicSocketAddress& peer_address,
1126 const QuicReceivedPacket& packet) {
1127 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1128 if (connection_.GetSendAlarm()->IsSet()) {
1129 connection_.GetSendAlarm()->Fire();
1130 }
1131 }
1132
1133 void ProcessFramePacket(QuicFrame frame) {
1134 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1135 }
1136
1137 void ProcessFramePacketWithAddresses(QuicFrame frame,
1138 QuicSocketAddress self_address,
1139 QuicSocketAddress peer_address) {
1140 QuicFrames frames;
1141 frames.push_back(QuicFrame(frame));
1142 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001143 &peer_creator_,
1144 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1145 ENCRYPTION_FORWARD_SECURE &&
1146 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001147
dschinazi66dea072019-04-09 11:41:06 -07001148 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001149 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001150 QuicPacketCreatorPeer::SerializeAllFrames(
1151 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001152 connection_.ProcessUdpPacket(
1153 self_address, peer_address,
1154 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1155 serialized_packet.encrypted_length, clock_.Now()));
1156 if (connection_.GetSendAlarm()->IsSet()) {
1157 connection_.GetSendAlarm()->Fire();
1158 }
1159 }
1160
1161 // Bypassing the packet creator is unrealistic, but allows us to process
1162 // packets the QuicPacketCreator won't allow us to create.
1163 void ForceProcessFramePacket(QuicFrame frame) {
1164 QuicFrames frames;
1165 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001166 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1167 if (connection_.version().KnowsWhichDecrypterToUse()) {
1168 send_version = true;
1169 }
1170 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001171 QuicPacketHeader header;
1172 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001173 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001174 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001175 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1176 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001177 DCHECK_GT(length, 0u);
1178
1179 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001180 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001181 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1182 header),
dschinazi66dea072019-04-09 11:41:06 -07001183 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001184 DCHECK_GT(encrypted_length, 0u);
1185
1186 connection_.ProcessUdpPacket(
1187 kSelfAddress, kPeerAddress,
1188 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1189 }
1190
1191 size_t ProcessFramePacketAtLevel(uint64_t number,
1192 QuicFrame frame,
1193 EncryptionLevel level) {
1194 QuicPacketHeader header;
1195 header.destination_connection_id = connection_id_;
1196 header.packet_number_length = packet_number_length_;
1197 header.destination_connection_id_included = connection_id_included_;
dschinazi5e1a7b22019-07-31 12:23:21 -07001198 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001199 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1200 }
zhongyi546cc452019-04-12 15:27:49 -07001201 if (level == ENCRYPTION_INITIAL &&
1202 peer_framer_.version().KnowsWhichDecrypterToUse()) {
1203 header.version_flag = true;
nharperd43f1d62019-07-01 15:18:20 -07001204 if (QuicVersionHasLongHeaderLengths(peer_framer_.transport_version())) {
1205 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1206 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1207 }
QUICHE team2252b702019-05-14 23:55:14 -04001208 }
dschinazi5e1a7b22019-07-31 12:23:21 -07001209 if (header.version_flag &&
QUICHE team2252b702019-05-14 23:55:14 -04001210 peer_framer_.perspective() == Perspective::IS_SERVER) {
1211 header.source_connection_id = connection_id_;
1212 header.source_connection_id_included = CONNECTION_ID_PRESENT;
zhongyi546cc452019-04-12 15:27:49 -07001213 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001214 header.packet_number = QuicPacketNumber(number);
1215 QuicFrames frames;
1216 frames.push_back(frame);
1217 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teamcd098022019-03-22 18:49:55 -07001218 // Set the correct encryption level and encrypter on peer_creator and
1219 // peer_framer, respectively.
1220 peer_creator_.set_encryption_level(level);
1221 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1222 ENCRYPTION_INITIAL) {
1223 peer_framer_.SetEncrypter(
1224 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001225 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001226 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001227 if (connection_.version().KnowsWhichDecrypterToUse()) {
1228 connection_.InstallDecrypter(
1229 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001230 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001231 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1232 } else {
1233 connection_.SetDecrypter(
1234 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001235 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001236 }
QUICHE teamcd098022019-03-22 18:49:55 -07001237 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001238
dschinazi66dea072019-04-09 11:41:06 -07001239 char buffer[kMaxOutgoingPacketSize];
1240 size_t encrypted_length =
1241 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1242 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001243 connection_.ProcessUdpPacket(
1244 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001245 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1246 if (connection_.GetSendAlarm()->IsSet()) {
1247 connection_.GetSendAlarm()->Fire();
1248 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001249 return encrypted_length;
1250 }
1251
1252 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001253 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001254 }
1255
1256 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001257 return ProcessDataPacketAtLevel(packet_number, false,
1258 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001259 }
1260
1261 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1262 bool has_stop_waiting,
1263 EncryptionLevel level) {
1264 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1265 level);
1266 }
1267
dschinazi17d42422019-06-18 16:35:07 -07001268 size_t ProcessCryptoPacketAtLevel(uint64_t number,
1269 EncryptionLevel /*level*/) {
fayangc31c9952019-06-05 13:54:48 -07001270 QuicPacketHeader header = ConstructPacketHeader(number, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07001271 QuicFrames frames;
1272 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1273 frames.push_back(QuicFrame(&crypto_frame_));
1274 } else {
1275 frames.push_back(QuicFrame(frame1_));
1276 }
fayang5f135052019-08-22 17:59:40 -07001277 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001278 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1279 char buffer[kMaxOutgoingPacketSize];
1280 peer_creator_.set_encryption_level(ENCRYPTION_INITIAL);
fayangc31c9952019-06-05 13:54:48 -07001281 size_t encrypted_length = peer_framer_.EncryptPayload(
1282 ENCRYPTION_INITIAL, QuicPacketNumber(number), *packet, buffer,
1283 kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001284 connection_.ProcessUdpPacket(
1285 kSelfAddress, kPeerAddress,
1286 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1287 if (connection_.GetSendAlarm()->IsSet()) {
1288 connection_.GetSendAlarm()->Fire();
1289 }
1290 return encrypted_length;
1291 }
1292
QUICHE teama6ef0a62019-03-07 20:34:33 -05001293 size_t ProcessDataPacketAtLevel(uint64_t number,
1294 bool has_stop_waiting,
1295 EncryptionLevel level) {
1296 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001297 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001298 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001299 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001300 size_t encrypted_length =
1301 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1302 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001303 connection_.ProcessUdpPacket(
1304 kSelfAddress, kPeerAddress,
1305 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1306 if (connection_.GetSendAlarm()->IsSet()) {
1307 connection_.GetSendAlarm()->Fire();
1308 }
1309 return encrypted_length;
1310 }
1311
1312 void ProcessClosePacket(uint64_t number) {
1313 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001314 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001315 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001316 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001317 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001318 connection_.ProcessUdpPacket(
1319 kSelfAddress, kPeerAddress,
1320 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1321 }
1322
1323 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001324 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325 QuicStreamOffset offset,
1326 StreamSendingState state,
1327 QuicPacketNumber* last_packet) {
1328 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001329 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001330 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001331 .Times(AnyNumber())
1332 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001333 connection_.SendStreamDataWithString(id, data, offset, state);
1334 if (last_packet != nullptr) {
1335 *last_packet = creator_->packet_number();
1336 }
1337 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1338 .Times(AnyNumber());
1339 return packet_size;
1340 }
1341
1342 void SendAckPacketToPeer() {
1343 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1344 {
fayanga4b37b22019-06-18 13:37:47 -07001345 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001346 connection_.SendAck();
1347 }
1348 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1349 .Times(AnyNumber());
1350 }
1351
1352 void SendRstStream(QuicStreamId id,
1353 QuicRstStreamErrorCode error,
1354 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001355 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001356 connection_.OnStreamReset(id, error);
1357 }
1358
fayangcff885a2019-10-22 07:39:04 -07001359 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001360
QUICHE teama6ef0a62019-03-07 20:34:33 -05001361 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1362 if (packet_number > 1) {
1363 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1364 } else {
1365 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1366 }
1367 ProcessFramePacket(QuicFrame(frame));
1368 }
1369
1370 void ProcessAckPacket(QuicAckFrame* frame) {
1371 ProcessFramePacket(QuicFrame(frame));
1372 }
1373
1374 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1375 ProcessFramePacket(QuicFrame(frame));
1376 }
1377
1378 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1379 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001380 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001381 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1382 ENCRYPTION_ZERO_RTT);
1383 }
1384
1385 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1386 ProcessFramePacket(QuicFrame(frame));
1387 }
1388
1389 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001390 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001391 QuicPacketNumber());
1392 }
1393
1394 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1395 const QuicFrames& frames) {
1396 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1397 EXPECT_NE(nullptr, packet.get());
1398 return packet;
1399 }
1400
nharper46833c32019-05-15 21:33:05 -07001401 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1402 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001403 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001404 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001405 level < ENCRYPTION_FORWARD_SECURE) {
1406 // Set long header type accordingly.
1407 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001408 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001409 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1410 if (QuicVersionHasLongHeaderLengths(
1411 peer_framer_.version().transport_version)) {
1412 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1413 if (header.long_packet_type == INITIAL) {
1414 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1415 }
1416 }
1417 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001418 // Set connection_id to peer's in memory representation as this data packet
1419 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001420 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001421 header.source_connection_id = connection_id_;
1422 header.source_connection_id_included = connection_id_included_;
1423 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1424 } else {
1425 header.destination_connection_id = connection_id_;
1426 header.destination_connection_id_included = connection_id_included_;
1427 }
fayangd4291e42019-05-30 10:31:21 -07001428 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 peer_framer_.perspective() == Perspective::IS_SERVER) {
1430 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001431 if (header.version_flag) {
1432 header.source_connection_id = connection_id_;
1433 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1434 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1435 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001436 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001437 }
1438 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001439 }
QUICHE team2252b702019-05-14 23:55:14 -04001440 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001441 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001442 return header;
1443 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001444
nharper46833c32019-05-15 21:33:05 -07001445 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1446 bool has_stop_waiting,
1447 EncryptionLevel level) {
1448 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001449 QuicFrames frames;
1450 frames.push_back(QuicFrame(frame1_));
1451 if (has_stop_waiting) {
1452 frames.push_back(QuicFrame(stop_waiting_));
1453 }
1454 return ConstructPacket(header, frames);
1455 }
1456
1457 OwningSerializedPacketPointer ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001458 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001459 QuicPathFrameBuffer payload = {
1460 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1461 return QuicPacketCreatorPeer::
1462 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1463 &payload);
1464 }
1465 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1466 &peer_creator_);
1467 }
1468
1469 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1470 QuicPacketHeader header;
1471 // Set connection_id to peer's in memory representation as this connection
1472 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001473 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001474 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001475 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001476 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001477 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1478 }
1479 } else {
1480 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001481 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001482 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1483 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001484 }
1485
QUICHE team2252b702019-05-14 23:55:14 -04001486 header.packet_number = QuicPacketNumber(number);
1487
fkastenholz0d6554a2019-08-05 12:20:35 -07001488 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001489 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1490 kQuicErrorCode, "",
1491 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001492 QuicFrames frames;
1493 frames.push_back(QuicFrame(&qccf));
1494 return ConstructPacket(header, frames);
1495 }
1496
1497 QuicTime::Delta DefaultRetransmissionTime() {
1498 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1499 }
1500
1501 QuicTime::Delta DefaultDelayedAckTime() {
1502 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1503 }
1504
1505 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1506 QuicStopWaitingFrame frame;
1507 frame.least_unacked = QuicPacketNumber(least_unacked);
1508 return frame;
1509 }
1510
1511 // Construct a ack_frame that acks all packet numbers between 1 and
1512 // |largest_acked|, except |missing|.
1513 // REQUIRES: 1 <= |missing| < |largest_acked|
1514 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1515 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1516 QuicPacketNumber(missing));
1517 }
1518
1519 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1520 QuicPacketNumber missing) {
1521 if (missing == QuicPacketNumber(1)) {
1522 return InitAckFrame({{missing + 1, largest_acked + 1}});
1523 }
1524 return InitAckFrame(
1525 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1526 }
1527
1528 // Undo nacking a packet within the frame.
1529 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1530 EXPECT_FALSE(frame->packets.Contains(arrived));
1531 frame->packets.Add(arrived);
1532 }
1533
1534 void TriggerConnectionClose() {
1535 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001536 EXPECT_CALL(visitor_,
1537 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1538 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1539
QUICHE teamcd098022019-03-22 18:49:55 -07001540 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1541 // Triggers a connection by receiving ACK of unsent packet.
1542 QuicAckFrame frame = InitAckFrame(10000);
1543 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001544 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1545 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001546 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001547 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1548 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001549 }
1550
1551 void BlockOnNextWrite() {
1552 writer_->BlockOnNextWrite();
1553 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1554 }
1555
1556 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1557
1558 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1559
1560 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1561 writer_->SetWritePauseTimeDelta(delta);
1562 }
1563
1564 void CongestionBlockWrites() {
1565 EXPECT_CALL(*send_algorithm_, CanSend(_))
1566 .WillRepeatedly(testing::Return(false));
1567 }
1568
1569 void CongestionUnblockWrites() {
1570 EXPECT_CALL(*send_algorithm_, CanSend(_))
1571 .WillRepeatedly(testing::Return(true));
1572 }
1573
1574 void set_perspective(Perspective perspective) {
1575 connection_.set_perspective(perspective);
1576 if (perspective == Perspective::IS_SERVER) {
1577 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001578 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1579 if (GetQuicReloadableFlag(quic_version_negotiated_by_default_at_server)) {
1580 connection_.OnSuccessfulVersionNegotiation();
1581 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001582 }
1583 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001584 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001585 }
1586
1587 void set_packets_between_probes_base(
1588 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001589 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1590 &connection_, packets_between_probes_base,
1591 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001592 }
1593
1594 bool IsDefaultTestConfiguration() {
1595 TestParams p = GetParam();
1596 return p.ack_response == AckResponse::kImmediate &&
1597 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1598 }
1599
fkastenholz5d880a92019-06-21 09:01:56 -07001600 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1601 // Not strictly needed for this test, but is commonly done.
1602 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1603 nullptr);
1604 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1605 writer_->connection_close_frames();
1606 ASSERT_EQ(1u, connection_close_frames.size());
fkastenholz0d6554a2019-08-05 12:20:35 -07001607 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1608 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1609 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1610 connection_close_frames[0].close_type);
1611 return;
1612 }
1613
1614 QuicErrorCodeToIetfMapping mapping =
1615 QuicErrorCodeToTransportErrorCode(expected_code);
1616
1617 if (mapping.is_transport_close_) {
1618 // This Google QUIC Error Code maps to a transport close,
1619 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1620 connection_close_frames[0].close_type);
1621 EXPECT_EQ(mapping.transport_error_code_,
1622 connection_close_frames[0].transport_error_code);
1623 // TODO(fkastenholz): when the extracted error code CL lands,
1624 // need to test that extracted==expected.
1625 } else {
1626 // This maps to an application close.
1627 EXPECT_EQ(expected_code, connection_close_frames[0].quic_error_code);
1628 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1629 connection_close_frames[0].close_type);
1630 // TODO(fkastenholz): when the extracted error code CL lands,
1631 // need to test that extracted==expected.
1632 }
fkastenholz5d880a92019-06-21 09:01:56 -07001633 }
1634
wub031d47c2019-11-21 08:04:07 -08001635 void MtuDiscoveryTestInit() {
1636 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001637 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1638 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1639 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1640 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1641 // across all encrypters. The initial encrypter used with IETF QUIC has a
1642 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1643 // 12-byte overhead. This test tests behavior that relies on computing the
1644 // packet size correctly, so by unsetting the initial encrypter, we avoid
1645 // having a mismatch between the overheads for the encrypters used. In
1646 // non-test scenarios all encrypters used for a given connection have the
1647 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1648 // bytes for ones using TLS.
1649 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
1650 EXPECT_TRUE(connection_.connected());
1651 }
1652
QUICHE teama6ef0a62019-03-07 20:34:33 -05001653 QuicConnectionId connection_id_;
1654 QuicFramer framer_;
1655
1656 MockSendAlgorithm* send_algorithm_;
1657 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1658 MockClock clock_;
1659 MockRandom random_generator_;
1660 SimpleBufferAllocator buffer_allocator_;
1661 std::unique_ptr<TestConnectionHelper> helper_;
1662 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1663 QuicFramer peer_framer_;
1664 QuicPacketCreator peer_creator_;
1665 std::unique_ptr<TestPacketWriter> writer_;
1666 TestConnection connection_;
1667 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001668 QuicSentPacketManager* manager_;
1669 StrictMock<MockQuicConnectionVisitor> visitor_;
1670
1671 QuicStreamFrame frame1_;
1672 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001673 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001674 QuicAckFrame ack_;
1675 QuicStopWaitingFrame stop_waiting_;
1676 QuicPacketNumberLength packet_number_length_;
1677 QuicConnectionIdIncluded connection_id_included_;
1678
1679 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001680
1681 QuicConnectionCloseFrame saved_connection_close_frame_;
1682 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001683};
1684
1685// Run all end to end tests with all supported versions.
1686INSTANTIATE_TEST_SUITE_P(SupportedVersion,
1687 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001688 ::testing::ValuesIn(GetTestParams()),
1689 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001690
fkastenholz0d6554a2019-08-05 12:20:35 -07001691// These two tests ensure that the QuicErrorCode mapping works correctly.
1692// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1693// If running IETF QUIC, the first will generate a transport connection
1694// close, the second an application connection close.
1695// The connection close codes for the two tests are manually chosen;
1696// they are expected to always map to transport- and application-
1697// closes, respectively. If that changes, mew codes should be chosen.
1698TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1699 EXPECT_TRUE(connection_.connected());
1700 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1701 connection_.CloseConnection(
1702 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1703 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1704 EXPECT_FALSE(connection_.connected());
1705 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1706}
1707
1708// Test that the IETF QUIC Error code mapping function works
1709// properly for application connection close codes.
1710TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1711 EXPECT_TRUE(connection_.connected());
1712 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1713 connection_.CloseConnection(
1714 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1715 "Should be application close",
1716 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1717 EXPECT_FALSE(connection_.connected());
1718 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1719}
1720
QUICHE teama6ef0a62019-03-07 20:34:33 -05001721TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1722 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1723
1724 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1725 EXPECT_TRUE(connection_.connected());
1726
nharper46833c32019-05-15 21:33:05 -07001727 QuicFrame frame;
1728 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1729 frame = QuicFrame(&crypto_frame_);
1730 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1731 } else {
1732 frame = QuicFrame(QuicStreamFrame(
1733 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001734 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001735 EXPECT_CALL(visitor_, OnStreamFrame(_));
1736 }
1737 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001738 // Cause change in self_address.
1739 QuicIpAddress host;
1740 host.FromString("1.1.1.1");
1741 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001742 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1743 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1744 } else {
1745 EXPECT_CALL(visitor_, OnStreamFrame(_));
1746 }
1747 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001748 EXPECT_TRUE(connection_.connected());
1749}
1750
1751TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001752 set_perspective(Perspective::IS_SERVER);
1753 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1754
1755 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1756 EXPECT_TRUE(connection_.connected());
1757
nharper46833c32019-05-15 21:33:05 -07001758 QuicFrame frame;
1759 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1760 frame = QuicFrame(&crypto_frame_);
1761 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1762 } else {
1763 frame = QuicFrame(QuicStreamFrame(
1764 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001765 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001766 EXPECT_CALL(visitor_, OnStreamFrame(_));
1767 }
1768 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001769 // Cause change in self_address.
1770 QuicIpAddress host;
1771 host.FromString("1.1.1.1");
1772 QuicSocketAddress self_address(host, 123);
1773 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001774 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
nharper46833c32019-05-15 21:33:05 -07001775 ProcessFramePacketWithAddresses(frame, self_address, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001776 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001777 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001778}
1779
1780TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001781 set_perspective(Perspective::IS_SERVER);
1782 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1783
1784 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1785 EXPECT_TRUE(connection_.connected());
1786
nharper46833c32019-05-15 21:33:05 -07001787 QuicFrame frame;
1788 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1789 frame = QuicFrame(&crypto_frame_);
1790 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1791 } else {
1792 frame = QuicFrame(QuicStreamFrame(
1793 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001794 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001795 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1796 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001797 QuicIpAddress host;
1798 host.FromString("1.1.1.1");
1799 QuicSocketAddress self_address1(host, 443);
nharper46833c32019-05-15 21:33:05 -07001800 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001801 // Cause self_address change to mapped Ipv4 address.
1802 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001803 host2.FromString(quiche::QuicheStrCat(
1804 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001805 QuicSocketAddress self_address2(host2, connection_.self_address().port());
nharper46833c32019-05-15 21:33:05 -07001806 ProcessFramePacketWithAddresses(frame, self_address2, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001807 EXPECT_TRUE(connection_.connected());
1808 // self_address change back to Ipv4 address.
nharper46833c32019-05-15 21:33:05 -07001809 ProcessFramePacketWithAddresses(frame, self_address1, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001810 EXPECT_TRUE(connection_.connected());
1811}
1812
1813TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001814 set_perspective(Perspective::IS_SERVER);
1815 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1816
1817 // Clear direct_peer_address.
1818 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1819 // Clear effective_peer_address, it is the same as direct_peer_address for
1820 // this test.
1821 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1822 QuicSocketAddress());
1823
nharper46833c32019-05-15 21:33:05 -07001824 QuicFrame frame;
1825 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1826 frame = QuicFrame(&crypto_frame_);
1827 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1828 } else {
1829 frame = QuicFrame(QuicStreamFrame(
1830 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001831 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001832 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1833 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001834 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001835 const QuicSocketAddress kNewPeerAddress =
1836 QuicSocketAddress(QuicIpAddress::Loopback6(),
1837 /*port=*/23456);
nharper46833c32019-05-15 21:33:05 -07001838 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001839 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1840 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1841
1842 // Decrease packet number to simulate out-of-order packets.
1843 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1844 // This is an old packet, do not migrate.
1845 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07001846 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001847 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1848 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1849}
1850
1851TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001852 set_perspective(Perspective::IS_SERVER);
1853 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1854 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1855
1856 // Clear direct_peer_address.
1857 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1858 // Clear effective_peer_address, it is the same as direct_peer_address for
1859 // this test.
1860 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1861 QuicSocketAddress());
1862 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1863
nharper46833c32019-05-15 21:33:05 -07001864 QuicFrame frame;
1865 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1866 frame = QuicFrame(&crypto_frame_);
1867 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1868 } else {
1869 frame = QuicFrame(QuicStreamFrame(
1870 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001871 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001872 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1873 }
1874 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001875 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1876 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1877
1878 // Process another packet with a different peer address on server side will
1879 // start connection migration.
1880 const QuicSocketAddress kNewPeerAddress =
1881 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1882 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001883 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001884 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1885 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1886}
1887
1888TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001889 set_perspective(Perspective::IS_SERVER);
1890 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1891 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1892
1893 // Clear direct_peer_address.
1894 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1895 // Clear effective_peer_address, it is different from direct_peer_address for
1896 // this test.
1897 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1898 QuicSocketAddress());
1899 const QuicSocketAddress kEffectivePeerAddress =
1900 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1901 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1902
nharper46833c32019-05-15 21:33:05 -07001903 QuicFrame frame;
1904 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1905 frame = QuicFrame(&crypto_frame_);
1906 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1907 } else {
1908 frame = QuicFrame(QuicStreamFrame(
1909 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001910 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001911 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1912 }
1913 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001914 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1915 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1916
1917 // Process another packet with the same direct peer address and different
1918 // effective peer address on server side will start connection migration.
1919 const QuicSocketAddress kNewEffectivePeerAddress =
1920 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1921 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1922 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001923 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001924 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1925 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1926
1927 // Process another packet with a different direct peer address and the same
1928 // effective peer address on server side will not start connection migration.
1929 const QuicSocketAddress kNewPeerAddress =
1930 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1931 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1932 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1933 // ack_frame is used to complete the migration started by the last packet, we
1934 // need to make sure a new migration does not start after the previous one is
1935 // completed.
1936 QuicAckFrame ack_frame = InitAckFrame(1);
1937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1938 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1939 kNewPeerAddress);
1940 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1941 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1942
1943 // Process another packet with different direct peer address and different
1944 // effective peer address on server side will start connection migration.
1945 const QuicSocketAddress kNewerEffectivePeerAddress =
1946 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
1947 const QuicSocketAddress kFinalPeerAddress =
1948 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
1949 connection_.ReturnEffectivePeerAddressForNextPacket(
1950 kNewerEffectivePeerAddress);
1951 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
nharper46833c32019-05-15 21:33:05 -07001952 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001953 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1954 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
1955 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
1956
1957 // While the previous migration is ongoing, process another packet with the
1958 // same direct peer address and different effective peer address on server
1959 // side will start a new connection migration.
1960 const QuicSocketAddress kNewestEffectivePeerAddress =
1961 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
1962 connection_.ReturnEffectivePeerAddressForNextPacket(
1963 kNewestEffectivePeerAddress);
1964 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1965 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
nharper46833c32019-05-15 21:33:05 -07001966 ProcessFramePacketWithAddresses(frame, kSelfAddress, kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001967 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
1968 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
1969 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1970 connection_.active_effective_peer_migration_type());
1971}
1972
1973TEST_P(QuicConnectionTest, ReceivePaddedPingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001974 set_perspective(Perspective::IS_SERVER);
1975 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1976 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1977
1978 // Clear direct_peer_address.
1979 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1980 // Clear effective_peer_address, it is the same as direct_peer_address for
1981 // this test.
1982 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1983 QuicSocketAddress());
1984 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1985
nharper46833c32019-05-15 21:33:05 -07001986 QuicFrame frame;
1987 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1988 frame = QuicFrame(&crypto_frame_);
1989 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1990 } else {
1991 frame = QuicFrame(QuicStreamFrame(
1992 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001993 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07001994 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1995 }
1996 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001997 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1998 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1999
2000 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002001 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002002
2003 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2004 // on server side will be ignored.
2005 OwningSerializedPacketPointer probing_packet;
fkastenholz305e1732019-06-18 05:01:22 -07002006 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002007 QuicPathFrameBuffer payload = {
2008 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
2009 probing_packet =
2010 QuicPacketCreatorPeer::SerializePathChallengeConnectivityProbingPacket(
2011 &peer_creator_, &payload);
2012 } else {
2013 probing_packet = QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
2014 &peer_creator_);
2015 }
2016 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2017 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2018 probing_packet->encrypted_length),
2019 clock_.Now()));
2020
2021 uint64_t num_probing_received =
2022 connection_.GetStats().num_connectivity_probing_received;
2023 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2024
2025 EXPECT_EQ(num_probing_received,
2026 connection_.GetStats().num_connectivity_probing_received);
2027 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2028 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2029}
2030
2031TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2032 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002033 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002034 return;
2035 }
2036
2037 set_perspective(Perspective::IS_CLIENT);
2038
2039 BlockOnNextWrite();
2040
2041 QuicStreamId stream_id = 2;
2042 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2043
2044 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2045
2046 writer_->SetWritable();
2047 connection_.SendConnectivityProbingPacket(writer_.get(),
2048 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002049 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2050 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002051}
2052
2053TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2054 // Regression test for b/74073386.
2055 {
2056 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002057 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2058 .Times(AtLeast(1));
2059 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002060 }
2061
2062 set_perspective(Perspective::IS_CLIENT);
2063
2064 writer_->SimulateNextPacketTooLarge();
2065
2066 // This packet write should fail, which should cause the connection to close
2067 // after sending a connection close packet, then the failed packet should be
2068 // queued.
2069 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2070
2071 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002072 // No need to buffer packets.
2073 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002074
2075 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2076 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002077 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002078}
2079
2080TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002081 set_perspective(Perspective::IS_SERVER);
2082 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2083 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2084
2085 // Clear direct_peer_address.
2086 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2087 // Clear effective_peer_address, it is the same as direct_peer_address for
2088 // this test.
2089 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2090 QuicSocketAddress());
2091 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2092
nharper46833c32019-05-15 21:33:05 -07002093 QuicFrame frame;
2094 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2095 frame = QuicFrame(&crypto_frame_);
2096 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2097 } else {
2098 frame = QuicFrame(QuicStreamFrame(
2099 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002100 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002101 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2102 }
2103 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002104 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2105 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2106
2107 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002108 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109
2110 // Process a padded PING packet from a new peer address on server side
2111 // is effectively receiving a connectivity probing.
2112 const QuicSocketAddress kNewPeerAddress =
2113 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2114
2115 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2116 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2117 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2118 probing_packet->encrypted_length),
2119 clock_.Now()));
2120
2121 uint64_t num_probing_received =
2122 connection_.GetStats().num_connectivity_probing_received;
2123 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2124
2125 EXPECT_EQ(num_probing_received + 1,
2126 connection_.GetStats().num_connectivity_probing_received);
2127 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2128 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2129
2130 // Process another packet with the old peer address on server side will not
2131 // start peer migration.
2132 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002133 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002134 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2135 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2136}
2137
2138TEST_P(QuicConnectionTest, ReceiveReorderedConnectivityProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002139 set_perspective(Perspective::IS_SERVER);
2140 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2141 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2142
2143 // Clear direct_peer_address.
2144 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2145 // Clear effective_peer_address, it is the same as direct_peer_address for
2146 // this test.
2147 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2148 QuicSocketAddress());
2149 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2150
nharper46833c32019-05-15 21:33:05 -07002151 QuicFrame frame;
2152 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2153 frame = QuicFrame(&crypto_frame_);
2154 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2155 } else {
2156 frame = QuicFrame(QuicStreamFrame(
2157 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002158 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002159 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2160 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002161 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
nharper46833c32019-05-15 21:33:05 -07002162 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002163 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2164 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2165
2166 // Decrease packet number to simulate out-of-order packets.
2167 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2168
2169 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002170 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002171
2172 // Process a padded PING packet from a new peer address on server side
2173 // is effectively receiving a connectivity probing, even if a newer packet has
2174 // been received before this one.
2175 const QuicSocketAddress kNewPeerAddress =
2176 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2177
2178 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2179 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2180 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2181 probing_packet->encrypted_length),
2182 clock_.Now()));
2183
2184 uint64_t num_probing_received =
2185 connection_.GetStats().num_connectivity_probing_received;
2186 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2187
2188 EXPECT_EQ(num_probing_received + 1,
2189 connection_.GetStats().num_connectivity_probing_received);
2190 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2191 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2192}
2193
2194TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002195 set_perspective(Perspective::IS_SERVER);
2196 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2197 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2198
2199 // Clear direct_peer_address.
2200 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2201 // Clear effective_peer_address, it is the same as direct_peer_address for
2202 // this test.
2203 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2204 QuicSocketAddress());
2205 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2206
nharper46833c32019-05-15 21:33:05 -07002207 QuicFrame frame;
2208 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2209 frame = QuicFrame(&crypto_frame_);
2210 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2211 } else {
2212 frame = QuicFrame(QuicStreamFrame(
2213 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002214 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002215 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2216 }
2217 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002218 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2219 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2220
2221 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002222 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002223
2224 // Process a padded PING packet from a new peer address on server side
2225 // is effectively receiving a connectivity probing.
2226 const QuicSocketAddress kNewPeerAddress =
2227 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2228
2229 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2230 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2231 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2232 probing_packet->encrypted_length),
2233 clock_.Now()));
2234 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2235 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2236 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2237
2238 // Process another non-probing packet with the new peer address on server
2239 // side will start peer migration.
2240 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2241
nharper46833c32019-05-15 21:33:05 -07002242 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002243 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2244 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2245}
2246
2247TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2248 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2249 set_perspective(Perspective::IS_CLIENT);
2250 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2251
2252 // Clear direct_peer_address.
2253 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2254 // Clear effective_peer_address, it is the same as direct_peer_address for
2255 // this test.
2256 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2257 QuicSocketAddress());
2258 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2259
nharper46833c32019-05-15 21:33:05 -07002260 QuicFrame frame;
2261 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2262 frame = QuicFrame(&crypto_frame_);
2263 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2264 } else {
2265 frame = QuicFrame(QuicStreamFrame(
2266 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002267 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002268 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2269 }
2270 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002271 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2272 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2273
2274 // Client takes all padded PING packet as speculative connectivity
2275 // probing packet, and reports to visitor.
2276 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002277 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002278
2279 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2280 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2281 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2282 probing_packet->encrypted_length),
2283 clock_.Now()));
2284 uint64_t num_probing_received =
2285 connection_.GetStats().num_connectivity_probing_received;
2286 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2287
2288 EXPECT_EQ(num_probing_received,
2289 connection_.GetStats().num_connectivity_probing_received);
2290 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2291 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2292}
2293
2294TEST_P(QuicConnectionTest, ReceiveConnectivityProbingAtClient) {
2295 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2296 set_perspective(Perspective::IS_CLIENT);
2297 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2298
2299 // Clear direct_peer_address.
2300 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2301 // Clear effective_peer_address, it is the same as direct_peer_address for
2302 // this test.
2303 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2304 QuicSocketAddress());
2305 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2306
nharper46833c32019-05-15 21:33:05 -07002307 QuicFrame frame;
2308 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2309 frame = QuicFrame(&crypto_frame_);
2310 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2311 } else {
2312 frame = QuicFrame(QuicStreamFrame(
2313 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002314 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002315 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2316 }
2317 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002318 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2319 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2320
2321 // Process a padded PING packet with a different self address on client side
2322 // is effectively receiving a connectivity probing.
2323 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002324 EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002325
2326 const QuicSocketAddress kNewSelfAddress =
2327 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2328
2329 OwningSerializedPacketPointer probing_packet = ConstructProbingPacket();
2330 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2331 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2332 probing_packet->encrypted_length),
2333 clock_.Now()));
2334 uint64_t num_probing_received =
2335 connection_.GetStats().num_connectivity_probing_received;
2336 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2337
2338 EXPECT_EQ(num_probing_received + 1,
2339 connection_.GetStats().num_connectivity_probing_received);
2340 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2341 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2342}
2343
2344TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2345 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2346 set_perspective(Perspective::IS_CLIENT);
2347 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2348
2349 // Clear direct_peer_address.
2350 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2351 // Clear effective_peer_address, it is the same as direct_peer_address for
2352 // this test.
2353 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2354 QuicSocketAddress());
2355 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2356
nharper46833c32019-05-15 21:33:05 -07002357 QuicFrame frame;
2358 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2359 frame = QuicFrame(&crypto_frame_);
2360 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2361 } else {
2362 frame = QuicFrame(QuicStreamFrame(
2363 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08002364 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07002365 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2366 }
2367 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002368 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2369 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2370
2371 // Process another packet with a different peer address on client side will
2372 // only update peer address.
2373 const QuicSocketAddress kNewPeerAddress =
2374 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2375 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
nharper46833c32019-05-15 21:33:05 -07002376 ProcessFramePacketWithAddresses(frame, kSelfAddress, kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002377 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2378 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2379}
2380
2381TEST_P(QuicConnectionTest, MaxPacketSize) {
2382 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2383 EXPECT_EQ(1350u, connection_.max_packet_length());
2384}
2385
dschinazi4ad1f462020-01-16 11:56:52 -08002386TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2387 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2388
2389 // SetFromConfig is always called after construction from InitializeSession.
2390 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2391 constexpr uint32_t kTestMaxPacketSize = 1233u;
2392 QuicConfig config;
2393 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2394 connection_.SetFromConfig(config);
2395
2396 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2397}
2398
vasilvvebc5d0c2020-01-16 15:19:21 -08002399TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2400 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2401
2402 // SetFromConfig is always called after construction from InitializeSession.
2403 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2404 constexpr uint32_t kTestMaxPacketSize = 1450u;
2405 QuicConfig config;
2406 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2407 connection_.SetFromConfig(config);
2408
2409 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2410}
2411
QUICHE teama6ef0a62019-03-07 20:34:33 -05002412TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2413 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2414 alarm_factory_.get(), writer_.get(),
2415 Perspective::IS_SERVER, version());
2416 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2417 EXPECT_EQ(1000u, connection.max_packet_length());
2418}
2419
2420TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002421 set_perspective(Perspective::IS_SERVER);
2422 connection_.SetMaxPacketLength(1000);
2423
2424 QuicPacketHeader header;
2425 header.destination_connection_id = connection_id_;
2426 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002427 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002428
2429 if (QuicVersionHasLongHeaderLengths(
2430 peer_framer_.version().transport_version)) {
2431 header.long_packet_type = INITIAL;
2432 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2433 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2434 }
2435
2436 QuicFrames frames;
2437 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002438 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2439 frames.push_back(QuicFrame(&crypto_frame_));
2440 } else {
2441 frames.push_back(QuicFrame(frame1_));
2442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002443 frames.push_back(QuicFrame(padding));
2444 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002445 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002446 size_t encrypted_length =
2447 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002448 *packet, buffer, kMaxOutgoingPacketSize);
2449 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002450
2451 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002452 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2453 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2454 } else {
2455 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2456 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002457 connection_.ProcessUdpPacket(
2458 kSelfAddress, kPeerAddress,
2459 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2460
dschinazi66dea072019-04-09 11:41:06 -07002461 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002462}
2463
2464TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002465 const QuicByteCount lower_max_packet_size = 1240;
2466 writer_->set_max_packet_size(lower_max_packet_size);
2467 set_perspective(Perspective::IS_SERVER);
2468 connection_.SetMaxPacketLength(1000);
2469 EXPECT_EQ(1000u, connection_.max_packet_length());
2470
2471 QuicPacketHeader header;
2472 header.destination_connection_id = connection_id_;
2473 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002474 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002475
2476 if (QuicVersionHasLongHeaderLengths(
2477 peer_framer_.version().transport_version)) {
2478 header.long_packet_type = INITIAL;
2479 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2480 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2481 }
2482
2483 QuicFrames frames;
2484 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002485 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2486 frames.push_back(QuicFrame(&crypto_frame_));
2487 } else {
2488 frames.push_back(QuicFrame(frame1_));
2489 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002490 frames.push_back(QuicFrame(padding));
2491 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002492 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002493 size_t encrypted_length =
2494 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002495 *packet, buffer, kMaxOutgoingPacketSize);
2496 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002497
2498 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002499 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2500 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2501 } else {
2502 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2503 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002504 connection_.ProcessUdpPacket(
2505 kSelfAddress, kPeerAddress,
2506 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2507
2508 // Here, the limit imposed by the writer is lower than the size of the packet
2509 // received, so the writer max packet size is used.
2510 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2511}
2512
2513TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2514 const QuicByteCount lower_max_packet_size = 1240;
2515 writer_->set_max_packet_size(lower_max_packet_size);
2516
2517 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2518 "Default maximum packet size is too low");
2519 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2520
2521 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2522}
2523
2524TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2525 const QuicConnectionId connection_id = TestConnectionId(17);
2526 const QuicByteCount lower_max_packet_size = 1240;
2527 writer_->set_max_packet_size(lower_max_packet_size);
2528 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2529 alarm_factory_.get(), writer_.get(),
2530 Perspective::IS_CLIENT, version());
2531 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2532 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2533}
2534
2535TEST_P(QuicConnectionTest, PacketsInOrder) {
2536 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2537
2538 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002539 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2540 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002541
2542 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002543 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2544 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002545
2546 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002547 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2548 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002549}
2550
2551TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2552 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2553
2554 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002555 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002556 EXPECT_TRUE(IsMissing(2));
2557 EXPECT_TRUE(IsMissing(1));
2558
2559 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002560 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002561 EXPECT_FALSE(IsMissing(2));
2562 EXPECT_TRUE(IsMissing(1));
2563
2564 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002565 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 EXPECT_FALSE(IsMissing(2));
2567 EXPECT_FALSE(IsMissing(1));
2568}
2569
2570TEST_P(QuicConnectionTest, DuplicatePacket) {
2571 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2572
2573 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002574 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002575 EXPECT_TRUE(IsMissing(2));
2576 EXPECT_TRUE(IsMissing(1));
2577
2578 // Send packet 3 again, but do not set the expectation that
2579 // the visitor OnStreamFrame() will be called.
2580 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002581 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002582 EXPECT_TRUE(IsMissing(2));
2583 EXPECT_TRUE(IsMissing(1));
2584}
2585
2586TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002587 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2588 return;
2589 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002590 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2591
2592 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002593 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002594 EXPECT_TRUE(IsMissing(2));
2595 EXPECT_TRUE(IsMissing(1));
2596
2597 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002598 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002599 EXPECT_TRUE(IsMissing(1));
2600
2601 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002602 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002603 EXPECT_TRUE(IsMissing(1));
2604 EXPECT_TRUE(IsMissing(4));
2605
2606 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2607 // packet the peer will not retransmit. It indicates this by sending 'least
2608 // awaiting' is 4. The connection should then realize 1 will not be
2609 // retransmitted, and will remove it from the missing list.
2610 QuicAckFrame frame = InitAckFrame(1);
2611 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2612 ProcessAckPacket(6, &frame);
2613
2614 // Force an ack to be sent.
2615 SendAckPacketToPeer();
2616 EXPECT_TRUE(IsMissing(4));
2617}
2618
QUICHE teama6ef0a62019-03-07 20:34:33 -05002619TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2620 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2621 if (!IsDefaultTestConfiguration()) {
2622 return;
2623 }
2624
2625 // Process an unencrypted packet from the non-crypto stream.
2626 frame1_.stream_id = 3;
2627 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002628 EXPECT_CALL(visitor_,
2629 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002630 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2631 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002632 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002633}
2634
2635TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2636 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2637
2638 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002639 // Should not cause an ack.
2640 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002641
2642 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002643 // Should ack immediately, since this fills the last hole.
2644 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002645
2646 ProcessPacket(1);
2647 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002648 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002649
2650 ProcessPacket(4);
2651 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002652 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002653}
2654
2655TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2656 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2657
2658 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2659 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2660 EXPECT_EQ(2u, writer_->packets_write_attempts());
2661
2662 QuicAckFrame ack1 = InitAckFrame(1);
2663 QuicAckFrame ack2 = InitAckFrame(2);
2664 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2665 ProcessAckPacket(2, &ack2);
2666 // Should ack immediately since we have missing packets.
2667 EXPECT_EQ(2u, writer_->packets_write_attempts());
2668
2669 ProcessAckPacket(1, &ack1);
2670 // Should not ack an ack filling a missing packet.
2671 EXPECT_EQ(2u, writer_->packets_write_attempts());
2672}
2673
2674TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2675 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2676 QuicPacketNumber original, second;
2677
2678 QuicByteCount packet_size =
2679 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2680 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2681
2682 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2683 // First nack triggers early retransmit.
2684 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002685 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002686 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2687 .WillOnce(SetArgPointee<5>(lost_packets));
2688 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2689 QuicPacketNumber retransmission;
2690 // Packet 1 is short header for IETF QUIC because the encryption level
2691 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002692 EXPECT_CALL(*send_algorithm_,
2693 OnPacketSent(_, _, _,
2694 VersionHasIetfInvariantHeader(
2695 GetParam().version.transport_version)
2696 ? packet_size
2697 : packet_size - kQuicVersionSize,
2698 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002699 .WillOnce(SaveArg<2>(&retransmission));
2700
2701 ProcessAckPacket(&frame);
2702
2703 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2704 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2705 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2706 ProcessAckPacket(&frame2);
2707
2708 // Now if the peer sends an ack which still reports the retransmitted packet
2709 // as missing, that will bundle an ack with data after two acks in a row
2710 // indicate the high water mark needs to be raised.
2711 EXPECT_CALL(*send_algorithm_,
2712 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2713 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2714 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002715 size_t padding_frame_count = writer_->padding_frames().size();
2716 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002717 EXPECT_EQ(1u, writer_->stream_frames().size());
2718
2719 // No more packet loss for the rest of the test.
2720 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2721 .Times(AnyNumber());
2722 ProcessAckPacket(&frame2);
2723 EXPECT_CALL(*send_algorithm_,
2724 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002725 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002726 // Ack bundled.
2727 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002728 // Do not ACK acks.
2729 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002730 } else {
2731 EXPECT_EQ(3u, writer_->frame_count());
2732 }
2733 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002734 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002735 EXPECT_TRUE(writer_->ack_frames().empty());
2736 } else {
2737 EXPECT_FALSE(writer_->ack_frames().empty());
2738 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002739
2740 // But an ack with no missing packets will not send an ack.
2741 AckPacket(original, &frame2);
2742 ProcessAckPacket(&frame2);
2743 ProcessAckPacket(&frame2);
2744}
2745
2746TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2747 connection_.set_ack_frequency_before_ack_decimation(3);
2748
2749 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2750 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2751
2752 // Expect 13 acks, every 3rd packet.
2753 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2754 // Receives packets 1 - 39.
2755 for (size_t i = 1; i <= 39; ++i) {
2756 ProcessDataPacket(i);
2757 }
2758}
2759
2760TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2761 const size_t kMinRttMs = 40;
2762 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2763 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2764 QuicTime::Delta::Zero(), QuicTime::Zero());
2765 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2766
2767 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2768
2769 // Start ack decimation from 10th packet.
2770 connection_.set_min_received_before_ack_decimation(10);
2771
2772 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2773 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2774
2775 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2776 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2777 // Receives packets 1 - 29.
2778 for (size_t i = 1; i <= 29; ++i) {
2779 ProcessDataPacket(i);
2780 }
2781
2782 // We now receive the 30th packet, and so we send an ack.
2783 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2784 ProcessDataPacket(30);
2785}
2786
2787TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002788 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002789 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2790 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2791
2792 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2793 // Receives packets 1 - 39.
2794 for (size_t i = 1; i <= 39; ++i) {
2795 ProcessDataPacket(i);
2796 }
2797 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2798 // WINDOW_UPDATE.
2799 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2800 .WillOnce(Invoke([this]() {
2801 connection_.SendControlFrame(
2802 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2803 }));
2804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2805 EXPECT_EQ(0u, writer_->window_update_frames().size());
2806 ProcessDataPacket(40);
2807 EXPECT_EQ(1u, writer_->window_update_frames().size());
2808
2809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
2810 // Receives packets 41 - 59.
2811 for (size_t i = 41; i <= 59; ++i) {
2812 ProcessDataPacket(i);
2813 }
2814 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07002815 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07002816 QuicUtils::GetFirstBidirectionalStreamId(
2817 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07002818 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819
2820 // Session will not be informed until receiving another 20 packets.
2821 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2822 for (size_t i = 60; i <= 98; ++i) {
2823 ProcessDataPacket(i);
2824 EXPECT_EQ(0u, writer_->window_update_frames().size());
2825 }
2826 // Session does not add a retransmittable frame.
2827 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2828 .WillOnce(Invoke([this]() {
2829 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
2830 }));
2831 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2832 EXPECT_EQ(0u, writer_->ping_frames().size());
2833 ProcessDataPacket(99);
2834 EXPECT_EQ(0u, writer_->window_update_frames().size());
2835 // A ping frame will be added.
2836 EXPECT_EQ(1u, writer_->ping_frames().size());
2837}
2838
2839TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07002840 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002841 return;
2842 }
2843 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2844
2845 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2846 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2847 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2848
2849 // Start out saying the least unacked is 2.
2850 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
2851 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
2852
2853 // Change it to 1, but lower the packet number to fake out-of-order packets.
2854 // This should be fine.
2855 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
2856 // The scheduler will not process out of order acks, but all packet processing
2857 // causes the connection to try to write.
2858 if (!GetParam().no_stop_waiting) {
2859 EXPECT_CALL(visitor_, OnCanWrite());
2860 }
2861 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
2862
2863 // Now claim it's one, but set the ordering so it was sent "after" the first
2864 // one. This should cause a connection error.
2865 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
2866 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07002867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2868 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002869 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07002870 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
2871 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002872 }
2873 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07002874 if (!GetParam().no_stop_waiting) {
2875 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
2876 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002877}
2878
2879TEST_P(QuicConnectionTest, TooManySentPackets) {
2880 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2881
2882 QuicPacketCount max_tracked_packets = 50;
2883 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
2884
2885 const int num_packets = max_tracked_packets + 5;
2886
2887 for (int i = 0; i < num_packets; ++i) {
2888 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
2889 }
2890
2891 // Ack packet 1, which leaves more than the limit outstanding.
2892 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2893 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07002894 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002895
2896 // Nack the first packet and ack the rest, leaving a huge gap.
2897 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
2898 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07002899 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002900}
2901
2902TEST_P(QuicConnectionTest, LargestObservedLower) {
2903 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2904
2905 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2906 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2907 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
2908 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2909
2910 // Start out saying the largest observed is 2.
2911 QuicAckFrame frame1 = InitAckFrame(1);
2912 QuicAckFrame frame2 = InitAckFrame(2);
2913 ProcessAckPacket(&frame2);
2914
fayang745c93a2019-06-21 13:43:04 -07002915 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 ProcessAckPacket(&frame1);
2917}
2918
2919TEST_P(QuicConnectionTest, AckUnsentData) {
2920 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07002921 EXPECT_CALL(visitor_,
2922 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002923 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07002924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002925 QuicAckFrame frame = InitAckFrame(1);
2926 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
2927 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07002928 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002929}
2930
2931TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07002932 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2933 return;
2934 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002935 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2936 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2937 ProcessDataPacket(1);
2938 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
2939 QuicPacketNumber last_packet;
2940 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
2941 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
2942 SendAckPacketToPeer(); // Packet 2
2943
2944 if (GetParam().no_stop_waiting) {
2945 // Expect no stop waiting frame is sent.
2946 EXPECT_FALSE(least_unacked().IsInitialized());
2947 } else {
2948 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2949 }
2950
2951 SendAckPacketToPeer(); // Packet 3
2952 if (GetParam().no_stop_waiting) {
2953 // Expect no stop waiting frame is sent.
2954 EXPECT_FALSE(least_unacked().IsInitialized());
2955 } else {
2956 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2957 }
2958
2959 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
2960 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
2961 SendAckPacketToPeer(); // Packet 5
2962 if (GetParam().no_stop_waiting) {
2963 // Expect no stop waiting frame is sent.
2964 EXPECT_FALSE(least_unacked().IsInitialized());
2965 } else {
2966 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
2967 }
2968
2969 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2970
2971 // Peer acks up to packet 3.
2972 QuicAckFrame frame = InitAckFrame(3);
2973 ProcessAckPacket(&frame);
2974 SendAckPacketToPeer(); // Packet 6
2975
2976 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
2977 // ack for 4.
2978 if (GetParam().no_stop_waiting) {
2979 // Expect no stop waiting frame is sent.
2980 EXPECT_FALSE(least_unacked().IsInitialized());
2981 } else {
2982 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
2983 }
2984
2985 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2986
2987 // Peer acks up to packet 4, the last packet.
2988 QuicAckFrame frame2 = InitAckFrame(6);
2989 ProcessAckPacket(&frame2); // Acks don't instigate acks.
2990
2991 // Verify that we did not send an ack.
2992 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
2993
2994 // So the last ack has not changed.
2995 if (GetParam().no_stop_waiting) {
2996 // Expect no stop waiting frame is sent.
2997 EXPECT_FALSE(least_unacked().IsInitialized());
2998 } else {
2999 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3000 }
3001
3002 // If we force an ack, we shouldn't change our retransmit state.
3003 SendAckPacketToPeer(); // Packet 7
3004 if (GetParam().no_stop_waiting) {
3005 // Expect no stop waiting frame is sent.
3006 EXPECT_FALSE(least_unacked().IsInitialized());
3007 } else {
3008 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3009 }
3010
3011 // But if we send more data it should.
3012 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3013 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3014 SendAckPacketToPeer(); // Packet 9
3015 if (GetParam().no_stop_waiting) {
3016 // Expect no stop waiting frame is sent.
3017 EXPECT_FALSE(least_unacked().IsInitialized());
3018 } else {
3019 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3020 }
3021}
3022
3023// QuicConnection should record the packet sent-time prior to sending the
3024// packet.
3025TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3026 // We're using a MockClock for the tests, so we have complete control over the
3027 // time.
3028 // Our recorded timestamp for the last packet sent time will be passed in to
3029 // the send_algorithm. Make sure that it is set to the correct value.
3030 QuicTime actual_recorded_send_time = QuicTime::Zero();
3031 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3032 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3033
3034 // First send without any pause and check the result.
3035 QuicTime expected_recorded_send_time = clock_.Now();
3036 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3037 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3038 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3039 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3040
3041 // Now pause during the write, and check the results.
3042 actual_recorded_send_time = QuicTime::Zero();
3043 const QuicTime::Delta write_pause_time_delta =
3044 QuicTime::Delta::FromMilliseconds(5000);
3045 SetWritePauseTimeDelta(write_pause_time_delta);
3046 expected_recorded_send_time = clock_.Now();
3047
3048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3049 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3050 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3051 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3052 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3053 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3054}
3055
3056TEST_P(QuicConnectionTest, FramePacking) {
3057 // Send two stream frames in 1 packet by queueing them.
3058 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3059 {
fayanga4b37b22019-06-18 13:37:47 -07003060 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003061 connection_.SendStreamData3();
3062 connection_.SendStreamData5();
3063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3064 }
3065 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3066 EXPECT_FALSE(connection_.HasQueuedData());
3067
3068 // Parse the last packet and ensure it's an ack and two stream frames from
3069 // two different streams.
3070 if (GetParam().no_stop_waiting) {
3071 EXPECT_EQ(2u, writer_->frame_count());
3072 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3073 } else {
3074 EXPECT_EQ(2u, writer_->frame_count());
3075 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3076 }
3077
3078 EXPECT_TRUE(writer_->ack_frames().empty());
3079
3080 ASSERT_EQ(2u, writer_->stream_frames().size());
3081 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3082 writer_->stream_frames()[0]->stream_id);
3083 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3084 writer_->stream_frames()[1]->stream_id);
3085}
3086
3087TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3088 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3089 // queueing them.
3090 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3091 {
3092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003093 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003094 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003095 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003096 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003097 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003098 }
3099 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3100 EXPECT_FALSE(connection_.HasQueuedData());
3101
3102 // Parse the last packet and ensure it's the crypto stream frame.
3103 EXPECT_EQ(2u, writer_->frame_count());
3104 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003105 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003106 ASSERT_EQ(1u, writer_->stream_frames().size());
3107 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3108 writer_->stream_frames()[0]->stream_id);
3109 } else {
3110 EXPECT_EQ(1u, writer_->crypto_frames().size());
3111 }
3112}
3113
3114TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3115 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3116 // queueing them.
3117 {
3118 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3119 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003120 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003121 connection_.SendCryptoStreamData();
3122 connection_.SendStreamData3();
3123 }
3124 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3125 EXPECT_FALSE(connection_.HasQueuedData());
3126
3127 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003128 size_t padding_frame_count = writer_->padding_frames().size();
3129 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 ASSERT_EQ(1u, writer_->stream_frames().size());
3131 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3132 writer_->stream_frames()[0]->stream_id);
3133}
3134
3135TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3136 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3137 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003138 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3139 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3140 } else {
3141 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3142 }
3143 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3144
QUICHE teama6ef0a62019-03-07 20:34:33 -05003145 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003146 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3147 connection_.SendCryptoDataWithString("foo", 0);
3148 } else {
3149 SendStreamDataToPeer(
3150 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3151 NO_FIN, &last_packet);
3152 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003153 // Verify ack is bundled with outging packet.
3154 EXPECT_FALSE(writer_->ack_frames().empty());
3155
3156 EXPECT_CALL(visitor_, OnCanWrite())
3157 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3158 &connection_, &TestConnection::SendStreamData3)),
3159 IgnoreResult(InvokeWithoutArgs(
3160 &connection_, &TestConnection::SendStreamData5))));
3161
3162 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3163
3164 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3165 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003166 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003167 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003168 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003169 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003170 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003171
3172 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3173 EXPECT_FALSE(connection_.HasQueuedData());
3174
3175 // Parse the last packet and ensure it's an ack and two stream frames from
3176 // two different streams.
3177 if (GetParam().no_stop_waiting) {
3178 EXPECT_EQ(3u, writer_->frame_count());
3179 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3180 } else {
3181 EXPECT_EQ(4u, writer_->frame_count());
3182 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3183 }
3184 EXPECT_FALSE(writer_->ack_frames().empty());
3185 ASSERT_EQ(2u, writer_->stream_frames().size());
3186 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3187 writer_->stream_frames()[0]->stream_id);
3188 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3189 writer_->stream_frames()[1]->stream_id);
3190}
3191
3192TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003193 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003194 // Send data in 1 packet by writing multiple blocks in a single iovector
3195 // using writev.
3196 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3197
3198 char data[] = "ABCDEF";
3199 struct iovec iov[2];
3200 iov[0].iov_base = data;
3201 iov[0].iov_len = 4;
3202 iov[1].iov_base = data + 4;
3203 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003204 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3205 connection_.transport_version(), Perspective::IS_CLIENT);
3206 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003207
3208 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3209 EXPECT_FALSE(connection_.HasQueuedData());
3210
3211 // Parse the last packet and ensure multiple iovector blocks have
3212 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003213 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003214 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003215 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003216 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003217 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003218 EXPECT_EQ("ABCDEF",
3219 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003220}
3221
3222TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003223 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003224 // Try to send two stream frames in 1 packet by using writev.
3225 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3226
3227 BlockOnNextWrite();
3228 char data[] = "ABCDEF";
3229 struct iovec iov[2];
3230 iov[0].iov_base = data;
3231 iov[0].iov_len = 4;
3232 iov[1].iov_base = data + 4;
3233 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003234 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3235 connection_.transport_version(), Perspective::IS_CLIENT);
3236 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003237
3238 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3239 EXPECT_TRUE(connection_.HasQueuedData());
3240
3241 // Unblock the writes and actually send.
3242 writer_->SetWritable();
3243 connection_.OnCanWrite();
3244 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3245
3246 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003247 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003248 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003249 EXPECT_EQ(0u, writer_->padding_frames().size());
3250 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003251}
3252
3253TEST_P(QuicConnectionTest, SendingZeroBytes) {
3254 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3255 // Send a zero byte write with a fin using writev.
3256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003257 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3258 connection_.transport_version(), Perspective::IS_CLIENT);
3259 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003260
3261 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3262 EXPECT_FALSE(connection_.HasQueuedData());
3263
nharper55fa6132019-05-07 19:37:21 -07003264 // Padding frames are added by v99 to ensure a minimum packet size.
3265 size_t extra_padding_frames = 0;
3266 if (GetParam().version.HasHeaderProtection()) {
3267 extra_padding_frames = 1;
3268 }
3269
QUICHE teama6ef0a62019-03-07 20:34:33 -05003270 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003271 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3272 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3273 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003274 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003275 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3276}
3277
3278TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3279 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3280 // Set the ack alarm by processing a ping frame.
3281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3282
3283 // Processs a PING frame.
3284 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3285 // Ensure that this has caused the ACK alarm to be set.
3286 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3287 EXPECT_TRUE(ack_alarm->IsSet());
3288
3289 // Send data and ensure the ack is bundled.
3290 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3291 size_t len = 10000;
3292 std::unique_ptr<char[]> data_array(new char[len]);
3293 memset(data_array.get(), '?', len);
3294 struct iovec iov;
3295 iov.iov_base = data_array.get();
3296 iov.iov_len = len;
3297 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003298 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3299 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003300 EXPECT_EQ(len, consumed.bytes_consumed);
3301 EXPECT_TRUE(consumed.fin_consumed);
3302 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3303 EXPECT_FALSE(connection_.HasQueuedData());
3304
3305 // Parse the last packet and ensure it's one stream frame with a fin.
3306 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003307 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003308 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003309 writer_->stream_frames()[0]->stream_id);
3310 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3311 // Ensure the ack alarm was cancelled when the ack was sent.
3312 EXPECT_FALSE(ack_alarm->IsSet());
3313}
3314
3315TEST_P(QuicConnectionTest, OnCanWrite) {
3316 // Visitor's OnCanWrite will send data, but will have more pending writes.
3317 EXPECT_CALL(visitor_, OnCanWrite())
3318 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3319 &connection_, &TestConnection::SendStreamData3)),
3320 IgnoreResult(InvokeWithoutArgs(
3321 &connection_, &TestConnection::SendStreamData5))));
3322 {
3323 InSequence seq;
3324 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3325 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3326 .WillRepeatedly(Return(false));
3327 }
3328
3329 EXPECT_CALL(*send_algorithm_, CanSend(_))
3330 .WillRepeatedly(testing::Return(true));
3331
3332 connection_.OnCanWrite();
3333
3334 // Parse the last packet and ensure it's the two stream frames from
3335 // two different streams.
3336 EXPECT_EQ(2u, writer_->frame_count());
3337 EXPECT_EQ(2u, writer_->stream_frames().size());
3338 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3339 writer_->stream_frames()[0]->stream_id);
3340 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3341 writer_->stream_frames()[1]->stream_id);
3342}
3343
3344TEST_P(QuicConnectionTest, RetransmitOnNack) {
3345 QuicPacketNumber last_packet;
3346 QuicByteCount second_packet_size;
3347 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3348 second_packet_size =
3349 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3350 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3351
3352 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3353
3354 // Don't lose a packet on an ack, and nothing is retransmitted.
3355 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3356 QuicAckFrame ack_one = InitAckFrame(1);
3357 ProcessAckPacket(&ack_one);
3358
3359 // Lose a packet and ensure it triggers retransmission.
3360 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3361 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003362 lost_packets.push_back(
3363 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003364 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3365 .WillOnce(SetArgPointee<5>(lost_packets));
3366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3367 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3368 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3369 ProcessAckPacket(&nack_two);
3370}
3371
3372TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3373 // Block the connection to queue the packet.
3374 BlockOnNextWrite();
3375
3376 QuicStreamId stream_id = 2;
3377 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3378
3379 // Now that there is a queued packet, reset the stream.
3380 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3381
3382 // Unblock the connection and verify that only the RST_STREAM is sent.
3383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3384 writer_->SetWritable();
3385 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003386 size_t padding_frame_count = writer_->padding_frames().size();
3387 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003388 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3389}
3390
3391TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3392 // Block the connection to queue the packet.
3393 BlockOnNextWrite();
3394
3395 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003396 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003397 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3398
3399 // Now that there is a queued packet, reset the stream.
3400 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3401
3402 // Unblock the connection and verify that the RST_STREAM is sent and the data
3403 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003405 writer_->SetWritable();
3406 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003407 size_t padding_frame_count = writer_->padding_frames().size();
3408 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003409 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3410}
3411
3412TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3413 QuicStreamId stream_id = 2;
3414 QuicPacketNumber last_packet;
3415 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3416 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3417 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3418
3419 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3420 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3421
3422 // Lose a packet and ensure it does not trigger retransmission.
3423 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3424 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3425 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3426 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3427 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3428 ProcessAckPacket(&nack_two);
3429}
3430
3431TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3432 QuicStreamId stream_id = 2;
3433 QuicPacketNumber last_packet;
3434 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3435 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3436 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3437
3438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3439 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3440
3441 // Lose a packet, ensure it triggers retransmission.
3442 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3443 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3444 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003445 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003446 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3447 .WillOnce(SetArgPointee<5>(lost_packets));
3448 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3449 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3450 ProcessAckPacket(&nack_two);
3451}
3452
3453TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3454 QuicStreamId stream_id = 2;
3455 QuicPacketNumber last_packet;
3456 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3457
3458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3459 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3460
3461 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3463 clock_.AdvanceTime(DefaultRetransmissionTime());
3464 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003465 size_t padding_frame_count = writer_->padding_frames().size();
3466 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003467 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3468 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3469}
3470
3471// Ensure that if the only data in flight is non-retransmittable, the
3472// retransmission alarm is not set.
3473TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3474 QuicStreamId stream_id = 2;
3475 QuicPacketNumber last_data_packet;
3476 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3477
3478 // Cancel the stream.
3479 const QuicPacketNumber rst_packet = last_data_packet + 1;
3480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3481 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3482
3483 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3484 // packet, which is no longer retransmittable since the stream was cancelled.
3485 QuicAckFrame nack_stream_data =
3486 ConstructAckFrame(rst_packet, last_data_packet);
3487 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3488 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3489 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3490 ProcessAckPacket(&nack_stream_data);
3491
3492 // Ensure that the data is still in flight, but the retransmission alarm is no
3493 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003494 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003495 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003496}
3497
3498TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3499 connection_.SetMaxTailLossProbes(0);
3500
3501 QuicStreamId stream_id = 2;
3502 QuicPacketNumber last_packet;
3503 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3504
3505 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3506 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3507
3508 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3509 // is sent.
3510 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3511 clock_.AdvanceTime(DefaultRetransmissionTime());
3512 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003513 size_t padding_frame_count = writer_->padding_frames().size();
3514 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003515 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3516 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3517}
3518
3519TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3520 QuicStreamId stream_id = 2;
3521 QuicPacketNumber last_packet;
3522 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3523 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3524 BlockOnNextWrite();
3525 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3526
3527 // Lose a packet which will trigger a pending retransmission.
3528 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3529 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3530 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3531 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3532 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3533 ProcessAckPacket(&ack);
3534
3535 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3536
3537 // Unblock the connection and verify that the RST_STREAM is sent but not the
3538 // second data packet nor a retransmit.
3539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3540 writer_->SetWritable();
3541 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003542 size_t padding_frame_count = writer_->padding_frames().size();
3543 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003544 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003545 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3546}
3547
3548TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3549 QuicStreamId stream_id = 2;
3550 QuicPacketNumber last_packet;
3551 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3552 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3553 BlockOnNextWrite();
3554 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3555
3556 // Lose a packet which will trigger a pending retransmission.
3557 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3559 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003560 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003561 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3562 .WillOnce(SetArgPointee<5>(lost_packets));
3563 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3564 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3565 ProcessAckPacket(&ack);
3566
3567 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3568
3569 // Unblock the connection and verify that the RST_STREAM is sent and the
3570 // second data packet or a retransmit is sent.
3571 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3572 writer_->SetWritable();
3573 connection_.OnCanWrite();
3574 // The RST_STREAM_FRAME is sent after queued packets and pending
3575 // retransmission.
3576 connection_.SendControlFrame(QuicFrame(
3577 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003578 size_t padding_frame_count = writer_->padding_frames().size();
3579 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003580 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3581}
3582
3583TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3584 QuicPacketNumber last_packet;
3585 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3586 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3587 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3588
3589 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3590
3591 // Instigate a loss with an ack.
3592 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3593 // The first nack should trigger a fast retransmission, but we'll be
3594 // write blocked, so the packet will be queued.
3595 BlockOnNextWrite();
3596
3597 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003598 lost_packets.push_back(
3599 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003600 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3601 .WillOnce(SetArgPointee<5>(lost_packets));
3602 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3604 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003605 ProcessAckPacket(&nack_two);
3606 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3607
3608 // Now, ack the previous transmission.
3609 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3610 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3611 QuicAckFrame ack_all = InitAckFrame(3);
3612 ProcessAckPacket(&ack_all);
3613
fayange62e63c2019-12-04 07:16:25 -08003614 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3615 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003616
3617 writer_->SetWritable();
3618 connection_.OnCanWrite();
3619
3620 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3621 // We do not store retransmittable frames of this retransmission.
3622 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3623}
3624
3625TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3626 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3627 QuicPacketNumber original, second;
3628
3629 QuicByteCount packet_size =
3630 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3631 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3632
3633 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3634 // The first nack should retransmit the largest observed packet.
3635 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003636 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003637 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3638 .WillOnce(SetArgPointee<5>(lost_packets));
3639 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3640 // Packet 1 is short header for IETF QUIC because the encryption level
3641 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003642 EXPECT_CALL(*send_algorithm_,
3643 OnPacketSent(_, _, _,
3644 VersionHasIetfInvariantHeader(
3645 GetParam().version.transport_version)
3646 ? packet_size
3647 : packet_size - kQuicVersionSize,
3648 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003649 ProcessAckPacket(&frame);
3650}
3651
3652TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003653 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003654 return;
3655 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003656 connection_.SetMaxTailLossProbes(0);
3657
3658 for (int i = 0; i < 10; ++i) {
3659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3660 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3661 }
3662
3663 // Block the writer and ensure they're queued.
3664 BlockOnNextWrite();
3665 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003666 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003667 connection_.GetRetransmissionAlarm()->Fire();
3668 EXPECT_TRUE(connection_.HasQueuedData());
3669
3670 // Unblock the writer.
3671 writer_->SetWritable();
3672 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3673 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003674 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003675 connection_.GetRetransmissionAlarm()->Fire();
3676 connection_.OnCanWrite();
3677}
3678
3679TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3680 BlockOnNextWrite();
3681 writer_->set_is_write_blocked_data_buffered(true);
3682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3683 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3684 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3685
3686 writer_->SetWritable();
3687 connection_.OnCanWrite();
3688 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3689}
3690
3691TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3693 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003694 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003695 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003696 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003697 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3698
3699 // The second packet should also be queued, in order to ensure packets are
3700 // never sent out of order.
3701 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003703 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3704 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3705
3706 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003707 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003708 connection_.OnCanWrite();
3709 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003710 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003711}
3712
3713TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3714 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3715 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3716 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3717
3718 BlockOnNextWrite();
3719 writer_->set_is_write_blocked_data_buffered(true);
3720 // Simulate the retransmission alarm firing.
3721 clock_.AdvanceTime(DefaultRetransmissionTime());
3722 connection_.GetRetransmissionAlarm()->Fire();
3723
3724 // Ack the sent packet before the callback returns, which happens in
3725 // rare circumstances with write blocked sockets.
3726 QuicAckFrame ack = InitAckFrame(1);
3727 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3728 ProcessAckPacket(&ack);
3729
3730 writer_->SetWritable();
3731 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07003732 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003733 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 2));
3734}
3735
3736TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3737 // Block the connection.
3738 BlockOnNextWrite();
3739 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3740 EXPECT_EQ(1u, writer_->packets_write_attempts());
3741 EXPECT_TRUE(writer_->IsWriteBlocked());
3742
3743 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3744 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3745 connection_.GetSendAlarm()->Fire();
3746 EXPECT_TRUE(writer_->IsWriteBlocked());
3747 EXPECT_EQ(1u, writer_->packets_write_attempts());
3748}
3749
3750TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
3751 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3752
3753 // Block the connection.
3754 BlockOnNextWrite();
3755 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3756 EXPECT_TRUE(writer_->IsWriteBlocked());
3757 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3758 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3759
3760 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3761 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
3762 // here, because they will fire the alarm after QuicConnection::ProcessPacket
3763 // is returned.
3764 const uint64_t received_packet_num = 1;
3765 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07003766 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
3767 std::unique_ptr<QuicPacket> packet(
3768 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07003769 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05003770 size_t encrypted_length =
3771 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07003772 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003773 connection_.ProcessUdpPacket(
3774 kSelfAddress, kPeerAddress,
3775 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
3776
3777 EXPECT_TRUE(writer_->IsWriteBlocked());
3778 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3779}
3780
3781TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
3782 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3783 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3784
3785 // Simulate the case where a shared writer gets blocked by another connection.
3786 writer_->SetWriteBlocked();
3787
3788 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
3789 QuicAckFrame ack1 = InitAckFrame(1);
3790 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3791 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3792 ProcessAckPacket(1, &ack1);
3793}
3794
3795TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
3796 writer_->SetBatchMode(true);
3797 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07003798 // Have to explicitly grab the OnConnectionClosed frame and check
3799 // its parameters because this is a silent connection close and the
3800 // frame is not also transmitted to the peer.
3801 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3802 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003803
3804 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
3805
3806 {
fayanga4b37b22019-06-18 13:37:47 -07003807 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003808 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
3809 ConnectionCloseBehavior::SILENT_CLOSE);
3810
3811 EXPECT_FALSE(connection_.connected());
3812 writer_->SetWriteBlocked();
3813 }
fkastenholz5d880a92019-06-21 09:01:56 -07003814 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08003815 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
3816 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003817}
3818
3819TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
3820 writer_->SetBatchMode(true);
3821 writer_->BlockOnNextFlush();
3822
3823 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
3824 {
fayanga4b37b22019-06-18 13:37:47 -07003825 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003826 // flusher's destructor will call connection_.FlushPackets, which should add
3827 // the connection to the write blocked list.
3828 }
3829}
3830
3831TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
3832 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3833 int offset = 0;
3834 // Send packets 1 to 15.
3835 for (int i = 0; i < 15; ++i) {
3836 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
3837 offset += 3;
3838 }
3839
3840 // Ack 15, nack 1-14.
3841
3842 QuicAckFrame nack =
3843 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
3844
3845 // 14 packets have been NACK'd and lost.
3846 LostPacketVector lost_packets;
3847 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07003848 lost_packets.push_back(
3849 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003850 }
3851 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3852 .WillOnce(SetArgPointee<5>(lost_packets));
3853 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07003854 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003855 ProcessAckPacket(&nack);
3856}
3857
3858// Test sending multiple acks from the connection to the session.
3859TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07003860 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3861 return;
3862 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003863 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3864 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3865 ProcessDataPacket(1);
3866 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3867 QuicPacketNumber last_packet;
3868 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3869 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3870 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
3871 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
3872 SendAckPacketToPeer(); // Packet 3
3873 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
3874 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3875 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
3876 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
3877 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
3878 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
3879
3880 // Client will ack packets 1, 2, [!3], 4, 5.
3881 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3882 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
3883 ProcessAckPacket(&frame1);
3884
3885 // Now the client implicitly acks 3, and explicitly acks 6.
3886 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3887 QuicAckFrame frame2 = InitAckFrame(6);
3888 ProcessAckPacket(&frame2);
3889}
3890
3891TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07003892 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3893 return;
3894 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003895 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3896 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3897 ProcessDataPacket(1);
3898 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3899 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
3900 // From now on, we send acks, so the send algorithm won't mark them pending.
3901 SendAckPacketToPeer(); // Packet 2
3902
3903 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3904 QuicAckFrame frame = InitAckFrame(1);
3905 ProcessAckPacket(&frame);
3906
3907 // Verify that our internal state has least-unacked as 2, because we're still
3908 // waiting for a potential ack for 2.
3909
3910 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
3911
3912 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3913 frame = InitAckFrame(2);
3914 ProcessAckPacket(&frame);
3915 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3916
3917 // When we send an ack, we make sure our least-unacked makes sense. In this
3918 // case since we're not waiting on an ack for 2 and all packets are acked, we
3919 // set it to 3.
3920 SendAckPacketToPeer(); // Packet 3
3921 // Least_unacked remains at 3 until another ack is received.
3922 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
3923 if (GetParam().no_stop_waiting) {
3924 // Expect no stop waiting frame is sent.
3925 EXPECT_FALSE(least_unacked().IsInitialized());
3926 } else {
3927 // Check that the outgoing ack had its packet number as least_unacked.
3928 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
3929 }
3930
3931 // Ack the ack, which updates the rtt and raises the least unacked.
3932 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3933 frame = InitAckFrame(3);
3934 ProcessAckPacket(&frame);
3935
3936 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
3937 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
3938 SendAckPacketToPeer(); // Packet 5
3939 if (GetParam().no_stop_waiting) {
3940 // Expect no stop waiting frame is sent.
3941 EXPECT_FALSE(least_unacked().IsInitialized());
3942 } else {
3943 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3944 }
3945
3946 // Send two data packets at the end, and ensure if the last one is acked,
3947 // the least unacked is raised above the ack packets.
3948 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
3949 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
3950
3951 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3952 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
3953 {QuicPacketNumber(7), QuicPacketNumber(8)}});
3954 ProcessAckPacket(&frame);
3955
3956 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
3957}
3958
3959TEST_P(QuicConnectionTest, TLP) {
3960 connection_.SetMaxTailLossProbes(1);
3961
3962 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3963 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3964 QuicTime retransmission_time =
3965 connection_.GetRetransmissionAlarm()->deadline();
3966 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3967
3968 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
3969 // Simulate the retransmission alarm firing and sending a tlp,
3970 // so send algorithm's OnRetransmissionTimeout is not called.
3971 clock_.AdvanceTime(retransmission_time - clock_.Now());
3972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
3973 connection_.GetRetransmissionAlarm()->Fire();
3974 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
3975 // We do not raise the high water mark yet.
3976 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3977}
3978
zhongyifbb25772019-04-10 16:54:08 -07003979TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07003980 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07003981 return;
3982 }
3983
zhongyifbb25772019-04-10 16:54:08 -07003984 // Set TLPR from QuicConfig.
3985 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3986 QuicConfig config;
3987 QuicTagVector options;
3988 options.push_back(kTLPR);
3989 config.SetConnectionOptionsToSend(options);
3990 connection_.SetFromConfig(config);
3991 connection_.SetMaxTailLossProbes(1);
3992
3993 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
3994 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
3995
3996 QuicTime retransmission_time =
3997 connection_.GetRetransmissionAlarm()->deadline();
3998 EXPECT_NE(QuicTime::Zero(), retransmission_time);
3999 QuicTime::Delta expected_tlp_delay =
4000 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4001 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4002
4003 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4004 // Simulate firing of the retransmission alarm and retransmit the packet.
4005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4006 clock_.AdvanceTime(retransmission_time - clock_.Now());
4007 connection_.GetRetransmissionAlarm()->Fire();
4008 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4009
4010 // We do not raise the high water mark yet.
4011 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4012}
4013
4014TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004015 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004016 return;
4017 }
4018
zhongyifbb25772019-04-10 16:54:08 -07004019 // Set TLPR from QuicConfig.
4020 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4021 QuicConfig config;
4022 QuicTagVector options;
4023 options.push_back(kTLPR);
4024 config.SetConnectionOptionsToSend(options);
4025 connection_.SetFromConfig(config);
4026 connection_.SetMaxTailLossProbes(1);
4027
4028 // Sets retransmittable on wire.
4029 const QuicTime::Delta retransmittable_on_wire_timeout =
4030 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004031 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004032 retransmittable_on_wire_timeout);
4033
4034 EXPECT_TRUE(connection_.connected());
4035 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4036 .WillRepeatedly(Return(true));
4037 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4038 EXPECT_FALSE(connection_.IsPathDegrading());
4039 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4040
4041 const char data[] = "data";
4042 size_t data_size = strlen(data);
4043 QuicStreamOffset offset = 0;
4044
4045 // Send a data packet.
4046 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4047 offset += data_size;
4048
4049 // Path degrading alarm should be set when there is a retransmittable packet
4050 // on the wire.
4051 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4052
4053 // Verify the path degrading delay.
4054 // First TLP with stream data.
4055 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4056 QuicTime::Delta expected_delay = 0.5 * srtt;
4057 // Add 1st RTO.
4058 QuicTime::Delta retransmission_delay =
4059 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4060 expected_delay = expected_delay + retransmission_delay;
4061 // Add 2nd RTO.
4062 expected_delay = expected_delay + retransmission_delay * 2;
4063 EXPECT_EQ(expected_delay,
4064 QuicConnectionPeer::GetSentPacketManager(&connection_)
4065 ->GetPathDegradingDelay());
4066 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4067
4068 // The ping alarm is set for the ping timeout, not the shorter
4069 // retransmittable_on_wire_timeout.
4070 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004071 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004072 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4073
4074 // Receive an ACK for the data packet.
4075 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4076 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4077 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4078 QuicAckFrame frame =
4079 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4080 ProcessAckPacket(&frame);
4081
4082 // Path degrading alarm should be cancelled as there is no more
4083 // reretransmittable packets on the wire.
4084 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
4085 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4086 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4087 EXPECT_EQ(retransmittable_on_wire_timeout,
4088 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4089
4090 // Simulate firing of the retransmittable on wire and send a PING.
4091 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4092 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4093 connection_.GetPingAlarm()->Fire();
4094
4095 // The retransmission alarm and the path degrading alarm should be set as
4096 // there is a retransmittable packet (PING) on the wire,
4097 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4098 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
4099
4100 // Verify the retransmission delay.
4101 QuicTime::Delta min_rto_timeout =
4102 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4103 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004104
4105 // First TLP without unacked stream data will no longer use TLPR.
4106 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004107 EXPECT_EQ(expected_delay,
4108 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4109
zhongyi1b2f7832019-06-14 13:31:34 -07004110 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004111 // Add 1st RTO.
4112 retransmission_delay =
4113 std::max(manager_->GetRttStats()->smoothed_rtt() +
4114 4 * manager_->GetRttStats()->mean_deviation(),
4115 min_rto_timeout);
4116 expected_delay = expected_delay + retransmission_delay;
4117 // Add 2nd RTO.
4118 expected_delay = expected_delay + retransmission_delay * 2;
4119 EXPECT_EQ(expected_delay,
4120 QuicConnectionPeer::GetSentPacketManager(&connection_)
4121 ->GetPathDegradingDelay());
4122
4123 // The ping alarm is set for the ping timeout, not the shorter
4124 // retransmittable_on_wire_timeout.
4125 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004126 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004127 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004128
4129 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4130 // This will update the retransmission alarm, verify the retransmission delay
4131 // is correct.
4132 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4133 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4134 ProcessAckPacket(&ack);
4135
4136 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004137 // First TLP without unacked stream data will no longer use TLPR.
4138 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004139 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4140 EXPECT_EQ(expected_delay,
4141 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004142}
4143
QUICHE teama6ef0a62019-03-07 20:34:33 -05004144TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004145 if (connection_.PtoEnabled()) {
4146 return;
4147 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004148 connection_.SetMaxTailLossProbes(0);
4149
4150 QuicTime default_retransmission_time =
4151 clock_.ApproximateNow() + DefaultRetransmissionTime();
4152 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4153 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4154
4155 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4156 EXPECT_EQ(default_retransmission_time,
4157 connection_.GetRetransmissionAlarm()->deadline());
4158 // Simulate the retransmission alarm firing.
4159 clock_.AdvanceTime(DefaultRetransmissionTime());
4160 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4161 connection_.GetRetransmissionAlarm()->Fire();
4162 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4163 // We do not raise the high water mark yet.
4164 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4165}
4166
fayanga29eb242019-07-16 12:25:38 -07004167// Regression test of b/133771183.
4168TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004169 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004170 return;
4171 }
4172 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4173 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4174 connection_.SetMaxTailLossProbes(0);
4175
4176 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4177 // Connection is cwnd limited.
4178 CongestionBlockWrites();
4179 // Stream gets reset.
4180 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4181 // Simulate the retransmission alarm firing.
4182 clock_.AdvanceTime(DefaultRetransmissionTime());
4183 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004185 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004186 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004187
4188 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4189 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004190 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4191 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004192 // Receives packets 1 - 40.
4193 for (size_t i = 1; i <= 40; ++i) {
4194 ProcessDataPacket(i);
4195 }
4196}
4197
QUICHE teama6ef0a62019-03-07 20:34:33 -05004198TEST_P(QuicConnectionTest, RetransmitWithSameEncryptionLevel) {
4199 use_tagging_decrypter();
4200
4201 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4202 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004203 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004204 std::make_unique<TaggingEncrypter>(0x01));
nharper46833c32019-05-15 21:33:05 -07004205 QuicByteCount packet_size;
4206 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4207 .WillOnce(SaveArg<3>(&packet_size));
4208 connection_.SendCryptoDataWithString("foo", 0);
4209 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004210 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4211
4212 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004213 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004214 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4215 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4216 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4217
4218 {
4219 InSequence s;
4220 EXPECT_CALL(*send_algorithm_,
4221 OnPacketSent(_, _, QuicPacketNumber(3), _, _));
4222 EXPECT_CALL(*send_algorithm_,
4223 OnPacketSent(_, _, QuicPacketNumber(4), _, _));
4224 }
4225
4226 // Manually mark both packets for retransmission.
4227 connection_.RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
fayang58f71072019-11-05 08:47:02 -08004228 if (!connection_.version().CanSendCoalescedPackets()) {
4229 // Packet should have been sent with ENCRYPTION_INITIAL.
4230 // If connection can send coalesced packet, both retransmissions will be
4231 // coalesced in the same UDP datagram.
4232 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
4233 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004234
4235 // Packet should have been sent with ENCRYPTION_ZERO_RTT.
4236 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
4237}
4238
4239TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4240 use_tagging_decrypter();
4241 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4242 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004243 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004244 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004245
4246 // Attempt to send a handshake message and have the socket block.
4247 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4248 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004249 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004250 // The packet should be serialized, but not queued.
4251 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4252
4253 // Switch to the new encrypter.
4254 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004255 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004256 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4257
4258 // Now become writeable and flush the packets.
4259 writer_->SetWritable();
4260 EXPECT_CALL(visitor_, OnCanWrite());
4261 connection_.OnCanWrite();
4262 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4263
4264 // Verify that the handshake packet went out at the null encryption.
4265 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4266}
4267
4268TEST_P(QuicConnectionTest,
4269 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4270 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004271 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004272 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004273 connection_.SendCryptoStreamData();
4274
4275 // Simulate the retransmission alarm firing and the socket blocking.
4276 BlockOnNextWrite();
4277 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004278 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004279 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004280 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004281
4282 // Go forward secure.
4283 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004284 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004285 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4286 notifier_.NeuterUnencryptedData();
4287 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004288 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004289
4290 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4291 // Unblock the socket and ensure that no packets are sent.
4292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4293 writer_->SetWritable();
4294 connection_.OnCanWrite();
4295}
4296
4297TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4298 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004299 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004300 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004301 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004302
nharper46833c32019-05-15 21:33:05 -07004303 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004304
4305 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004306 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004307 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4308
4309 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4311
4312 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
4313}
4314
4315TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004316 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4317 return;
4318 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004319 // SetFromConfig is always called after construction from InitializeSession.
4320 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4321 QuicConfig config;
4322 connection_.SetFromConfig(config);
4323 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4324 use_tagging_decrypter();
4325
4326 const uint8_t tag = 0x07;
4327 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004328 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004329
4330 // Process an encrypted packet which can not yet be decrypted which should
4331 // result in the packet being buffered.
4332 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4333
4334 // Transition to the new encryption state and process another encrypted packet
4335 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004336 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004337 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004338 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4339 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004340 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004341 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4342 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4343
4344 // Finally, process a third packet and note that we do not reprocess the
4345 // buffered packet.
4346 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4347 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4348}
4349
4350TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004351 if (connection_.PtoEnabled()) {
4352 return;
4353 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004354 connection_.SetMaxTailLossProbes(0);
4355
4356 QuicByteCount first_packet_size;
4357 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4358 .WillOnce(SaveArg<3>(&first_packet_size));
4359
4360 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4361 QuicByteCount second_packet_size;
4362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4363 .WillOnce(SaveArg<3>(&second_packet_size));
4364 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4365 EXPECT_NE(first_packet_size, second_packet_size);
4366 // Advance the clock by huge time to make sure packets will be retransmitted.
4367 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4368 {
4369 InSequence s;
4370 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4371 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4372 }
4373 connection_.GetRetransmissionAlarm()->Fire();
4374
4375 // Advance again and expect the packets to be sent again in the same order.
4376 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4377 {
4378 InSequence s;
4379 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4380 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4381 }
4382 connection_.GetRetransmissionAlarm()->Fire();
4383}
4384
4385TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004386 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4387 return;
4388 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004389 // SetFromConfig is always called after construction from InitializeSession.
4390 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4391 QuicConfig config;
4392 config.set_max_undecryptable_packets(100);
4393 connection_.SetFromConfig(config);
4394 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4395 use_tagging_decrypter();
4396
4397 const uint8_t tag = 0x07;
4398 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004399 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004400
4401 // Process an encrypted packet which can not yet be decrypted which should
4402 // result in the packet being buffered.
4403 for (uint64_t i = 1; i <= 100; ++i) {
4404 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4405 }
4406
4407 // Transition to the new encryption state and process another encrypted packet
4408 // which should result in the original packets being processed.
4409 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004410 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004411 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004412 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4413 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4414 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004415 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004416
4417 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4418 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4419
4420 // Finally, process a third packet and note that we do not reprocess the
4421 // buffered packet.
4422 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4423 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4424}
4425
4426TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4427 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004428 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004429 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004430 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004431
4432 // Test that RTO is started once we write to the socket.
4433 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004435 connection_.OnCanWrite();
4436 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4437}
4438
4439TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004440 if (connection_.PtoEnabled()) {
4441 return;
4442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004443 connection_.SetMaxTailLossProbes(0);
4444
4445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4447 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4448 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4449 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4450 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004451 EXPECT_EQ(DefaultRetransmissionTime(),
4452 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004453
4454 // Advance the time right before the RTO, then receive an ack for the first
4455 // packet to delay the RTO.
4456 clock_.AdvanceTime(DefaultRetransmissionTime());
4457 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4458 QuicAckFrame ack = InitAckFrame(1);
4459 ProcessAckPacket(&ack);
4460 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4461 // so the RTO has increased to 2 * SRTT.
4462 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004463 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4464 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004465
4466 // Move forward past the original RTO and ensure the RTO is still pending.
4467 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4468
4469 // Ensure the second packet gets retransmitted when it finally fires.
4470 EXPECT_TRUE(retransmission_alarm->IsSet());
4471 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4472 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4473 // Manually cancel the alarm to simulate a real test.
4474 connection_.GetRetransmissionAlarm()->Fire();
4475
4476 // The new retransmitted packet number should set the RTO to a larger value
4477 // than previously.
4478 EXPECT_TRUE(retransmission_alarm->IsSet());
4479 QuicTime next_rto_time = retransmission_alarm->deadline();
4480 QuicTime expected_rto_time =
4481 connection_.sent_packet_manager().GetRetransmissionTime();
4482 EXPECT_EQ(next_rto_time, expected_rto_time);
4483}
4484
4485TEST_P(QuicConnectionTest, TestQueued) {
4486 connection_.SetMaxTailLossProbes(0);
4487
4488 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4489 BlockOnNextWrite();
4490 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4491 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4492
4493 // Unblock the writes and actually send.
4494 writer_->SetWritable();
4495 connection_.OnCanWrite();
4496 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4497}
4498
4499TEST_P(QuicConnectionTest, InitialTimeout) {
4500 EXPECT_TRUE(connection_.connected());
4501 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4502 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4503
4504 // SetFromConfig sets the initial timeouts before negotiation.
4505 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4506 QuicConfig config;
4507 connection_.SetFromConfig(config);
4508 // Subtract a second from the idle timeout on the client side.
4509 QuicTime default_timeout =
4510 clock_.ApproximateNow() +
4511 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4512 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4513
fkastenholz5d880a92019-06-21 09:01:56 -07004514 EXPECT_CALL(visitor_,
4515 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004516 // Simulate the timeout alarm firing.
4517 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4518 connection_.GetTimeoutAlarm()->Fire();
4519
4520 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4521 EXPECT_FALSE(connection_.connected());
4522
4523 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4524 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4525 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4526 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4527 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004528 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004529 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004530}
4531
4532TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4533 EXPECT_TRUE(connection_.connected());
4534 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4535 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4536
4537 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4538 QuicConfig config;
4539 connection_.SetFromConfig(config);
4540 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4541 QuicTime initial_ddl =
4542 clock_.ApproximateNow() +
4543 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4544 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4545 EXPECT_TRUE(connection_.connected());
4546
4547 // Advance the time and send the first packet to the peer.
4548 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(20));
4549 QuicPacketNumber last_packet;
4550 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4551 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4552 // This will be the updated deadline for the connection to idle time out.
4553 QuicTime new_ddl = clock_.ApproximateNow() +
4554 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4555
4556 // Simulate the timeout alarm firing, the connection should not be closed as
4557 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004558 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004559 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4560 clock_.AdvanceTime(delay);
4561 connection_.GetTimeoutAlarm()->Fire();
4562 // Verify the timeout alarm deadline is updated.
4563 EXPECT_TRUE(connection_.connected());
4564 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4565 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4566
4567 // Simulate the timeout alarm firing again, the connection now should be
4568 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004569 EXPECT_CALL(visitor_,
4570 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004571 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4572 connection_.GetTimeoutAlarm()->Fire();
4573 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4574 EXPECT_FALSE(connection_.connected());
4575
4576 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4577 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4578 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4579 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4580 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004581 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004582}
4583
4584TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4585 EXPECT_TRUE(connection_.connected());
4586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4587 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4588
4589 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4590 QuicConfig config;
4591 connection_.SetFromConfig(config);
4592 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4593 QuicTime initial_ddl =
4594 clock_.ApproximateNow() +
4595 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4596 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4597 EXPECT_TRUE(connection_.connected());
4598
4599 // Immediately send the first packet, this is a rare case but test code will
4600 // hit this issue often as MockClock used for tests doesn't move with code
4601 // execution until manually adjusted.
4602 QuicPacketNumber last_packet;
4603 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4604 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4605
4606 // Advance the time and send the second packet to the peer.
4607 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4608 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4609 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4610
zhongyic1cab062019-06-19 12:02:24 -07004611 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004612 EXPECT_CALL(visitor_,
4613 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004614 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4615 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004616
4617 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4618 EXPECT_FALSE(connection_.connected());
4619
4620 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4621 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4622 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4623 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4624 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004625 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004626}
4627
4628TEST_P(QuicConnectionTest, HandshakeTimeout) {
4629 // Use a shorter handshake timeout than idle timeout for this test.
4630 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4631 connection_.SetNetworkTimeouts(timeout, timeout);
4632 EXPECT_TRUE(connection_.connected());
4633 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4634
4635 QuicTime handshake_timeout =
4636 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4637 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4638 EXPECT_TRUE(connection_.connected());
4639
4640 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4641 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004642 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4643 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004644 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4645 QuicAckFrame frame = InitAckFrame(1);
4646 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4647 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4648 ProcessAckPacket(&frame);
4649
4650 // Fire early to verify it wouldn't timeout yet.
4651 connection_.GetTimeoutAlarm()->Fire();
4652 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4653 EXPECT_TRUE(connection_.connected());
4654
4655 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4656
fkastenholz5d880a92019-06-21 09:01:56 -07004657 EXPECT_CALL(visitor_,
4658 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004659 // Simulate the timeout alarm firing.
4660 connection_.GetTimeoutAlarm()->Fire();
4661
4662 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4663 EXPECT_FALSE(connection_.connected());
4664
4665 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
4666 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4667 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4668 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004669 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004670}
4671
4672TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004673 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4674 return;
4675 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004676 EXPECT_TRUE(connection_.connected());
4677 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4678 .WillRepeatedly(Return(true));
4679 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4680
4681 // Advance to 5ms, and send a packet to the peer, which will set
4682 // the ping alarm.
4683 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4684 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4685 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004686 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4687 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004688 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004689 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4690 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004691
4692 // Now recevie an ACK of the previous packet, which will move the
4693 // ping alarm forward.
4694 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4695 QuicAckFrame frame = InitAckFrame(1);
4696 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4697 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4698 ProcessAckPacket(&frame);
4699 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4700 // The ping timer is set slightly less than 15 seconds in the future, because
4701 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004702 EXPECT_EQ(
4703 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4704 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004705
4706 writer_->Reset();
4707 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004708 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004709 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004710 size_t padding_frame_count = writer_->padding_frames().size();
4711 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004712 ASSERT_EQ(1u, writer_->ping_frames().size());
4713 writer_->Reset();
4714
4715 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4716 .WillRepeatedly(Return(false));
4717 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4718 SendAckPacketToPeer();
4719
4720 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4721}
4722
4723TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004724 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4725 return;
4726 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004727 EXPECT_TRUE(connection_.connected());
4728 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4729 .WillRepeatedly(Return(true));
4730 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4731
4732 // Use a reduced ping timeout for this connection.
4733 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4734
4735 // Advance to 5ms, and send a packet to the peer, which will set
4736 // the ping alarm.
4737 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4738 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4739 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004740 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4741 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004742 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004743 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4744 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004745
4746 // Now recevie an ACK of the previous packet, which will move the
4747 // ping alarm forward.
4748 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4749 QuicAckFrame frame = InitAckFrame(1);
4750 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4752 ProcessAckPacket(&frame);
4753 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4754 // The ping timer is set slightly less than 10 seconds in the future, because
4755 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004756 EXPECT_EQ(
4757 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4758 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004759
4760 writer_->Reset();
4761 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4762 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4763 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4764 }));
4765 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004766 size_t padding_frame_count = writer_->padding_frames().size();
4767 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004768 ASSERT_EQ(1u, writer_->ping_frames().size());
4769 writer_->Reset();
4770
4771 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4772 .WillRepeatedly(Return(false));
4773 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4774 SendAckPacketToPeer();
4775
4776 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4777}
4778
4779// Tests whether sending an MTU discovery packet to peer successfully causes the
4780// maximum packet size to increase.
4781TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08004782 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004783
4784 // Send an MTU probe.
4785 const size_t new_mtu = kDefaultMaxPacketSize + 100;
4786 QuicByteCount mtu_probe_size;
4787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4788 .WillOnce(SaveArg<3>(&mtu_probe_size));
4789 connection_.SendMtuDiscoveryPacket(new_mtu);
4790 EXPECT_EQ(new_mtu, mtu_probe_size);
4791 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
4792
4793 // Send more than MTU worth of data. No acknowledgement was received so far,
4794 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07004795 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05004796 QuicByteCount size_before_mtu_change;
4797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4798 .Times(2)
4799 .WillOnce(SaveArg<3>(&size_before_mtu_change))
4800 .WillOnce(Return());
4801 connection_.SendStreamDataWithString(3, data, 0, FIN);
4802 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
4803 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
4804
4805 // Acknowledge all packets so far.
4806 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004807 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4808 ProcessAckPacket(&probe_ack);
4809 EXPECT_EQ(new_mtu, connection_.max_packet_length());
4810
4811 // Send the same data again. Check that it fits into a single packet now.
4812 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4813 connection_.SendStreamDataWithString(3, data, 0, FIN);
4814 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
4815}
4816
4817// Tests whether MTU discovery does not happen when it is not explicitly enabled
4818// by the connection options.
4819TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08004820 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004821
4822 const QuicPacketCount packets_between_probes_base = 10;
4823 set_packets_between_probes_base(packets_between_probes_base);
4824
4825 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
4826 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4827 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4828 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4829 EXPECT_EQ(0u, connection_.mtu_probe_count());
4830 }
4831}
4832
wubf76cf2a2019-10-11 18:49:07 -07004833// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834// first try.
4835TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08004836 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07004837
QUICHE teama6ef0a62019-03-07 20:34:33 -05004838 const QuicPacketCount packets_between_probes_base = 5;
4839 set_packets_between_probes_base(packets_between_probes_base);
4840
wubf76cf2a2019-10-11 18:49:07 -07004841 connection_.EnablePathMtuDiscovery(send_algorithm_);
4842
QUICHE teama6ef0a62019-03-07 20:34:33 -05004843 // Send enough packets so that the next one triggers path MTU discovery.
4844 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4845 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
4846 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4847 }
4848
4849 // Trigger the probe.
4850 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4851 nullptr);
4852 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4853 QuicByteCount probe_size;
4854 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4855 .WillOnce(SaveArg<3>(&probe_size));
4856 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08004857
4858 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
4859 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004860
4861 const QuicPacketNumber probe_packet_number =
4862 FirstSendingPacketNumber() + packets_between_probes_base;
4863 ASSERT_EQ(probe_packet_number, creator_->packet_number());
4864
4865 // Acknowledge all packets sent so far.
4866 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07004867 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4868 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004869 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07004870 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004871 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4872
wubf76cf2a2019-10-11 18:49:07 -07004873 EXPECT_EQ(1u, connection_.mtu_probe_count());
4874
wubf76cf2a2019-10-11 18:49:07 -07004875 QuicStreamOffset stream_offset = packets_between_probes_base;
4876 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
4877 ++num_probes) {
4878 // Send just enough packets without triggering the next probe.
4879 for (QuicPacketCount i = 0;
4880 i < (packets_between_probes_base << num_probes) - 1; ++i) {
4881 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
4882 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4883 }
4884
4885 // Trigger the next probe.
4886 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
4887 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4888 QuicByteCount new_probe_size;
4889 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4890 .WillOnce(SaveArg<3>(&new_probe_size));
4891 connection_.GetMtuDiscoveryAlarm()->Fire();
4892 EXPECT_THAT(new_probe_size,
4893 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
4894 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
4895
4896 // Acknowledge all packets sent so far.
4897 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
4898 ProcessAckPacket(&probe_ack);
4899 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
4900 EXPECT_EQ(0u, connection_.GetBytesInFlight());
4901
4902 probe_size = new_probe_size;
4903 }
4904
4905 // The last probe size should be equal to the target.
4906 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
4907}
4908
4909// Simulate the case where the first attempt to send a probe is write blocked,
4910// and after unblock, the second attempt returns a MSG_TOO_BIG error.
4911TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08004912 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07004913
4914 const QuicPacketCount packets_between_probes_base = 5;
4915 set_packets_between_probes_base(packets_between_probes_base);
4916
4917 connection_.EnablePathMtuDiscovery(send_algorithm_);
4918
4919 // Send enough packets so that the next one triggers path MTU discovery.
4920 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
4921 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004922 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4923 }
4924
wubf76cf2a2019-10-11 18:49:07 -07004925 QuicByteCount original_max_packet_length = connection_.max_packet_length();
4926
4927 // Trigger the probe.
4928 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
4929 nullptr);
4930 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08004931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07004932 BlockOnNextWrite();
4933 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4934 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004935 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07004936 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4937 ASSERT_TRUE(connection_.connected());
4938
4939 writer_->SetWritable();
4940 SimulateNextPacketTooLarge();
4941 connection_.OnCanWrite();
4942 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4943 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
4944 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004945}
4946
4947// Tests whether MTU discovery works correctly when the probes never get
4948// acknowledged.
4949TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08004950 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004951
QUICHE teama6ef0a62019-03-07 20:34:33 -05004952 // Lower the number of probes between packets in order to make the test go
4953 // much faster.
4954 const QuicPacketCount packets_between_probes_base = 5;
4955 set_packets_between_probes_base(packets_between_probes_base);
4956
wubf76cf2a2019-10-11 18:49:07 -07004957 connection_.EnablePathMtuDiscovery(send_algorithm_);
4958
4959 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
4960
4961 EXPECT_EQ(packets_between_probes_base,
4962 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
4963
QUICHE teama6ef0a62019-03-07 20:34:33 -05004964 // This tests sends more packets than strictly necessary to make sure that if
4965 // the connection was to send more discovery packets than needed, those would
4966 // get caught as well.
4967 const QuicPacketCount number_of_packets =
4968 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
4969 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004970 // Called on many acks.
4971 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
4972 .Times(AnyNumber());
4973 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
4974 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
4975 clock_.AdvanceTime(rtt);
4976
4977 // Receive an ACK, which marks all data packets as received, and all MTU
4978 // discovery packets as missing.
4979
4980 QuicAckFrame ack;
4981
4982 if (!mtu_discovery_packets.empty()) {
4983 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
4984 mtu_discovery_packets.end());
4985 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
4986 mtu_discovery_packets.end());
4987 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
4988 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
4989 creator_->packet_number() + 1);
4990 ack.largest_acked = creator_->packet_number();
4991
4992 } else {
4993 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
4994 ack.largest_acked = creator_->packet_number();
4995 }
4996
4997 ProcessAckPacket(&ack);
4998
4999 // Trigger MTU probe if it would be scheduled now.
5000 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5001 continue;
5002 }
5003
5004 // Fire the alarm. The alarm should cause a packet to be sent.
5005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5006 connection_.GetMtuDiscoveryAlarm()->Fire();
5007 // Record the packet number of the MTU discovery packet in order to
5008 // mark it as NACK'd.
5009 mtu_discovery_packets.push_back(creator_->packet_number());
5010 }
5011
5012 // Ensure the number of packets between probes grows exponentially by checking
5013 // it against the closed-form expression for the packet number.
5014 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5015 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5016 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5017 const QuicPacketCount packets_between_probes =
5018 packets_between_probes_base * ((1 << (i + 1)) - 1);
5019 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5020 mtu_discovery_packets[i]);
5021 }
5022
5023 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5024 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5025 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5026}
5027
wubf76cf2a2019-10-11 18:49:07 -07005028// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5029TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005030 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005031
5032 const QuicPacketCount packets_between_probes_base = 5;
5033 set_packets_between_probes_base(packets_between_probes_base);
5034
5035 connection_.EnablePathMtuDiscovery(send_algorithm_);
5036
5037 // Send enough packets so that the next one triggers path MTU discovery.
5038 QuicStreamOffset stream_offset = 0;
5039 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5040 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5041 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5042 }
5043
5044 // Trigger the probe.
5045 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5046 nullptr);
5047 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5048 QuicByteCount probe_size;
5049 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5050 .WillOnce(SaveArg<3>(&probe_size));
5051 connection_.GetMtuDiscoveryAlarm()->Fire();
5052 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5053 kMtuDiscoveryTargetPacketSizeHigh));
5054
5055 const QuicPacketNumber probe_packet_number =
5056 FirstSendingPacketNumber() + packets_between_probes_base;
5057 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5058
5059 // Acknowledge all packets sent so far.
5060 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005061 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5062 .Times(AnyNumber());
5063 ProcessAckPacket(&first_ack);
5064 EXPECT_EQ(probe_size, connection_.max_packet_length());
5065 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5066
5067 EXPECT_EQ(1u, connection_.mtu_probe_count());
5068
5069 // Send just enough packets without triggering the second probe.
5070 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5071 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5072 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5073 }
5074
5075 // Trigger the second probe.
5076 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5077 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5078 QuicByteCount second_probe_size;
5079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5080 .WillOnce(SaveArg<3>(&second_probe_size));
5081 connection_.GetMtuDiscoveryAlarm()->Fire();
5082 EXPECT_THAT(second_probe_size,
5083 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5084 EXPECT_EQ(2u, connection_.mtu_probe_count());
5085
5086 // Acknowledge all packets sent so far, except the second probe.
5087 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5088 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5089 ProcessAckPacket(&first_ack);
5090 EXPECT_EQ(probe_size, connection_.max_packet_length());
5091
5092 // Send just enough packets without triggering the third probe.
5093 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5094 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5095 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5096 }
5097
5098 // Trigger the third probe.
5099 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5100 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5101 QuicByteCount third_probe_size;
5102 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5103 .WillOnce(SaveArg<3>(&third_probe_size));
5104 connection_.GetMtuDiscoveryAlarm()->Fire();
5105 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5106 EXPECT_EQ(3u, connection_.mtu_probe_count());
5107
5108 // Acknowledge all packets sent so far, except the second probe.
5109 QuicAckFrame third_ack =
5110 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5111 ProcessAckPacket(&third_ack);
5112 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5113}
5114
QUICHE teama6ef0a62019-03-07 20:34:33 -05005115// Tests whether MTU discovery works when the writer has a limit on how large a
5116// packet can be.
5117TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005118 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005119
QUICHE teama6ef0a62019-03-07 20:34:33 -05005120 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5121 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005122
5123 const QuicPacketCount packets_between_probes_base = 5;
5124 set_packets_between_probes_base(packets_between_probes_base);
5125
wubf76cf2a2019-10-11 18:49:07 -07005126 connection_.EnablePathMtuDiscovery(send_algorithm_);
5127
QUICHE teama6ef0a62019-03-07 20:34:33 -05005128 // Send enough packets so that the next one triggers path MTU discovery.
5129 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5130 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5131 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5132 }
5133
5134 // Trigger the probe.
5135 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5136 nullptr);
5137 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5138 QuicByteCount probe_size;
5139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5140 .WillOnce(SaveArg<3>(&probe_size));
5141 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005142
5143 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005144
5145 const QuicPacketNumber probe_sequence_number =
5146 FirstSendingPacketNumber() + packets_between_probes_base;
5147 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5148
5149 // Acknowledge all packets sent so far.
5150 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5152 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005153 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005154 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005155 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5156
wubf76cf2a2019-10-11 18:49:07 -07005157 EXPECT_EQ(1u, connection_.mtu_probe_count());
5158
wubf76cf2a2019-10-11 18:49:07 -07005159 QuicStreamOffset stream_offset = packets_between_probes_base;
5160 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5161 ++num_probes) {
5162 // Send just enough packets without triggering the next probe.
5163 for (QuicPacketCount i = 0;
5164 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5165 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5166 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5167 }
5168
5169 // Trigger the next probe.
5170 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5171 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5172 QuicByteCount new_probe_size;
5173 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5174 .WillOnce(SaveArg<3>(&new_probe_size));
5175 connection_.GetMtuDiscoveryAlarm()->Fire();
5176 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5177 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5178
5179 // Acknowledge all packets sent so far.
5180 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5181 ProcessAckPacket(&probe_ack);
5182 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5183 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5184
5185 probe_size = new_probe_size;
5186 }
5187
5188 // The last probe size should be equal to the target.
5189 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005190}
5191
5192// Tests whether MTU discovery works when the writer returns an error despite
5193// advertising higher packet length.
5194TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005195 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005196
5197 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5198 const QuicByteCount initial_mtu = connection_.max_packet_length();
5199 EXPECT_LT(initial_mtu, mtu_limit);
5200 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005201
5202 const QuicPacketCount packets_between_probes_base = 5;
5203 set_packets_between_probes_base(packets_between_probes_base);
5204
wubf76cf2a2019-10-11 18:49:07 -07005205 connection_.EnablePathMtuDiscovery(send_algorithm_);
5206
QUICHE teama6ef0a62019-03-07 20:34:33 -05005207 // Send enough packets so that the next one triggers path MTU discovery.
5208 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5209 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5210 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5211 }
5212
5213 // Trigger the probe.
5214 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5215 nullptr);
5216 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5217 writer_->SimulateNextPacketTooLarge();
5218 connection_.GetMtuDiscoveryAlarm()->Fire();
5219 ASSERT_TRUE(connection_.connected());
5220
5221 // Send more data.
5222 QuicPacketNumber probe_number = creator_->packet_number();
5223 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5224 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5225 connection_.EnsureWritableAndSendStreamData5();
5226 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5227 }
5228
5229 // Acknowledge all packets sent so far, except for the lost probe.
5230 QuicAckFrame probe_ack =
5231 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005232 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5233 ProcessAckPacket(&probe_ack);
5234 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5235
5236 // Send more packets, and ensure that none of them sets the alarm.
5237 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5238 connection_.EnsureWritableAndSendStreamData5();
5239 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5240 }
5241
5242 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5243 EXPECT_EQ(1u, connection_.mtu_probe_count());
5244}
5245
5246TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005247 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005248
QUICHE teama6ef0a62019-03-07 20:34:33 -05005249 const QuicPacketCount packets_between_probes_base = 10;
5250 set_packets_between_probes_base(packets_between_probes_base);
5251
wubf76cf2a2019-10-11 18:49:07 -07005252 connection_.EnablePathMtuDiscovery(send_algorithm_);
5253
QUICHE teama6ef0a62019-03-07 20:34:33 -05005254 // Send enough packets so that the next one triggers path MTU discovery.
5255 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5256 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5257 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5258 }
5259
5260 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5261 nullptr);
5262 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5263
fkastenholz5d880a92019-06-21 09:01:56 -07005264 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005265 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5266 ConnectionCloseBehavior::SILENT_CLOSE);
5267 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5268}
5269
5270TEST_P(QuicConnectionTest, TimeoutAfterSend) {
5271 EXPECT_TRUE(connection_.connected());
5272 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5273 QuicConfig config;
5274 connection_.SetFromConfig(config);
5275 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5276
5277 const QuicTime::Delta initial_idle_timeout =
5278 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5279 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5280 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5281
5282 // When we send a packet, the timeout will change to 5ms +
5283 // kInitialIdleTimeoutSecs.
5284 clock_.AdvanceTime(five_ms);
5285 SendStreamDataToPeer(
5286 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5287 0, FIN, nullptr);
5288 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5289
5290 // Now send more data. This will not move the timeout because
5291 // no data has been received since the previous write.
5292 clock_.AdvanceTime(five_ms);
5293 SendStreamDataToPeer(
5294 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5295 3, FIN, nullptr);
5296 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5297
5298 // The original alarm will fire. We should not time out because we had a
5299 // network event at t=5ms. The alarm will reregister.
5300 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5301 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5302 connection_.GetTimeoutAlarm()->Fire();
5303 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5304 EXPECT_TRUE(connection_.connected());
5305 EXPECT_EQ(default_timeout + five_ms,
5306 connection_.GetTimeoutAlarm()->deadline());
5307
5308 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005309 EXPECT_CALL(visitor_,
5310 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005312 clock_.AdvanceTime(five_ms);
5313 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5314 connection_.GetTimeoutAlarm()->Fire();
5315 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5316 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005317 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005318}
5319
5320TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005321 if (connection_.PtoEnabled()) {
5322 return;
5323 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005324 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5325 EXPECT_TRUE(connection_.connected());
5326 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5327 QuicConfig config;
5328 connection_.SetFromConfig(config);
5329 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5330
5331 const QuicTime start_time = clock_.Now();
5332 const QuicTime::Delta initial_idle_timeout =
5333 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5334 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5335
5336 connection_.SetMaxTailLossProbes(0);
5337 const QuicTime default_retransmission_time =
5338 start_time + DefaultRetransmissionTime();
5339
5340 ASSERT_LT(default_retransmission_time, default_timeout);
5341
5342 // When we send a packet, the timeout will change to 5 ms +
5343 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5344 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5345 const QuicTime send_time = start_time + five_ms;
5346 clock_.AdvanceTime(five_ms);
5347 ASSERT_EQ(send_time, clock_.Now());
5348 SendStreamDataToPeer(
5349 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5350 0, FIN, nullptr);
5351 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5352
5353 // Move forward 5 ms and receive a packet, which will move the timeout
5354 // forward 5 ms more (but will not reschedule the alarm).
5355 const QuicTime receive_time = send_time + five_ms;
5356 clock_.AdvanceTime(receive_time - clock_.Now());
5357 ASSERT_EQ(receive_time, clock_.Now());
5358 ProcessPacket(1);
5359
5360 // Now move forward to the retransmission time and retransmit the
5361 // packet, which should move the timeout forward again (but will not
5362 // reschedule the alarm).
5363 EXPECT_EQ(default_retransmission_time + five_ms,
5364 connection_.GetRetransmissionAlarm()->deadline());
5365 // Simulate the retransmission alarm firing.
5366 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5367 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5368 clock_.AdvanceTime(rto_time - clock_.Now());
5369 ASSERT_EQ(rto_time, clock_.Now());
5370 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5371 connection_.GetRetransmissionAlarm()->Fire();
5372
5373 // Advance to the original timeout and fire the alarm. The connection should
5374 // timeout, and the alarm should be registered based on the time of the
5375 // retransmission.
5376 clock_.AdvanceTime(default_timeout - clock_.Now());
5377 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5378 clock_.Now().ToDebuggingValue());
5379 EXPECT_EQ(default_timeout, clock_.Now());
5380 connection_.GetTimeoutAlarm()->Fire();
5381 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5382 EXPECT_TRUE(connection_.connected());
5383 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5384 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5385
5386 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005387 EXPECT_CALL(visitor_,
5388 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005389 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005390 clock_.AdvanceTime(final_timeout - clock_.Now());
5391 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5392 EXPECT_EQ(final_timeout, clock_.Now());
5393 connection_.GetTimeoutAlarm()->Fire();
5394 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5395 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005396 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005397}
5398
5399TEST_P(QuicConnectionTest, NewTimeoutAfterSendSilentClose) {
5400 // Same test as above, but complete a handshake which enables silent close,
5401 // causing no connection close packet to be sent.
5402 EXPECT_TRUE(connection_.connected());
5403 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5404 QuicConfig config;
5405
5406 // Create a handshake message that also enables silent close.
5407 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005408 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005409 QuicConfig client_config;
5410 client_config.SetInitialStreamFlowControlWindowToSend(
5411 kInitialStreamFlowControlWindowForTest);
5412 client_config.SetInitialSessionFlowControlWindowToSend(
5413 kInitialSessionFlowControlWindowForTest);
5414 client_config.SetIdleNetworkTimeout(
5415 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5416 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005417 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005418 const QuicErrorCode error =
5419 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005420 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005421
5422 connection_.SetFromConfig(config);
5423 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5424
5425 const QuicTime::Delta default_idle_timeout =
5426 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5427 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5428 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5429
5430 // When we send a packet, the timeout will change to 5ms +
5431 // kInitialIdleTimeoutSecs.
5432 clock_.AdvanceTime(five_ms);
5433 SendStreamDataToPeer(
5434 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5435 0, FIN, nullptr);
5436 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5437
5438 // Now send more data. This will not move the timeout because
5439 // no data has been received since the previous write.
5440 clock_.AdvanceTime(five_ms);
5441 SendStreamDataToPeer(
5442 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5443 3, FIN, nullptr);
5444 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5445
5446 // The original alarm will fire. We should not time out because we had a
5447 // network event at t=5ms. The alarm will reregister.
5448 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5449 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5450 connection_.GetTimeoutAlarm()->Fire();
5451 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5452 EXPECT_TRUE(connection_.connected());
5453 EXPECT_EQ(default_timeout + five_ms,
5454 connection_.GetTimeoutAlarm()->deadline());
5455
5456 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005457 // This results in a SILENT_CLOSE, so the writer will not be invoked
5458 // and will not save the frame. Grab the frame from OnConnectionClosed
5459 // directly.
5460 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5461 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5462
QUICHE teama6ef0a62019-03-07 20:34:33 -05005463 clock_.AdvanceTime(five_ms);
5464 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5465 connection_.GetTimeoutAlarm()->Fire();
5466 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5467 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005468 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005469 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5470 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005471}
5472
5473TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005474 if (connection_.PtoEnabled()) {
5475 return;
5476 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005477 // Same test as above, but complete a handshake which enables silent close,
5478 // but sending TLPs causes the connection close to be sent.
5479 EXPECT_TRUE(connection_.connected());
5480 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5481 QuicConfig config;
5482
5483 // Create a handshake message that also enables silent close.
5484 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005485 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005486 QuicConfig client_config;
5487 client_config.SetInitialStreamFlowControlWindowToSend(
5488 kInitialStreamFlowControlWindowForTest);
5489 client_config.SetInitialSessionFlowControlWindowToSend(
5490 kInitialSessionFlowControlWindowForTest);
5491 client_config.SetIdleNetworkTimeout(
5492 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5493 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005494 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005495 const QuicErrorCode error =
5496 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005497 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005498
5499 connection_.SetFromConfig(config);
5500 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5501
5502 const QuicTime::Delta default_idle_timeout =
5503 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5504 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5505 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5506
5507 // When we send a packet, the timeout will change to 5ms +
5508 // kInitialIdleTimeoutSecs.
5509 clock_.AdvanceTime(five_ms);
5510 SendStreamDataToPeer(
5511 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5512 0, FIN, nullptr);
5513 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5514
5515 // Retransmit the packet via tail loss probe.
5516 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5517 clock_.Now());
5518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5519 connection_.GetRetransmissionAlarm()->Fire();
5520
5521 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005522 EXPECT_CALL(visitor_,
5523 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005524 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005525 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5526 clock_.ApproximateNow() + five_ms);
5527 connection_.GetTimeoutAlarm()->Fire();
5528 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5529 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005530 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005531}
5532
5533TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5534 // Same test as above, but complete a handshake which enables silent close,
5535 // but having open streams causes the connection close to be sent.
5536 EXPECT_TRUE(connection_.connected());
5537 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5538 QuicConfig config;
5539
5540 // Create a handshake message that also enables silent close.
5541 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005542 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005543 QuicConfig client_config;
5544 client_config.SetInitialStreamFlowControlWindowToSend(
5545 kInitialStreamFlowControlWindowForTest);
5546 client_config.SetInitialSessionFlowControlWindowToSend(
5547 kInitialSessionFlowControlWindowForTest);
5548 client_config.SetIdleNetworkTimeout(
5549 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
5550 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005551 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005552 const QuicErrorCode error =
5553 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005554 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005555
5556 connection_.SetFromConfig(config);
5557 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5558
5559 const QuicTime::Delta default_idle_timeout =
5560 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
5561 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5562 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5563
5564 // When we send a packet, the timeout will change to 5ms +
5565 // kInitialIdleTimeoutSecs.
5566 clock_.AdvanceTime(five_ms);
5567 SendStreamDataToPeer(
5568 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5569 0, FIN, nullptr);
5570 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5571
5572 // Indicate streams are still open.
5573 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5574 .WillRepeatedly(Return(true));
5575
5576 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005577 EXPECT_CALL(visitor_,
5578 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005580 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5581 clock_.ApproximateNow() + five_ms);
5582 connection_.GetTimeoutAlarm()->Fire();
5583 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5584 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005585 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005586}
5587
5588TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5589 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5590 EXPECT_TRUE(connection_.connected());
5591 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5592 QuicConfig config;
5593 connection_.SetFromConfig(config);
5594 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5595
5596 const QuicTime::Delta initial_idle_timeout =
5597 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5598 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5599 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5600
5601 connection_.SendStreamDataWithString(
5602 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5603 0, NO_FIN);
5604 connection_.SendStreamDataWithString(
5605 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5606 3, NO_FIN);
5607
5608 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5609 clock_.AdvanceTime(five_ms);
5610
5611 // When we receive a packet, the timeout will change to 5ms +
5612 // kInitialIdleTimeoutSecs.
5613 QuicAckFrame ack = InitAckFrame(2);
5614 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5615 ProcessAckPacket(&ack);
5616
5617 // The original alarm will fire. We should not time out because we had a
5618 // network event at t=5ms. The alarm will reregister.
5619 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5620 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5621 connection_.GetTimeoutAlarm()->Fire();
5622 EXPECT_TRUE(connection_.connected());
5623 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5624 EXPECT_EQ(default_timeout + five_ms,
5625 connection_.GetTimeoutAlarm()->deadline());
5626
5627 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005628 EXPECT_CALL(visitor_,
5629 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 clock_.AdvanceTime(five_ms);
5632 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5633 connection_.GetTimeoutAlarm()->Fire();
5634 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5635 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005636 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005637}
5638
5639TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5641 EXPECT_TRUE(connection_.connected());
5642 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5643 QuicConfig config;
5644 connection_.SetFromConfig(config);
5645 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
5646
5647 const QuicTime::Delta initial_idle_timeout =
5648 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5649 connection_.SetNetworkTimeouts(
5650 QuicTime::Delta::Infinite(),
5651 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5652 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5653 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5654
5655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5656 connection_.SendStreamDataWithString(
5657 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5658 0, NO_FIN);
5659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5660 connection_.SendStreamDataWithString(
5661 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5662 3, NO_FIN);
5663
5664 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5665
5666 clock_.AdvanceTime(five_ms);
5667
5668 // When we receive a packet, the timeout will change to 5ms +
5669 // kInitialIdleTimeoutSecs.
5670 QuicAckFrame ack = InitAckFrame(2);
5671 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5672 ProcessAckPacket(&ack);
5673
5674 // The original alarm will fire. We should not time out because we had a
5675 // network event at t=5ms. The alarm will reregister.
5676 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5677 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5678 connection_.GetTimeoutAlarm()->Fire();
5679 EXPECT_TRUE(connection_.connected());
5680 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5681 EXPECT_EQ(default_timeout + five_ms,
5682 connection_.GetTimeoutAlarm()->deadline());
5683
5684 // Now, send packets while advancing the time and verify that the connection
5685 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07005686 EXPECT_CALL(visitor_,
5687 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005688 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5689 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5690 QUIC_LOG(INFO) << "sending data packet";
5691 connection_.SendStreamDataWithString(
5692 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5693 "foo", 0, NO_FIN);
5694 connection_.GetTimeoutAlarm()->Fire();
5695 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5696 }
5697 EXPECT_FALSE(connection_.connected());
5698 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07005699 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005700}
5701
5702TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07005703 if (connection_.PtoEnabled()) {
5704 return;
5705 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005706 connection_.SetMaxTailLossProbes(2);
5707 EXPECT_TRUE(connection_.connected());
5708 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5709 QuicConfig config;
5710 QuicTagVector connection_options;
5711 connection_options.push_back(k5RTO);
5712 config.SetConnectionOptionsToSend(connection_options);
5713 connection_.SetFromConfig(config);
5714
5715 // Send stream data.
5716 SendStreamDataToPeer(
5717 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5718 0, FIN, nullptr);
5719
5720 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
5721 for (int i = 0; i < 6; ++i) {
5722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5723 connection_.GetRetransmissionAlarm()->Fire();
5724 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5725 EXPECT_TRUE(connection_.connected());
5726 }
5727
5728 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
5729 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
5730 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005731 EXPECT_CALL(visitor_,
5732 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005734 connection_.GetRetransmissionAlarm()->Fire();
5735 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5736 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005737 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005738}
5739
5740TEST_P(QuicConnectionTest, SendScheduler) {
5741 // Test that if we send a packet without delay, it is not queued.
5742 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005743 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005744 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005745 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5746 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07005747 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005748 HAS_RETRANSMITTABLE_DATA, false, false);
5749 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5750}
5751
5752TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5753 // Test that the connection does not crash when it fails to send the first
5754 // packet at which point self_address_ might be uninitialized.
5755 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07005756 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07005757 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005758 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005759 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5760 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07005761 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005762 HAS_RETRANSMITTABLE_DATA, false, false);
5763}
5764
5765TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5766 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07005767 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07005768 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005769 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5770 BlockOnNextWrite();
5771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5772 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07005773 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774 HAS_RETRANSMITTABLE_DATA, false, false);
5775 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5776}
5777
5778TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005779 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07005780 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005781 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07005782 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005783 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5784 connection_.version().transport_version, Perspective::IS_CLIENT));
5785 EXPECT_EQ(0u, connection_
5786 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5787 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05005788 .bytes_consumed);
5789 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5790}
5791
ianswett3085da82019-04-04 07:24:24 -07005792TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07005793 // Make the payload twice the size of the packet, so 3 packets are written.
5794 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07005795 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07005796 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5797 connection_.version().transport_version, Perspective::IS_CLIENT));
5798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5799 EXPECT_EQ(payload.size(), connection_
5800 .SendStreamDataWithString(first_bidi_stream_id,
5801 payload, 0, NO_FIN)
5802 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005803}
5804
5805TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
5806 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07005807 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005808 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
5809 // SendStreamDataWithString.
5810 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
5811 }
5812 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07005813 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005814 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
5815
5816 // Now send some packets with no truncation.
5817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5818 EXPECT_EQ(payload.size(),
5819 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
5820 .bytes_consumed);
5821 // Track the size of the second packet here. The overhead will be the largest
5822 // we see in this test, due to the non-truncated connection id.
5823 size_t non_truncated_packet_size = writer_->last_packet_size();
5824
5825 // Change to a 0 byte connection id.
5826 QuicConfig config;
5827 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
5828 connection_.SetFromConfig(config);
5829 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
5830 EXPECT_EQ(payload.size(),
5831 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
5832 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07005833 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005834 // Short header packets sent from server omit connection ID already, and
5835 // stream offset size increases from 0 to 2.
5836 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
5837 } else {
5838 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
5839 // because stream offset size is 2 instead of 0.
5840 EXPECT_EQ(non_truncated_packet_size,
5841 writer_->last_packet_size() + 8 * 2 - 2);
5842 }
5843}
5844
5845TEST_P(QuicConnectionTest, SendDelayedAck) {
5846 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5847 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5848 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5849 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005850 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005851 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005852 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005853 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005854 // Process a packet from the non-crypto stream.
5855 frame1_.stream_id = 3;
5856
5857 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005858 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005859 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5860 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5861
5862 // Check if delayed ack timer is running for the expected interval.
5863 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5864 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5865 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005866 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005867 connection_.GetAckAlarm()->Fire();
5868 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005869 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005870 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005871 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005872 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5873 } else {
nharper55fa6132019-05-07 19:37:21 -07005874 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005875 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5876 }
5877 EXPECT_FALSE(writer_->ack_frames().empty());
5878 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5879}
5880
5881TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
5882 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
5883
5884 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08005885 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005886 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5887 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5888 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005889 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005890 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005891 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005892 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005893 // Process a packet from the non-crypto stream.
5894 frame1_.stream_id = 3;
5895
5896 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005897 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005898 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5899 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5900
5901 // Check if delayed ack timer is running for the expected interval.
5902 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5903 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5904 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005905 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005906 connection_.GetAckAlarm()->Fire();
5907 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005908 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005909 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005910 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005911 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5912 } else {
nharper55fa6132019-05-07 19:37:21 -07005913 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005914 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5915 }
5916 EXPECT_FALSE(writer_->ack_frames().empty());
5917 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5918
5919 // Process another packet immedately after sending the ack and expect the
5920 // ack alarm to be set delayed ack time in the future.
5921 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
5922 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5923 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5924
5925 // Check if delayed ack timer is running for the expected interval.
5926 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5927 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5928 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07005929 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005930 connection_.GetAckAlarm()->Fire();
5931 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07005932 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005933 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07005934 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005935 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
5936 } else {
nharper55fa6132019-05-07 19:37:21 -07005937 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005938 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
5939 }
5940 EXPECT_FALSE(writer_->ack_frames().empty());
5941 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5942
ianswett8f90e512019-12-18 10:50:27 -08005943 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005944 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5945 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
5946 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5947 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5948
5949 // Check if delayed ack timer is running for the expected interval.
5950 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5951 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5952}
5953
5954TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
5955 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
5956 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
5957
5958 const size_t kMinRttMs = 40;
5959 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
5960 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
5961 QuicTime::Delta::Zero(), QuicTime::Zero());
5962 // The ack time should be based on min_rtt/4, since it's less than the
5963 // default delayed ack time.
5964 QuicTime ack_time = clock_.ApproximateNow() +
5965 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
5966 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5967 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5968 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07005969 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005970 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005971 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07005972 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005973 // Process a packet from the non-crypto stream.
5974 frame1_.stream_id = 3;
5975
5976 // Process all the initial packets in order so there aren't missing packets.
5977 uint64_t kFirstDecimatedPacket = 101;
5978 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
5979 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5980 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
5981 }
5982 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
5983 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07005984 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005985 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5986 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
5987 ENCRYPTION_ZERO_RTT);
5988
5989 // Check if delayed ack timer is running for the expected interval.
5990 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5991 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
5992
5993 // The 10th received packet causes an ack to be sent.
5994 for (int i = 0; i < 9; ++i) {
5995 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
5996 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
5997 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
5998 ENCRYPTION_ZERO_RTT);
5999 }
6000 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006001 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006002 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006003 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006004 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6005 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006006 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006007 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6008 }
6009 EXPECT_FALSE(writer_->ack_frames().empty());
6010 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6011}
6012
6013TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6014 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6015 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6016 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6017
6018 const size_t kMinRttMs = 40;
6019 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6020 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6021 QuicTime::Delta::Zero(), QuicTime::Zero());
6022
6023 // The beginning of the connection counts as quiescence.
6024 QuicTime ack_time =
6025 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6026 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6027 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6028 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006029 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006030 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006031 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006032 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006033 // Process a packet from the non-crypto stream.
6034 frame1_.stream_id = 3;
6035
6036 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006037 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006038 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6039 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6040
6041 // Check if delayed ack timer is running for the expected interval.
6042 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6043 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6044 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006045 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006046 connection_.GetAckAlarm()->Fire();
6047 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006048 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006049 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006050 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006051 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6052 } else {
nharper55fa6132019-05-07 19:37:21 -07006053 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006054 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6055 }
6056 EXPECT_FALSE(writer_->ack_frames().empty());
6057 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6058
6059 // Process another packet immedately after sending the ack and expect the
6060 // ack alarm to be set delayed ack time in the future.
6061 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6062 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6063 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6064
6065 // Check if delayed ack timer is running for the expected interval.
6066 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6067 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6068 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006069 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006070 connection_.GetAckAlarm()->Fire();
6071 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006072 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006073 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006074 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006075 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6076 } else {
nharper55fa6132019-05-07 19:37:21 -07006077 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006078 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6079 }
6080 EXPECT_FALSE(writer_->ack_frames().empty());
6081 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6082
6083 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6084 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6085 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6086 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6087 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6088
6089 // Check if delayed ack timer is running for the expected interval.
6090 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6091 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6092
6093 // Process enough packets to get into ack decimation behavior.
6094 // The ack time should be based on min_rtt/4, since it's less than the
6095 // default delayed ack time.
6096 ack_time = clock_.ApproximateNow() +
6097 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6098 uint64_t kFirstDecimatedPacket = 101;
6099 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6100 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6101 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6102 }
6103 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6104 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006105 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006106 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6107 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6108 ENCRYPTION_ZERO_RTT);
6109
6110 // Check if delayed ack timer is running for the expected interval.
6111 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6112 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6113
6114 // The 10th received packet causes an ack to be sent.
6115 for (int i = 0; i < 9; ++i) {
6116 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6117 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6118 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6119 ENCRYPTION_ZERO_RTT);
6120 }
6121 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006122 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006123 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006124 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006125 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6126 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006127 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006128 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6129 }
6130 EXPECT_FALSE(writer_->ack_frames().empty());
6131 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6132
6133 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6134 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6135 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6136 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6137 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6138 ENCRYPTION_ZERO_RTT);
6139
6140 // Check if delayed ack timer is running for the expected interval.
6141 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6142 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6143}
6144
6145TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6146 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6147 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6148 QuicConfig config;
6149 QuicTagVector connection_options;
6150 connection_options.push_back(kACKD);
6151 // No limit on the number of packets received before sending an ack.
6152 connection_options.push_back(kAKDU);
6153 config.SetConnectionOptionsToSend(connection_options);
6154 connection_.SetFromConfig(config);
6155
6156 const size_t kMinRttMs = 40;
6157 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6158 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6159 QuicTime::Delta::Zero(), QuicTime::Zero());
6160 // The ack time should be based on min_rtt/4, since it's less than the
6161 // default delayed ack time.
6162 QuicTime ack_time = clock_.ApproximateNow() +
6163 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6165 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6166 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006167 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006168 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006169 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006170 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006171 // Process a packet from the non-crypto stream.
6172 frame1_.stream_id = 3;
6173
6174 // Process all the initial packets in order so there aren't missing packets.
6175 uint64_t kFirstDecimatedPacket = 101;
6176 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6177 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6178 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6179 }
6180 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6181 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006182 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006183 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6184 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6185 ENCRYPTION_ZERO_RTT);
6186
6187 // Check if delayed ack timer is running for the expected interval.
6188 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6189 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6190
6191 // 18 packets will not cause an ack to be sent. 19 will because when
6192 // stop waiting frames are in use, we ack every 20 packets no matter what.
6193 for (int i = 0; i < 18; ++i) {
6194 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6195 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6196 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6197 ENCRYPTION_ZERO_RTT);
6198 }
6199 // The delayed ack timer should still be set to the expected deadline.
6200 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6201 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6202}
6203
6204TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6205 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6206 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6207 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6208
6209 const size_t kMinRttMs = 40;
6210 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6211 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6212 QuicTime::Delta::Zero(), QuicTime::Zero());
6213 // The ack time should be based on min_rtt/8, since it's less than the
6214 // default delayed ack time.
6215 QuicTime ack_time = clock_.ApproximateNow() +
6216 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6217 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6218 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6219 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006220 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006221 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006222 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006223 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006224 // Process a packet from the non-crypto stream.
6225 frame1_.stream_id = 3;
6226
6227 // Process all the initial packets in order so there aren't missing packets.
6228 uint64_t kFirstDecimatedPacket = 101;
6229 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6230 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6231 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6232 }
6233 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6234 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006235 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006236 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6237 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6238 ENCRYPTION_ZERO_RTT);
6239
6240 // Check if delayed ack timer is running for the expected interval.
6241 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6242 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6243
6244 // The 10th received packet causes an ack to be sent.
6245 for (int i = 0; i < 9; ++i) {
6246 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6247 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6248 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6249 ENCRYPTION_ZERO_RTT);
6250 }
6251 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006252 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006253 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006254 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006255 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6256 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006257 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006258 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6259 }
6260 EXPECT_FALSE(writer_->ack_frames().empty());
6261 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6262}
6263
6264TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6265 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6266 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6267
6268 const size_t kMinRttMs = 40;
6269 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6270 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6271 QuicTime::Delta::Zero(), QuicTime::Zero());
6272 // The ack time should be based on min_rtt/4, since it's less than the
6273 // default delayed ack time.
6274 QuicTime ack_time = clock_.ApproximateNow() +
6275 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6276 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6277 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6278 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006279 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006280 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006281 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006282 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006283 // Process a packet from the non-crypto stream.
6284 frame1_.stream_id = 3;
6285
6286 // Process all the initial packets in order so there aren't missing packets.
6287 uint64_t kFirstDecimatedPacket = 101;
6288 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6289 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6290 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6291 }
6292 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6293
6294 // Receive one packet out of order and then the rest in order.
6295 // The loop leaves a one packet gap between acks sent to simulate some loss.
6296 for (int j = 0; j < 3; ++j) {
6297 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6298 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6299 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6300 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6301 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6302 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6303 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6304
6305 // The 10th received packet causes an ack to be sent.
6306 writer_->Reset();
6307 for (int i = 0; i < 9; ++i) {
6308 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6309 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6310 // The ACK shouldn't be sent until the 10th packet is processed.
6311 EXPECT_TRUE(writer_->ack_frames().empty());
6312 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6313 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6314 }
6315 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006316 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006317 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006318 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006319 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6320 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006321 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006322 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6323 }
6324 EXPECT_FALSE(writer_->ack_frames().empty());
6325 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6326 }
6327}
6328
6329TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6330 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6331 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6332
6333 const size_t kMinRttMs = 40;
6334 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6335 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6336 QuicTime::Delta::Zero(), QuicTime::Zero());
6337 // The ack time should be based on min_rtt/4, since it's less than the
6338 // default delayed ack time.
6339 QuicTime ack_time = clock_.ApproximateNow() +
6340 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6341 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6342 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6343 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006344 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006345 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006346 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006347 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006348 // Process a packet from the non-crypto stream.
6349 frame1_.stream_id = 3;
6350
6351 // Process all the initial packets in order so there aren't missing packets.
6352 uint64_t kFirstDecimatedPacket = 101;
6353 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6354 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6355 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6356 }
6357 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6358 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006359 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006360 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6361 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6362 ENCRYPTION_ZERO_RTT);
6363
6364 // Check if delayed ack timer is running for the expected interval.
6365 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6366 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6367
6368 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6369 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6370 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6371 ENCRYPTION_ZERO_RTT);
6372 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6373 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6374 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6375
6376 // The 10th received packet causes an ack to be sent.
6377 for (int i = 0; i < 8; ++i) {
6378 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6379 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6380 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6381 ENCRYPTION_ZERO_RTT);
6382 }
6383 // Check that ack is sent and that delayed ack alarm is reset.
6384 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006385 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006386 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6387 } else {
6388 EXPECT_EQ(2u, writer_->frame_count());
6389 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6390 }
6391 EXPECT_FALSE(writer_->ack_frames().empty());
6392 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6393
6394 // The next packet received in order will cause an immediate ack,
6395 // because it fills a hole.
6396 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6397 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6398 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6399 ENCRYPTION_ZERO_RTT);
6400 // Check that ack is sent and that delayed ack alarm is reset.
6401 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006402 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006403 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6404 } else {
6405 EXPECT_EQ(2u, writer_->frame_count());
6406 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6407 }
6408 EXPECT_FALSE(writer_->ack_frames().empty());
6409 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6410}
6411
6412TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6413 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6414 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6415 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6416
6417 const size_t kMinRttMs = 40;
6418 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6419 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6420 QuicTime::Delta::Zero(), QuicTime::Zero());
6421 // The ack time should be based on min_rtt/8, since it's less than the
6422 // default delayed ack time.
6423 QuicTime ack_time = clock_.ApproximateNow() +
6424 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6425 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6426 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6427 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006428 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006429 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006430 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006431 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006432 // Process a packet from the non-crypto stream.
6433 frame1_.stream_id = 3;
6434
6435 // Process all the initial packets in order so there aren't missing packets.
6436 uint64_t kFirstDecimatedPacket = 101;
6437 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6438 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6439 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6440 }
6441 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6442 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006443 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006444 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6445 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6446 ENCRYPTION_ZERO_RTT);
6447
6448 // Check if delayed ack timer is running for the expected interval.
6449 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6450 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6451
6452 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6453 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6454 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6455 ENCRYPTION_ZERO_RTT);
6456 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6457 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6458 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6459
6460 // The 10th received packet causes an ack to be sent.
6461 for (int i = 0; i < 8; ++i) {
6462 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6463 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6464 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6465 ENCRYPTION_ZERO_RTT);
6466 }
6467 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006468 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006469 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006470 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006471 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6472 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006473 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006474 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6475 }
6476 EXPECT_FALSE(writer_->ack_frames().empty());
6477 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6478}
6479
6480TEST_P(QuicConnectionTest,
6481 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6482 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6483 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6484 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6485
6486 const size_t kMinRttMs = 40;
6487 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6488 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6489 QuicTime::Delta::Zero(), QuicTime::Zero());
6490 // The ack time should be based on min_rtt/8, since it's less than the
6491 // default delayed ack time.
6492 QuicTime ack_time = clock_.ApproximateNow() +
6493 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6494 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6495 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6496 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006497 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006498 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006499 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006500 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006501 // Process a packet from the non-crypto stream.
6502 frame1_.stream_id = 3;
6503
6504 // Process all the initial packets in order so there aren't missing packets.
6505 uint64_t kFirstDecimatedPacket = 101;
6506 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6507 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6508 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6509 }
6510 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6511 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006512 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006513 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6514 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6515 ENCRYPTION_ZERO_RTT);
6516
6517 // Check if delayed ack timer is running for the expected interval.
6518 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6519 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6520
6521 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6523 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6524 ENCRYPTION_ZERO_RTT);
6525 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
6526 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6527 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6528
6529 // The 10th received packet causes an ack to be sent.
6530 for (int i = 0; i < 8; ++i) {
6531 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6532 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6533 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6534 ENCRYPTION_ZERO_RTT);
6535 }
6536 // Check that ack is sent and that delayed ack alarm is reset.
6537 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006538 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006539 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6540 } else {
6541 EXPECT_EQ(2u, writer_->frame_count());
6542 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6543 }
6544 EXPECT_FALSE(writer_->ack_frames().empty());
6545 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6546
6547 // The next packet received in order will cause an immediate ack,
6548 // because it fills a hole.
6549 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6550 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6551 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6552 ENCRYPTION_ZERO_RTT);
6553 // Check that ack is sent and that delayed ack alarm is reset.
6554 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006555 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006556 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6557 } else {
6558 EXPECT_EQ(2u, writer_->frame_count());
6559 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6560 }
6561 EXPECT_FALSE(writer_->ack_frames().empty());
6562 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6563}
6564
6565TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6567 ProcessPacket(1);
6568 // Check that ack is sent and that delayed ack alarm is set.
6569 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6570 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6571 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6572
6573 // Completing the handshake as the server does nothing.
6574 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6575 connection_.OnHandshakeComplete();
6576 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6577 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6578
6579 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6580 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6581 connection_.OnHandshakeComplete();
6582 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6583 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6584}
6585
6586TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6587 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6588 ProcessPacket(1);
6589 ProcessPacket(2);
6590 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006591 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006592 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006593 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006594 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6595 } else {
nharper55fa6132019-05-07 19:37:21 -07006596 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006597 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6598 }
6599 EXPECT_FALSE(writer_->ack_frames().empty());
6600 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6601}
6602
6603TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6604 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006606 ProcessPacket(2);
6607 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006608
6609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6610 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006611 size_t padding_frame_count = writer_->padding_frames().size();
6612 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006613 EXPECT_FALSE(writer_->ack_frames().empty());
6614 writer_->Reset();
6615
fayang6dba4902019-06-17 10:04:23 -07006616 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006617 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006618 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006619
6620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6621 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006622 padding_frame_count = writer_->padding_frames().size();
6623 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006624 EXPECT_FALSE(writer_->ack_frames().empty());
6625 writer_->Reset();
6626
6627 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6628 // Now only set the timer on the 6th packet, instead of sending another ack.
6629 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006630 padding_frame_count = writer_->padding_frames().size();
6631 EXPECT_EQ(padding_frame_count, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006632 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
6633}
6634
6635TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6636 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006637 EXPECT_CALL(visitor_, OnStreamFrame(_));
6638 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006639 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006640 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006641 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006642 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006643 connection_.SendStreamDataWithString(
6644 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6645 0, NO_FIN);
6646 // Check that ack is bundled with outgoing data and that delayed ack
6647 // alarm is reset.
6648 if (GetParam().no_stop_waiting) {
6649 EXPECT_EQ(2u, writer_->frame_count());
6650 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6651 } else {
6652 EXPECT_EQ(3u, writer_->frame_count());
6653 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6654 }
6655 EXPECT_FALSE(writer_->ack_frames().empty());
6656 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6657}
6658
6659TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6660 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07006661 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6662 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6663 } else {
6664 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6665 }
6666 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07006667 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006668 // Check that ack is bundled with outgoing crypto data.
6669 if (GetParam().no_stop_waiting) {
6670 EXPECT_EQ(3u, writer_->frame_count());
6671 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6672 } else {
6673 EXPECT_EQ(4u, writer_->frame_count());
6674 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6675 }
6676 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6677}
6678
6679TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6680 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6681 ProcessPacket(1);
6682 BlockOnNextWrite();
6683 writer_->set_is_write_blocked_data_buffered(true);
nharper46833c32019-05-15 21:33:05 -07006684 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006685 EXPECT_TRUE(writer_->IsWriteBlocked());
6686 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07006687 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006688 EXPECT_TRUE(writer_->IsWriteBlocked());
6689 EXPECT_TRUE(connection_.HasQueuedData());
6690}
6691
6692TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6693 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6694 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6695 EXPECT_CALL(visitor_, OnCanWrite())
6696 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6697 &connection_, &TestConnection::SendCryptoStreamData)));
6698 // Process a packet from the crypto stream, which is frame1_'s default.
6699 // Receiving the CHLO as packet 2 first will cause the connection to
6700 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07006701 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6702 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6703 } else {
6704 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6705 }
6706 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006707 // Check that ack is sent and that delayed ack alarm is reset.
6708 if (GetParam().no_stop_waiting) {
6709 EXPECT_EQ(3u, writer_->frame_count());
6710 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6711 } else {
6712 EXPECT_EQ(4u, writer_->frame_count());
6713 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6714 }
QUICHE teamea740082019-03-11 17:58:43 -07006715 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006716 EXPECT_EQ(1u, writer_->stream_frames().size());
6717 } else {
6718 EXPECT_EQ(1u, writer_->crypto_frames().size());
6719 }
6720 EXPECT_EQ(1u, writer_->padding_frames().size());
6721 ASSERT_FALSE(writer_->ack_frames().empty());
6722 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6723 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6724}
6725
6726TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6727 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6728 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6729
6730 // Process two packets from the crypto stream, which is frame1_'s default,
6731 // simulating a 2 packet reject.
6732 {
fayangc31c9952019-06-05 13:54:48 -07006733 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6734 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6735 } else {
6736 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6737 }
6738 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006739 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07006740 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6741 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6742 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6743 &connection_, &TestConnection::SendCryptoStreamData)));
6744 } else {
6745 EXPECT_CALL(visitor_, OnStreamFrame(_))
6746 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6747 &connection_, &TestConnection::SendCryptoStreamData)));
6748 }
6749 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006750 }
6751 // Check that ack is sent and that delayed ack alarm is reset.
6752 if (GetParam().no_stop_waiting) {
6753 EXPECT_EQ(3u, writer_->frame_count());
6754 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6755 } else {
6756 EXPECT_EQ(4u, writer_->frame_count());
6757 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6758 }
QUICHE teamea740082019-03-11 17:58:43 -07006759 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006760 EXPECT_EQ(1u, writer_->stream_frames().size());
6761 } else {
6762 EXPECT_EQ(1u, writer_->crypto_frames().size());
6763 }
6764 EXPECT_EQ(1u, writer_->padding_frames().size());
6765 ASSERT_FALSE(writer_->ack_frames().empty());
6766 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6767 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6768}
6769
6770TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6771 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6772 connection_.SendStreamDataWithString(
6773 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6774 0, NO_FIN);
6775 connection_.SendStreamDataWithString(
6776 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6777 3, NO_FIN);
6778 // Ack the second packet, which will retransmit the first packet.
6779 QuicAckFrame ack = ConstructAckFrame(2, 1);
6780 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07006781 lost_packets.push_back(
6782 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006783 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6784 .WillOnce(SetArgPointee<5>(lost_packets));
6785 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6786 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07006787 size_t padding_frame_count = writer_->padding_frames().size();
6788 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006789 EXPECT_EQ(1u, writer_->stream_frames().size());
6790 writer_->Reset();
6791
6792 // Now ack the retransmission, which will both raise the high water mark
6793 // and see if there is more data to send.
6794 ack = ConstructAckFrame(3, 1);
6795 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6796 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6797 ProcessAckPacket(&ack);
6798
6799 // Check that no packet is sent and the ack alarm isn't set.
6800 EXPECT_EQ(0u, writer_->frame_count());
6801 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6802 writer_->Reset();
6803
6804 // Send the same ack, but send both data and an ack together.
6805 ack = ConstructAckFrame(3, 1);
6806 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6807 EXPECT_CALL(visitor_, OnCanWrite())
6808 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6809 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6810 ProcessAckPacket(&ack);
6811
6812 // Check that ack is bundled with outgoing data and the delayed ack
6813 // alarm is reset.
6814 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08006815 // Do not ACK acks.
6816 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006817 } else {
6818 EXPECT_EQ(3u, writer_->frame_count());
6819 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6820 }
fayang8a27b0f2019-11-04 11:27:40 -08006821 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07006822 EXPECT_TRUE(writer_->ack_frames().empty());
6823 } else {
6824 EXPECT_FALSE(writer_->ack_frames().empty());
6825 EXPECT_EQ(QuicPacketNumber(3u),
6826 LargestAcked(writer_->ack_frames().front()));
6827 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006828 EXPECT_EQ(1u, writer_->stream_frames().size());
6829 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
6830}
6831
6832TEST_P(QuicConnectionTest, NoAckSentForClose) {
6833 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6834 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07006835 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6836 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6838 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07006839 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006840 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6841 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006842}
6843
6844TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6845 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006846 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6847 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006848 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6849 ConnectionCloseBehavior::SILENT_CLOSE);
6850 EXPECT_FALSE(connection_.connected());
6851 EXPECT_FALSE(connection_.CanWriteStreamData());
QUICHE team8c1daa22019-03-13 08:33:41 -07006852 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006853 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006854 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6855 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006856 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006857 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07006858 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006859 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6860 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006861}
6862
6863TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6864 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07006865 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006866 return;
6867 }
6868
6869 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006870 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6871 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006872 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6873 ConnectionCloseBehavior::SILENT_CLOSE);
6874 EXPECT_FALSE(connection_.connected());
6875 EXPECT_FALSE(connection_.CanWriteStreamData());
6876
6877 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6878 .Times(0);
6879
6880 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6881 writer_.get(), connection_.peer_address()),
6882 "Not sending connectivity probing packet as connection is "
6883 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07006884 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006885 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6886 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006887}
6888
6889TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6890 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6891 TestPacketWriter probing_writer(version(), &clock_);
6892 // Block next write so that sending connectivity probe will encounter a
6893 // blocked write when send a connectivity probe to the peer.
6894 probing_writer.BlockOnNextWrite();
6895 // Connection will not be marked as write blocked as connectivity probe only
6896 // affects the probing_writer which is not the default.
6897 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6898
6899 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6900 .Times(1);
6901 connection_.SendConnectivityProbingPacket(&probing_writer,
6902 connection_.peer_address());
6903}
6904
6905TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6906 set_perspective(Perspective::IS_SERVER);
6907 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6908
6909 // Block next write so that sending connectivity probe will encounter a
6910 // blocked write when send a connectivity probe to the peer.
6911 writer_->BlockOnNextWrite();
6912 // Connection will be marked as write blocked as server uses the default
6913 // writer to send connectivity probes.
6914 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6915
6916 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6917 .Times(1);
6918 connection_.SendConnectivityProbingPacket(writer_.get(),
6919 connection_.peer_address());
6920}
6921
6922TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6923 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
6924 TestPacketWriter probing_writer(version(), &clock_);
6925 probing_writer.SetShouldWriteFail();
6926
6927 // Connection should not be closed if a connectivity probe is failed to be
6928 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006929 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006930
6931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6932 .Times(0);
6933 connection_.SendConnectivityProbingPacket(&probing_writer,
6934 connection_.peer_address());
6935}
6936
6937TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6938 set_perspective(Perspective::IS_SERVER);
6939 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6940
6941 writer_->SetShouldWriteFail();
6942 // Connection should not be closed if a connectivity probe is failed to be
6943 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07006944 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006945
6946 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6947 .Times(0);
6948 connection_.SendConnectivityProbingPacket(writer_.get(),
6949 connection_.peer_address());
6950}
6951
6952TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07006953 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006954 return;
6955 }
6956 QuicPublicResetPacket header;
6957 // Public reset packet in only built by server.
6958 header.connection_id = connection_id_;
6959 std::unique_ptr<QuicEncryptedPacket> packet(
6960 framer_.BuildPublicResetPacket(header));
6961 std::unique_ptr<QuicReceivedPacket> received(
6962 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006963 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6964 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006965 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006966 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006967 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6968 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006969}
6970
6971TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07006972 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006973 return;
6974 }
6975 const QuicUint128 kTestStatelessResetToken = 1010101;
6976 QuicConfig config;
6977 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6978 kTestStatelessResetToken);
6979 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6980 connection_.SetFromConfig(config);
6981 std::unique_ptr<QuicEncryptedPacket> packet(
6982 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6983 kTestStatelessResetToken));
6984 std::unique_ptr<QuicReceivedPacket> received(
6985 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07006986 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6987 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006988 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07006989 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08006990 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6991 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006992}
6993
6994TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07006995 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006996 // GoAway is not available in version 99.
6997 return;
6998 }
6999
7000 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7001
7002 QuicGoAwayFrame goaway;
7003 goaway.last_good_stream_id = 1;
7004 goaway.error_code = QUIC_PEER_GOING_AWAY;
7005 goaway.reason_phrase = "Going away.";
7006 EXPECT_CALL(visitor_, OnGoAway(_));
7007 ProcessGoAwayPacket(&goaway);
7008}
7009
7010TEST_P(QuicConnectionTest, WindowUpdate) {
7011 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7012
7013 QuicWindowUpdateFrame window_update;
7014 window_update.stream_id = 3;
renjietangd088eab2019-11-21 14:54:41 -08007015 window_update.max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007016 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7017 ProcessFramePacket(QuicFrame(&window_update));
7018}
7019
7020TEST_P(QuicConnectionTest, Blocked) {
7021 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7022
7023 QuicBlockedFrame blocked;
7024 blocked.stream_id = 3;
7025 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7026 ProcessFramePacket(QuicFrame(&blocked));
7027 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7028 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7029}
7030
7031TEST_P(QuicConnectionTest, ZeroBytePacket) {
7032 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007033 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007034 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7035 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7036}
7037
7038TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007039 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007040 return;
7041 }
7042 // Set the packet number of the ack packet to be least unacked (4).
7043 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7044 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7045 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007046 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007047}
7048
QUICHE teama6ef0a62019-03-07 20:34:33 -05007049TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007050 // All supported versions except the one the connection supports.
7051 ParsedQuicVersionVector versions;
7052 for (auto version : AllSupportedVersions()) {
7053 if (version != connection_.version()) {
7054 versions.push_back(version);
7055 }
7056 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007057
7058 // Send a version negotiation packet.
7059 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007060 QuicFramer::BuildVersionNegotiationPacket(
7061 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007062 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007063 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007064 std::unique_ptr<QuicReceivedPacket> received(
7065 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007066 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7067 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007068 // Verify no connection close packet gets sent.
7069 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007070 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007071 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007072 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007073 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7074 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007075}
7076
7077TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7078 // Send a version negotiation packet with the version the client started with.
7079 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007080 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7081 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007082 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007083 QuicFramer::BuildVersionNegotiationPacket(
7084 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007085 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007086 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007087 AllSupportedVersions()));
7088 std::unique_ptr<QuicReceivedPacket> received(
7089 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7090 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007091 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007092 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7093 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007094}
7095
7096TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007097 if (connection_.PtoEnabled()) {
7098 return;
7099 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007100 connection_.SetMaxTailLossProbes(0);
7101
7102 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7103 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7104 size_t first_packet_size = writer_->last_packet_size();
7105
7106 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7107 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7108 size_t second_packet_size = writer_->last_packet_size();
7109
7110 // 2 retransmissions due to rto, 1 due to explicit nack.
7111 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7112 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7113
7114 // Retransmit due to RTO.
7115 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7116 connection_.GetRetransmissionAlarm()->Fire();
7117
7118 // Retransmit due to explicit nacks.
7119 QuicAckFrame nack_three =
7120 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7121 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7122
7123 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007124 lost_packets.push_back(
7125 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7126 lost_packets.push_back(
7127 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007128 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
7129 .WillOnce(SetArgPointee<5>(lost_packets));
7130 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007131 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7132 ProcessAckPacket(&nack_three);
7133
7134 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7135 .WillOnce(Return(QuicBandwidth::Zero()));
7136
7137 const QuicConnectionStats& stats = connection_.GetStats();
7138 // For IETF QUIC, version is not included as the encryption level switches to
7139 // FORWARD_SECURE in SendStreamDataWithString.
7140 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007141 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7142 ? 0
7143 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007144 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7145 stats.bytes_sent);
7146 EXPECT_EQ(5u, stats.packets_sent);
7147 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7148 stats.bytes_retransmitted);
7149 EXPECT_EQ(3u, stats.packets_retransmitted);
7150 EXPECT_EQ(1u, stats.rto_count);
7151 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7152}
7153
7154TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7155 // Construct a packet with stream frame and connection close frame.
7156 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007157 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007158 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007159 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007160 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007161 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7162 }
7163 } else {
7164 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007165 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007166 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7167 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007168 }
7169 header.packet_number = QuicPacketNumber(1);
7170 header.version_flag = false;
7171
fkastenholz488a4622019-08-26 06:24:46 -07007172 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7173 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7174 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7175 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007176 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7177 kQuicErrorCode, "",
7178 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007179 QuicFrames frames;
7180 frames.push_back(QuicFrame(frame1_));
7181 frames.push_back(QuicFrame(&qccf));
7182 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7183 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007184 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007185 size_t encrypted_length = peer_framer_.EncryptPayload(
7186 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7187 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007188
fkastenholz5d880a92019-06-21 09:01:56 -07007189 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7190 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007191 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7192 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7193
7194 connection_.ProcessUdpPacket(
7195 kSelfAddress, kPeerAddress,
7196 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007197 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007198 EXPECT_THAT(saved_connection_close_frame_.extracted_error_code,
7199 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007200}
7201
7202TEST_P(QuicConnectionTest, SelectMutualVersion) {
7203 connection_.SetSupportedVersions(AllSupportedVersions());
7204 // Set the connection to speak the lowest quic version.
7205 connection_.set_version(QuicVersionMin());
7206 EXPECT_EQ(QuicVersionMin(), connection_.version());
7207
7208 // Pass in available versions which includes a higher mutually supported
7209 // version. The higher mutually supported version should be selected.
7210 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7211 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7212 EXPECT_EQ(QuicVersionMax(), connection_.version());
7213
7214 // Expect that the lowest version is selected.
7215 // Ensure the lowest supported version is less than the max, unless they're
7216 // the same.
7217 ParsedQuicVersionVector lowest_version_vector;
7218 lowest_version_vector.push_back(QuicVersionMin());
7219 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7220 EXPECT_EQ(QuicVersionMin(), connection_.version());
7221
7222 // Shouldn't be able to find a mutually supported version.
7223 ParsedQuicVersionVector unsupported_version;
7224 unsupported_version.push_back(UnsupportedQuicVersion());
7225 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7226}
7227
7228TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7229 EXPECT_FALSE(writer_->IsWriteBlocked());
7230
7231 // Send a packet.
7232 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7233 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7234 EXPECT_EQ(1u, writer_->packets_write_attempts());
7235
7236 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007237 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007238}
7239
7240TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7241 BlockOnNextWrite();
7242 TriggerConnectionClose();
7243 EXPECT_EQ(1u, writer_->packets_write_attempts());
7244 EXPECT_TRUE(writer_->IsWriteBlocked());
7245}
7246
7247TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7248 BlockOnNextWrite();
7249 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7250 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7251 EXPECT_EQ(1u, writer_->packets_write_attempts());
7252 EXPECT_TRUE(writer_->IsWriteBlocked());
7253 TriggerConnectionClose();
7254 EXPECT_EQ(1u, writer_->packets_write_attempts());
7255}
7256
7257TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7258 MockQuicConnectionDebugVisitor debug_visitor;
7259 connection_.set_debug_visitor(&debug_visitor);
7260
fayangcff885a2019-10-22 07:39:04 -07007261 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007262 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7263
fayangcff885a2019-10-22 07:39:04 -07007264 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007265 connection_.SendConnectivityProbingPacket(writer_.get(),
7266 connection_.peer_address());
7267}
7268
7269TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7270 QuicPacketHeader header;
7271 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007272 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007273 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7274 }
7275
7276 MockQuicConnectionDebugVisitor debug_visitor;
7277 connection_.set_debug_visitor(&debug_visitor);
7278 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7279 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7280 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7281 connection_.OnPacketHeader(header);
7282}
7283
7284TEST_P(QuicConnectionTest, Pacing) {
7285 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7286 alarm_factory_.get(), writer_.get(),
7287 Perspective::IS_SERVER, version());
7288 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7289 alarm_factory_.get(), writer_.get(),
7290 Perspective::IS_CLIENT, version());
7291 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7292 static_cast<const QuicSentPacketManager*>(
7293 &client.sent_packet_manager())));
7294 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7295 static_cast<const QuicSentPacketManager*>(
7296 &server.sent_packet_manager())));
7297}
7298
7299TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7300 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7301
7302 // Send a WINDOW_UPDATE frame.
7303 QuicWindowUpdateFrame window_update;
7304 window_update.stream_id = 3;
renjietangd088eab2019-11-21 14:54:41 -08007305 window_update.max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007306 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7307 ProcessFramePacket(QuicFrame(&window_update));
7308
7309 // Ensure that this has caused the ACK alarm to be set.
7310 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7311 EXPECT_TRUE(ack_alarm->IsSet());
7312}
7313
7314TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7315 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7316
7317 // Send a BLOCKED frame.
7318 QuicBlockedFrame blocked;
7319 blocked.stream_id = 3;
7320 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7321 ProcessFramePacket(QuicFrame(&blocked));
7322
7323 // Ensure that this has caused the ACK alarm to be set.
7324 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
7325 EXPECT_TRUE(ack_alarm->IsSet());
7326}
7327
7328TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7329 // Enable pacing.
7330 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7331 QuicConfig config;
7332 connection_.SetFromConfig(config);
7333
7334 // Send two packets. One packet is not sufficient because if it gets acked,
7335 // there will be no packets in flight after that and the pacer will always
7336 // allow the next packet in that situation.
7337 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7338 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7339 connection_.SendStreamDataWithString(
7340 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7341 0, NO_FIN);
7342 connection_.SendStreamDataWithString(
7343 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7344 3, NO_FIN);
7345 connection_.OnCanWrite();
7346
7347 // Schedule the next packet for a few milliseconds in future.
7348 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7349 QuicTime scheduled_pacing_time =
7350 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7351 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7352 scheduled_pacing_time);
7353
7354 // Send a packet and have it be blocked by congestion control.
7355 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7356 connection_.SendStreamDataWithString(
7357 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7358 6, NO_FIN);
7359 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7360
7361 // Process an ack and the send alarm will be set to the new 5ms delay.
7362 QuicAckFrame ack = InitAckFrame(1);
7363 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7365 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7366 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007367 size_t padding_frame_count = writer_->padding_frames().size();
7368 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007369 EXPECT_EQ(1u, writer_->stream_frames().size());
7370 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7371 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7372 writer_->Reset();
7373}
7374
7375TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007376 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7377 return;
7378 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007379 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7380 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7381 ProcessDataPacket(1);
7382 CongestionBlockWrites();
7383 SendAckPacketToPeer();
7384}
7385
7386TEST_P(QuicConnectionTest, SendPingImmediately) {
7387 MockQuicConnectionDebugVisitor debug_visitor;
7388 connection_.set_debug_visitor(&debug_visitor);
7389
7390 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007391 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007392 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007393 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007394 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7395 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7396 EXPECT_FALSE(connection_.HasQueuedData());
7397}
7398
7399TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7400 MockQuicConnectionDebugVisitor debug_visitor;
7401 connection_.set_debug_visitor(&debug_visitor);
7402
fayang93cc53a2019-08-22 12:47:30 -07007403 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007405 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007406 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7407 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7408 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7409 EXPECT_FALSE(connection_.HasQueuedData());
7410}
7411
fayang93cc53a2019-08-22 12:47:30 -07007412TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7413 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7414 return;
7415 }
7416 MockQuicConnectionDebugVisitor debug_visitor;
7417 connection_.set_debug_visitor(&debug_visitor);
7418 QuicBlockedFrame blocked(1, 3);
7419
7420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007421 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007422 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7423 connection_.SendControlFrame(QuicFrame(&blocked));
7424 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7425 EXPECT_FALSE(connection_.HasQueuedData());
7426}
7427
QUICHE teama6ef0a62019-03-07 20:34:33 -05007428TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7429 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7430 if (!IsDefaultTestConfiguration()) {
7431 return;
7432 }
7433
fkastenholz5d880a92019-06-21 09:01:56 -07007434 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7435 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007436 struct iovec iov;
7437 MakeIOVector("", &iov);
7438 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007439 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007440 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007441 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007442 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7443 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007444}
7445
7446TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7447 EXPECT_TRUE(connection_.connected());
7448 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7449
7450 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7451 connection_.SendCryptoStreamData();
7452
7453 // Verify retransmission timer is correctly set after crypto packet has been
7454 // sent.
7455 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7456 QuicTime retransmission_time =
7457 QuicConnectionPeer::GetSentPacketManager(&connection_)
7458 ->GetRetransmissionTime();
7459 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7460 EXPECT_EQ(retransmission_time,
7461 connection_.GetRetransmissionAlarm()->deadline());
7462
7463 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7464 connection_.GetRetransmissionAlarm()->Fire();
7465}
7466
7467TEST_P(QuicConnectionTest, PathDegradingAlarmForCryptoPacket) {
7468 EXPECT_TRUE(connection_.connected());
7469 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7470 EXPECT_FALSE(connection_.IsPathDegrading());
7471
7472 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7473 connection_.SendCryptoStreamData();
7474
7475 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7476 EXPECT_FALSE(connection_.IsPathDegrading());
7477 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7478 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007479 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7480 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007481
7482 // Fire the path degrading alarm, path degrading signal should be sent to
7483 // the visitor.
7484 EXPECT_CALL(visitor_, OnPathDegrading());
7485 clock_.AdvanceTime(delay);
7486 connection_.GetPathDegradingAlarm()->Fire();
7487 EXPECT_TRUE(connection_.IsPathDegrading());
7488 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7489}
7490
vasilvv693d5b02019-04-09 21:58:56 -07007491// Includes regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007492TEST_P(QuicConnectionTest, PathDegradingAlarmForNonCryptoPackets) {
7493 EXPECT_TRUE(connection_.connected());
7494 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7495 EXPECT_FALSE(connection_.IsPathDegrading());
7496
7497 const char data[] = "data";
7498 size_t data_size = strlen(data);
7499 QuicStreamOffset offset = 0;
7500
7501 for (int i = 0; i < 2; ++i) {
7502 // Send a packet. Now there's a retransmittable packet on the wire, so the
7503 // path degrading alarm should be set.
7504 connection_.SendStreamDataWithString(
7505 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7506 offset, NO_FIN);
7507 offset += data_size;
7508 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7509 // Check the deadline of the path degrading alarm.
7510 QuicTime::Delta delay =
7511 QuicConnectionPeer::GetSentPacketManager(&connection_)
7512 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007513 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7514 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007515
7516 // Send a second packet. The path degrading alarm's deadline should remain
7517 // the same.
vasilvv693d5b02019-04-09 21:58:56 -07007518 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007519 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7520 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7521 connection_.SendStreamDataWithString(
7522 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7523 offset, NO_FIN);
7524 offset += data_size;
7525 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7526 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7527
7528 // Now receive an ACK of the first packet. This should advance the path
7529 // degrading alarm's deadline since forward progress has been made.
7530 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7531 if (i == 0) {
7532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7533 }
7534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7535 QuicAckFrame frame = InitAckFrame(
7536 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7537 ProcessAckPacket(&frame);
7538 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7539 // Check the deadline of the path degrading alarm.
7540 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7541 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007542 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7543 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007544
7545 if (i == 0) {
7546 // Now receive an ACK of the second packet. Since there are no more
7547 // retransmittable packets on the wire, this should cancel the path
7548 // degrading alarm.
7549 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7550 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7551 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7552 ProcessAckPacket(&frame);
7553 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7554 } else {
7555 // Advance time to the path degrading alarm's deadline and simulate
7556 // firing the alarm.
7557 clock_.AdvanceTime(delay);
7558 EXPECT_CALL(visitor_, OnPathDegrading());
7559 connection_.GetPathDegradingAlarm()->Fire();
7560 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7561 }
7562 }
7563 EXPECT_TRUE(connection_.IsPathDegrading());
7564}
7565
7566TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7567 const QuicTime::Delta retransmittable_on_wire_timeout =
7568 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007569 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007570 retransmittable_on_wire_timeout);
7571
7572 EXPECT_TRUE(connection_.connected());
7573 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7574 .WillRepeatedly(Return(true));
7575
7576 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7577 EXPECT_FALSE(connection_.IsPathDegrading());
7578 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7579
7580 const char data[] = "data";
7581 size_t data_size = strlen(data);
7582 QuicStreamOffset offset = 0;
7583
7584 // Send a packet.
7585 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7586 offset += data_size;
7587 // Now there's a retransmittable packet on the wire, so the path degrading
7588 // alarm should be set.
7589 // The retransmittable-on-wire alarm should not be set.
7590 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7591 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7592 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007593 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7594 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007595 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7596 // The ping alarm is set for the ping timeout, not the shorter
7597 // retransmittable_on_wire_timeout.
7598 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7599 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007600 EXPECT_EQ(ping_delay,
7601 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007602
7603 // Now receive an ACK of the packet.
7604 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7606 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7607 QuicAckFrame frame =
7608 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7609 ProcessAckPacket(&frame);
7610 // No more retransmittable packets on the wire, so the path degrading alarm
7611 // should be cancelled, and the ping alarm should be set to the
7612 // retransmittable_on_wire_timeout.
7613 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7614 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007615 EXPECT_EQ(retransmittable_on_wire_timeout,
7616 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007617
7618 // Simulate firing the ping alarm and sending a PING.
7619 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7620 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7621 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7622 }));
7623 connection_.GetPingAlarm()->Fire();
7624
7625 // Now there's a retransmittable packet (PING) on the wire, so the path
7626 // degrading alarm should be set.
7627 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7628 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7629 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007630 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7631 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007632}
7633
7634// This test verifies that the connection marks path as degrading and does not
7635// spin timer to detect path degrading when a new packet is sent on the
7636// degraded path.
7637TEST_P(QuicConnectionTest, NoPathDegradingAlarmIfPathIsDegrading) {
7638 EXPECT_TRUE(connection_.connected());
7639 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7640 EXPECT_FALSE(connection_.IsPathDegrading());
7641
7642 const char data[] = "data";
7643 size_t data_size = strlen(data);
7644 QuicStreamOffset offset = 0;
7645
7646 // Send the first packet. Now there's a retransmittable packet on the wire, so
7647 // the path degrading alarm should be set.
7648 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7649 offset += data_size;
7650 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7651 // Check the deadline of the path degrading alarm.
7652 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7653 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007654 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7655 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007656
7657 // Send a second packet. The path degrading alarm's deadline should remain
7658 // the same.
7659 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7660 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7661 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7662 offset += data_size;
7663 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7664 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7665
7666 // Now receive an ACK of the first packet. This should advance the path
7667 // degrading alarm's deadline since forward progress has been made.
7668 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7669 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7670 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7671 QuicAckFrame frame =
7672 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7673 ProcessAckPacket(&frame);
7674 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7675 // Check the deadline of the path degrading alarm.
7676 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7677 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007678 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7679 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007680
7681 // Advance time to the path degrading alarm's deadline and simulate
7682 // firing the path degrading alarm. This path will be considered as
7683 // degrading.
7684 clock_.AdvanceTime(delay);
7685 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7686 connection_.GetPathDegradingAlarm()->Fire();
7687 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7688 EXPECT_TRUE(connection_.IsPathDegrading());
7689
7690 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7691 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7692 // Send a third packet. The path degrading alarm is no longer set but path
7693 // should still be marked as degrading.
7694 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7695 offset += data_size;
7696 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7697 EXPECT_TRUE(connection_.IsPathDegrading());
7698}
7699
7700// This test verifies that the connection unmarks path as degrarding and spins
7701// the timer to detect future path degrading when forward progress is made
7702// after path has been marked degrading.
7703TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7704 EXPECT_TRUE(connection_.connected());
7705 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7706 EXPECT_FALSE(connection_.IsPathDegrading());
7707
7708 const char data[] = "data";
7709 size_t data_size = strlen(data);
7710 QuicStreamOffset offset = 0;
7711
7712 // Send the first packet. Now there's a retransmittable packet on the wire, so
7713 // the path degrading alarm should be set.
7714 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7715 offset += data_size;
7716 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7717 // Check the deadline of the path degrading alarm.
7718 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7719 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007720 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7721 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007722
7723 // Send a second packet. The path degrading alarm's deadline should remain
7724 // the same.
7725 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7726 QuicTime prev_deadline = connection_.GetPathDegradingAlarm()->deadline();
7727 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7728 offset += data_size;
7729 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7730 EXPECT_EQ(prev_deadline, connection_.GetPathDegradingAlarm()->deadline());
7731
7732 // Now receive an ACK of the first packet. This should advance the path
7733 // degrading alarm's deadline since forward progress has been made.
7734 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7736 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7737 QuicAckFrame frame =
7738 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7739 ProcessAckPacket(&frame);
7740 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7741 // Check the deadline of the path degrading alarm.
7742 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7743 ->GetPathDegradingDelay();
zhongyieef848f2019-10-18 07:09:37 -07007744 EXPECT_EQ(delay, connection_.GetPathDegradingAlarm()->deadline() -
7745 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007746
7747 // Advance time to the path degrading alarm's deadline and simulate
7748 // firing the alarm.
7749 clock_.AdvanceTime(delay);
7750 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7751 connection_.GetPathDegradingAlarm()->Fire();
7752 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7753 EXPECT_TRUE(connection_.IsPathDegrading());
7754
7755 // Send a third packet. The path degrading alarm is no longer set but path
7756 // should still be marked as degrading.
7757 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7758 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7759 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7760 offset += data_size;
7761 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7762 EXPECT_TRUE(connection_.IsPathDegrading());
7763
7764 // Now receive an ACK of the second packet. This should unmark the path as
7765 // degrading. And will set a timer to detect new path degrading.
7766 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7767 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7768 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7769 ProcessAckPacket(&frame);
7770 EXPECT_FALSE(connection_.IsPathDegrading());
7771 EXPECT_TRUE(connection_.GetPathDegradingAlarm()->IsSet());
7772}
7773
7774TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07007775 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7776 return;
7777 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007778 set_perspective(Perspective::IS_SERVER);
7779 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7780
7781 EXPECT_FALSE(connection_.IsPathDegrading());
7782 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7783
7784 // Send data.
7785 const char data[] = "data";
7786 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7787 EXPECT_FALSE(connection_.IsPathDegrading());
7788 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7789
7790 // Ack data.
7791 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007792 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7793 QuicAckFrame frame =
7794 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7795 ProcessAckPacket(&frame);
7796 EXPECT_FALSE(connection_.IsPathDegrading());
7797 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7798}
7799
7800TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07007801 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7802 return;
7803 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007804 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7805 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7806 ProcessDataPacket(1);
7807 SendAckPacketToPeer();
7808 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7809 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7810 EXPECT_FALSE(connection_.IsPathDegrading());
7811 EXPECT_FALSE(connection_.GetPathDegradingAlarm()->IsSet());
7812}
7813
7814TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7815 // Verifies that multiple calls to CloseConnection do not
7816 // result in multiple attempts to close the connection - it will be marked as
7817 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07007818 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007819 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7820 ConnectionCloseBehavior::SILENT_CLOSE);
7821 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7822 ConnectionCloseBehavior::SILENT_CLOSE);
7823}
7824
7825TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007826 set_perspective(Perspective::IS_SERVER);
7827 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7828
7829 CryptoHandshakeMessage message;
7830 CryptoFramer framer;
7831 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007832 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007833 frame1_.stream_id = 10;
7834 frame1_.data_buffer = data->data();
7835 frame1_.data_length = data->length();
7836
fkastenholz5d880a92019-06-21 09:01:56 -07007837 EXPECT_CALL(visitor_,
7838 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007839 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007840 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007841}
7842
7843TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7844 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7845
7846 CryptoHandshakeMessage message;
7847 CryptoFramer framer;
7848 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07007849 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007850 frame1_.stream_id = 10;
7851 frame1_.data_buffer = data->data();
7852 frame1_.data_length = data->length();
7853
fkastenholz5d880a92019-06-21 09:01:56 -07007854 EXPECT_CALL(visitor_,
7855 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007856 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07007857 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007858}
7859
7860TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7861 SimulateNextPacketTooLarge();
7862 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07007863 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007864 .Times(1);
7865 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007866 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007867}
7868
7869TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7870 // Test even we always get packet too large, we do not infinitely try to send
7871 // close packet.
7872 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07007873 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05007874 .Times(1);
7875 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07007876 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007877}
7878
nharperef468962019-07-02 14:15:38 -07007879TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07007880 // Regression test for crbug.com/979507.
7881 //
7882 // If we get a write error when writing queued packets, we should attempt to
7883 // send a connection close packet, but if sending that fails, it shouldn't get
7884 // queued.
7885
7886 // Queue a packet to write.
7887 BlockOnNextWrite();
7888 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7889 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7890
7891 // Configure writer to always fail.
7892 AlwaysGetPacketTooLarge();
7893
7894 // Expect that we attempt to close the connection exactly once.
7895 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7896 .Times(1);
7897
7898 // Unblock the writes and actually send.
7899 writer_->SetWritable();
7900 connection_.OnCanWrite();
7901 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7902
7903 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7904}
7905
QUICHE teama6ef0a62019-03-07 20:34:33 -05007906// Verify that if connection has no outstanding data, it notifies the send
7907// algorithm after the write.
7908TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7909 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7910 {
7911 InSequence seq;
7912 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7914 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7915 .WillRepeatedly(Return(false));
7916 }
7917
7918 connection_.SendStreamData3();
7919}
7920
7921// Verify that the connection does not become app-limited if there is
7922// outstanding data to send after the write.
7923TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7924 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7925 {
7926 InSequence seq;
7927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7928 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7929 }
7930
7931 connection_.SendStreamData3();
7932}
7933
7934// Verify that the connection does not become app-limited after blocked write
7935// even if there is outstanding data to send after the write.
7936TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7937 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7938 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7939 BlockOnNextWrite();
7940
fayange62e63c2019-12-04 07:16:25 -08007941 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007942 connection_.SendStreamData3();
7943
7944 // Now unblock the writer, become congestion control blocked,
7945 // and ensure we become app-limited after writing.
7946 writer_->SetWritable();
7947 CongestionBlockWrites();
7948 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08007949 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07007950 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007951 connection_.OnCanWrite();
7952}
7953
7954// Test the mode in which the link is filled up with probing retransmissions if
7955// the connection becomes application-limited.
7956TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
7957 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7958 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
7959 .WillRepeatedly(Return(true));
7960 {
7961 InSequence seq;
7962 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7963 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7964 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7965 .WillRepeatedly(Return(false));
7966 }
QUICHE teamb8343252019-04-29 13:58:01 -07007967 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
7968 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
7969 PROBING_RETRANSMISSION);
7970 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05007971 // Fix congestion window to be 20,000 bytes.
7972 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
7973 .WillRepeatedly(Return(false));
7974 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
7975 .WillRepeatedly(Return(true));
7976
7977 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7978 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
7979 connection_.set_fill_up_link_during_probing(true);
7980 connection_.OnHandshakeComplete();
7981 connection_.SendStreamData3();
7982
7983 // We expect a lot of packets from a 20 kbyte window.
7984 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
7985 // Ensure that the packets are padded.
7986 QuicByteCount average_packet_size =
7987 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
7988 EXPECT_GT(average_packet_size, 1000u);
7989
7990 // Acknowledge all packets sent, except for the last one.
7991 QuicAckFrame ack = InitAckFrame(
7992 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
7993 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7994 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7995
7996 // Ensure that since we no longer have retransmittable bytes in flight, this
7997 // will not cause any responses to be sent.
7998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7999 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8000 ProcessAckPacket(&ack);
8001}
8002
rchd672c6d2019-11-27 15:30:54 -08008003TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8005 // Send an ack by simulating delayed ack alarm firing.
8006 ProcessPacket(1);
8007 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8008 EXPECT_TRUE(ack_alarm->IsSet());
8009 connection_.GetAckAlarm()->Fire();
8010 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008011 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008012 SimulateNextPacketTooLarge();
8013 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008014 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008015 // Ack frame is not bundled in connection close packet.
8016 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008017 if (writer_->padding_frames().empty()) {
8018 EXPECT_EQ(1u, writer_->frame_count());
8019 } else {
8020 EXPECT_EQ(2u, writer_->frame_count());
8021 }
8022
fkastenholz5d880a92019-06-21 09:01:56 -07008023 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008024}
8025
rchd672c6d2019-11-27 15:30:54 -08008026TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
8027 SetQuicReloadableFlag(quic_close_all_encryptions_levels2, true);
8028
8029 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8030 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8031 connection_.CloseConnection(
8032 kQuicErrorCode, "Some random error message",
8033 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8034
8035 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8036
8037 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8038 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8039
8040 if (!connection_.version().CanSendCoalescedPackets()) {
8041 // Each connection close packet should be sent in distinct UDP packets.
8042 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8043 writer_->connection_close_packets());
8044 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8045 writer_->packets_write_attempts());
8046 return;
8047 }
8048
8049 // A single UDP packet should be sent with multiple connection close packets
8050 // coalesced together.
8051 EXPECT_EQ(1u, writer_->packets_write_attempts());
8052
8053 // Only the first packet has been processed yet.
8054 EXPECT_EQ(1u, writer_->connection_close_packets());
8055
8056 // ProcessPacket resets the visitor and frees the coalesced packet.
8057 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8058 auto packet = writer_->coalesced_packet()->Clone();
8059 writer_->framer()->ProcessPacket(*packet);
8060 EXPECT_EQ(1u, writer_->connection_close_packets());
8061 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8062}
8063
8064TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
8065 SetQuicReloadableFlag(quic_close_all_encryptions_levels2, false);
8066
8067 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8068 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8069 connection_.CloseConnection(
8070 kQuicErrorCode, "Some random error message",
8071 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8072
8073 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8074
8075 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8076 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8077 EXPECT_EQ(1u, writer_->connection_close_packets());
8078 EXPECT_EQ(1u, writer_->packets_write_attempts());
8079 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8080}
8081
QUICHE teama6ef0a62019-03-07 20:34:33 -05008082// Regression test for b/63620844.
8083TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8084 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008085 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008086 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008087
QUICHE teama6ef0a62019-03-07 20:34:33 -05008088 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008089 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008090}
8091
8092TEST_P(QuicConnectionTest, MaxPacingRate) {
8093 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8094 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8095 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8096}
8097
8098TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8099 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8100 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8101 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8102 EXPECT_EQ(CONNECTION_ID_PRESENT,
8103 writer_->last_packet_header().destination_connection_id_included);
8104
8105 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8106 QuicConfig config;
8107 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8108 connection_.SetFromConfig(config);
8109
8110 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8111 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8112 // Verify connection id is still sent in the packet.
8113 EXPECT_EQ(CONNECTION_ID_PRESENT,
8114 writer_->last_packet_header().destination_connection_id_included);
8115}
8116
8117TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8118 MockQuicConnectionDebugVisitor debug_visitor;
8119 connection_.set_debug_visitor(&debug_visitor);
8120
8121 const QuicStreamId stream_id = 2;
8122 QuicPacketNumber last_packet;
8123 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8124 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8125 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8126
8127 const QuicByteCount old_bytes_in_flight =
8128 connection_.sent_packet_manager().GetBytesInFlight();
8129
8130 // Allow 9 probing retransmissions to be sent.
8131 {
8132 InSequence seq;
8133 EXPECT_CALL(*send_algorithm_, CanSend(_))
8134 .Times(9 * 2)
8135 .WillRepeatedly(Return(true));
8136 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8137 }
8138 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8139 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008140 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008141 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008142 TransmissionType, QuicTime) {
8143 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008144 if (connection_.version().CanSendCoalescedPackets()) {
8145 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8146 // 0...).
8147 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8148 writer_->stream_frames()[0]->offset);
8149 } else {
8150 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8151 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8152 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008153 sent_count++;
8154 }));
8155 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8156 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008157 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8158 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8159 PROBING_RETRANSMISSION);
8160 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008161
8162 connection_.SendProbingRetransmissions();
8163
8164 // Ensure that the in-flight has increased.
8165 const QuicByteCount new_bytes_in_flight =
8166 connection_.sent_packet_manager().GetBytesInFlight();
8167 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8168}
8169
8170// Ensure that SendProbingRetransmissions() does not retransmit anything when
8171// there are no outstanding packets.
8172TEST_P(QuicConnectionTest,
8173 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8174 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8175
8176 MockQuicConnectionDebugVisitor debug_visitor;
8177 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008178 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008179 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8180 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008181 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8182 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8183 PROBING_RETRANSMISSION);
8184 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008185
8186 connection_.SendProbingRetransmissions();
8187}
8188
8189TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8190 const QuicTime::Delta retransmittable_on_wire_timeout =
8191 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008192 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008193 retransmittable_on_wire_timeout);
8194
8195 EXPECT_TRUE(connection_.connected());
8196 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8197 .WillRepeatedly(Return(true));
8198
8199 const char data[] = "data";
8200 size_t data_size = strlen(data);
8201 QuicStreamOffset offset = 0;
8202
8203 // Advance 5ms, send a retransmittable packet to the peer.
8204 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8205 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8206 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8207 offset += data_size;
8208 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8209 // The ping alarm is set for the ping timeout, not the shorter
8210 // retransmittable_on_wire_timeout.
8211 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8212 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008213 EXPECT_EQ(ping_delay,
8214 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008215
8216 // Advance 5ms, send a second retransmittable packet to the peer.
8217 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8218 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8219 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8220 offset += data_size;
8221 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8222
8223 // Now receive an ACK of the first packet. This should not set the
8224 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8225 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8226 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8227 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8228 QuicAckFrame frame =
8229 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8230 ProcessAckPacket(&frame);
8231 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8232 // The ping alarm is set for the ping timeout, not the shorter
8233 // retransmittable_on_wire_timeout.
8234 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8235 // The ping alarm has a 1 second granularity, and the clock has been advanced
8236 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008237 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8238 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008239
8240 // Now receive an ACK of the second packet. This should set the
8241 // retransmittable-on-wire alarm now that no retransmittable packets are on
8242 // the wire.
8243 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8244 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8245 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8246 ProcessAckPacket(&frame);
8247 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008248 EXPECT_EQ(retransmittable_on_wire_timeout,
8249 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008250
8251 // Now receive a duplicate ACK of the second packet. This should not update
8252 // the ping alarm.
8253 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8254 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8255 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8256 ProcessAckPacket(&frame);
8257 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8258 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8259
8260 // Now receive a non-ACK packet. This should not update the ping alarm.
8261 prev_deadline = connection_.GetPingAlarm()->deadline();
8262 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8263 ProcessPacket(4);
8264 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8265 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8266
8267 // Simulate the alarm firing and check that a PING is sent.
8268 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8269 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8270 }));
8271 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008272 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008273 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008274 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008275 } else {
nharper55fa6132019-05-07 19:37:21 -07008276 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008277 }
8278 ASSERT_EQ(1u, writer_->ping_frames().size());
8279}
8280
8281TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8282 const QuicTime::Delta retransmittable_on_wire_timeout =
8283 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008284 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008285 retransmittable_on_wire_timeout);
8286
8287 EXPECT_TRUE(connection_.connected());
8288 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8289 .WillRepeatedly(Return(true));
8290
8291 const char data[] = "data";
8292 size_t data_size = strlen(data);
8293 QuicStreamOffset offset = 0;
8294
8295 // Advance 5ms, send a retransmittable packet to the peer.
8296 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8297 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8298 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8299 offset += data_size;
8300 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8301 // The ping alarm is set for the ping timeout, not the shorter
8302 // retransmittable_on_wire_timeout.
8303 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8304 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008305 EXPECT_EQ(ping_delay,
8306 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008307
8308 // Now receive an ACK of the first packet. This should set the
8309 // retransmittable-on-wire alarm now that no retransmittable packets are on
8310 // the wire.
8311 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8312 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8313 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8314 QuicAckFrame frame =
8315 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8316 ProcessAckPacket(&frame);
8317 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008318 EXPECT_EQ(retransmittable_on_wire_timeout,
8319 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008320
8321 // Before the alarm fires, send another retransmittable packet. This should
8322 // cancel the retransmittable-on-wire alarm since now there's a
8323 // retransmittable packet on the wire.
8324 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8325 offset += data_size;
8326 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8327
8328 // Now receive an ACK of the second packet. This should set the
8329 // retransmittable-on-wire alarm now that no retransmittable packets are on
8330 // the wire.
8331 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8332 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8333 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8334 ProcessAckPacket(&frame);
8335 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008336 EXPECT_EQ(retransmittable_on_wire_timeout,
8337 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008338
8339 // Simulate the alarm firing and check that a PING is sent.
8340 writer_->Reset();
8341 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8342 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8343 }));
8344 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008345 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008346 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008347 // Do not ACK acks.
8348 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008349 } else {
nharper55fa6132019-05-07 19:37:21 -07008350 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008351 }
8352 ASSERT_EQ(1u, writer_->ping_frames().size());
8353}
8354
zhongyi79ace162019-10-21 15:57:09 -07008355// When there is no stream data received but are open streams, send the
8356// first few consecutive pings with aggressive retransmittable-on-wire
8357// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8358// afterwards until it exceeds the default ping timeout.
8359TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8360 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8361 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8362 max_aggressive_retransmittable_on_wire_ping_count);
8363 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8364 QuicTime::Delta::FromMilliseconds(200);
8365 connection_.set_initial_retransmittable_on_wire_timeout(
8366 initial_retransmittable_on_wire_timeout);
8367
8368 EXPECT_TRUE(connection_.connected());
8369 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8370 .WillRepeatedly(Return(true));
8371
8372 const char data[] = "data";
8373 // Advance 5ms, send a retransmittable data packet to the peer.
8374 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8375 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8376 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8377 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8378 // The ping alarm is set for the ping timeout, not the shorter
8379 // retransmittable_on_wire_timeout.
8380 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8381 EXPECT_EQ(connection_.ping_timeout(),
8382 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8383
8384 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8385 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8386 .Times(AnyNumber());
8387
8388 // Verify that the first few consecutive retransmittable on wire pings are
8389 // sent with aggressive timeout.
8390 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8391 // Receive an ACK of the previous packet. This should set the ping alarm
8392 // with the initial retransmittable-on-wire timeout.
8393 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8394 QuicPacketNumber ack_num = creator_->packet_number();
8395 QuicAckFrame frame = InitAckFrame(
8396 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8397 ProcessAckPacket(&frame);
8398 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8399 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8400 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8401 // Simulate the alarm firing and check that a PING is sent.
8402 writer_->Reset();
8403 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8404 SendPing();
8405 }));
8406 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8407 connection_.GetPingAlarm()->Fire();
8408 }
8409
8410 QuicTime::Delta retransmittable_on_wire_timeout =
8411 initial_retransmittable_on_wire_timeout;
8412
8413 // Verify subsequent pings are sent with timeout that is exponentially backed
8414 // off.
8415 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8416 // Receive an ACK for the previous PING. This should set the
8417 // ping alarm with backed off retransmittable-on-wire timeout.
8418 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8419 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8420 QuicPacketNumber ack_num = creator_->packet_number();
8421 QuicAckFrame frame = InitAckFrame(
8422 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8423 ProcessAckPacket(&frame);
8424 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8425 EXPECT_EQ(retransmittable_on_wire_timeout,
8426 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8427
8428 // Simulate the alarm firing and check that a PING is sent.
8429 writer_->Reset();
8430 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8431 SendPing();
8432 }));
8433 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8434 connection_.GetPingAlarm()->Fire();
8435 }
8436
8437 // The ping alarm is set with default ping timeout.
8438 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8439 EXPECT_EQ(connection_.ping_timeout(),
8440 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8441
8442 // Receive an ACK for the previous PING. The ping alarm is set with an
8443 // earlier deadline.
8444 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8445 QuicPacketNumber ack_num = creator_->packet_number();
8446 QuicAckFrame frame = InitAckFrame(
8447 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8448 ProcessAckPacket(&frame);
8449 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8450 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8451 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8452}
8453
8454// This test verify that the count of consecutive aggressive pings is reset
8455// when new data is received. And it also verifies the connection resets
8456// the exponential back-off of the retransmittable-on-wire ping timeout
8457// after receiving new stream data.
8458TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8459 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8460 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8461 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8462 QuicTime::Delta::FromMilliseconds(200);
8463 connection_.set_initial_retransmittable_on_wire_timeout(
8464 initial_retransmittable_on_wire_timeout);
8465
8466 EXPECT_TRUE(connection_.connected());
8467 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8468 .WillRepeatedly(Return(true));
8469 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8470 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8471 .Times(AnyNumber());
8472
8473 const char data[] = "data";
8474 // Advance 5ms, send a retransmittable data packet to the peer.
8475 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8476 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8477 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8478 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8479 // The ping alarm is set for the ping timeout, not the shorter
8480 // retransmittable_on_wire_timeout.
8481 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8482 EXPECT_EQ(connection_.ping_timeout(),
8483 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8484
8485 // Receive an ACK of the first packet. This should set the ping alarm with
8486 // initial retransmittable-on-wire timeout since there is no retransmittable
8487 // packet on the wire.
8488 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8489 QuicAckFrame frame =
8490 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8491 ProcessAckPacket(&frame);
8492 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8493 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8494 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8495
8496 // Simulate the alarm firing and check that a PING is sent.
8497 writer_->Reset();
8498 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8499 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8500 connection_.GetPingAlarm()->Fire();
8501
8502 // Receive an ACK for the previous PING. Ping alarm will be set with
8503 // aggressive timeout.
8504 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8505 QuicPacketNumber ack_num = creator_->packet_number();
8506 frame = InitAckFrame(
8507 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8508 ProcessAckPacket(&frame);
8509 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8510 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8511 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8512
8513 // Process a data packet.
8514 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8515 ProcessDataPacket(peer_creator_.packet_number() + 1);
8516 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8517 peer_creator_.packet_number() + 1);
8518 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8519 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8520
8521 // Verify the count of consecutive aggressive pings is reset.
8522 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8523 // Receive an ACK of the previous packet. This should set the ping alarm
8524 // with the initial retransmittable-on-wire timeout.
8525 QuicPacketNumber ack_num = creator_->packet_number();
8526 QuicAckFrame frame = InitAckFrame(
8527 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8528 ProcessAckPacket(&frame);
8529 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8530 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8531 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8532 // Simulate the alarm firing and check that a PING is sent.
8533 writer_->Reset();
8534 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8535 SendPing();
8536 }));
8537 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8538 connection_.GetPingAlarm()->Fire();
8539 // Advance 5ms to receive next packet.
8540 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8541 }
8542
8543 // Receive another ACK for the previous PING. This should set the
8544 // ping alarm with backed off retransmittable-on-wire timeout.
8545 ack_num = creator_->packet_number();
8546 frame = InitAckFrame(
8547 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8548 ProcessAckPacket(&frame);
8549 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8550 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8551 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8552
8553 writer_->Reset();
8554 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8555 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8556 connection_.GetPingAlarm()->Fire();
8557
8558 // Process another data packet and a new ACK packet. The ping alarm is set
8559 // with aggressive ping timeout again.
8560 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8561 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8562 ProcessDataPacket(peer_creator_.packet_number() + 1);
8563 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8564 peer_creator_.packet_number() + 1);
8565 ack_num = creator_->packet_number();
8566 frame = InitAckFrame(
8567 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8568 ProcessAckPacket(&frame);
8569 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8570 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8571 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8572}
8573
QUICHE teama6ef0a62019-03-07 20:34:33 -05008574TEST_P(QuicConnectionTest, OnForwardProgressConfirmed) {
8575 EXPECT_CALL(visitor_, OnForwardProgressConfirmed()).Times(Exactly(0));
8576 EXPECT_TRUE(connection_.connected());
8577
8578 const char data[] = "data";
8579 size_t data_size = strlen(data);
8580 QuicStreamOffset offset = 0;
8581
8582 // Send two packets.
8583 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8584 offset += data_size;
8585 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8586 offset += data_size;
8587
8588 // Ack packet 1. This increases the largest_acked to 1, so
8589 // OnForwardProgressConfirmed() should be called
8590 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8591 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8592 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8593 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8594 QuicAckFrame frame =
8595 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8596 ProcessAckPacket(&frame);
8597
8598 // Ack packet 1 again. largest_acked remains at 1, so
8599 // OnForwardProgressConfirmed() should not be called.
8600 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8601 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8602 ProcessAckPacket(&frame);
8603
8604 // Ack packet 2. This increases the largest_acked to 2, so
8605 // OnForwardProgressConfirmed() should be called.
8606 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8607 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8608 EXPECT_CALL(visitor_, OnForwardProgressConfirmed());
8609 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8610 ProcessAckPacket(&frame);
8611}
8612
8613TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8614 const QuicUint128 kTestToken = 1010101;
8615 const QuicUint128 kWrongTestToken = 1010100;
8616 QuicConfig config;
8617 // No token has been received.
8618 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8619
8620 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8621 // Token is different from received token.
8622 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8623 connection_.SetFromConfig(config);
8624 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8625
8626 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8627 connection_.SetFromConfig(config);
8628 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8629}
8630
8631TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8632 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08008633 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008634 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08008635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008636 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8637 // This causes connection to be closed because packet 1 has not been sent yet.
8638 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08008639 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008640 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08008641 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008642}
8643
8644TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008645 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008646 return;
8647 }
ianswettb239f862019-04-05 09:15:06 -07008648 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08008649 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008650 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8651 {
fayanga4b37b22019-06-18 13:37:47 -07008652 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008653 connection_.SendStreamData3();
8654 // Send a message which cannot fit into current open packet, and 2 packets
8655 // get sent, one contains stream frame, and the other only contains the
8656 // message frame.
8657 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08008658 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8659 connection_.SendMessage(
8660 1,
8661 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08008662 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08008663 message_data.data(),
8664 connection_.GetCurrentLargestMessagePayload()),
8665 &storage),
8666 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008667 }
8668 // Fail to send a message if connection is congestion control blocked.
8669 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08008670 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8671 connection_.SendMessage(
8672 2,
8673 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
8674 "message", &storage),
8675 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008676
8677 // Always fail to send a message which cannot fit into one packet.
8678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08008679 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8680 connection_.SendMessage(
8681 3,
8682 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08008683 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08008684 message_data.data(),
8685 connection_.GetCurrentLargestMessagePayload() + 1),
8686 &storage),
8687 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008688}
8689
8690// Test to check that the path challenge/path response logic works
8691// correctly. This test is only for version-99
8692TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07008693 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008694 return;
8695 }
8696 // First check if we can probe from server to client and back
8697 set_perspective(Perspective::IS_SERVER);
8698 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8699
8700 // Create and send the probe request (PATH_CHALLENGE frame).
8701 // SendConnectivityProbingPacket ends up calling
8702 // TestPacketWriter::WritePacket() which in turns receives and parses the
8703 // packet by calling framer_.ProcessPacket() -- which in turn calls
8704 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8705 // the packet in writer_->path_challenge_frames()
8706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8707 connection_.SendConnectivityProbingPacket(writer_.get(),
8708 connection_.peer_address());
8709 // Save the random contents of the challenge for later comparison to the
8710 // response.
nharper55fa6132019-05-07 19:37:21 -07008711 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008712 QuicPathFrameBuffer challenge_data =
8713 writer_->path_challenge_frames().front().data_buffer;
8714
8715 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8716 // called and it will perform actions to ensure that the rest of the protocol
8717 // is performed (specifically, call UpdatePacketContent to say that this is a
8718 // path challenge so that when QuicConnection::OnPacketComplete is called
8719 // (again, out of the framer), the response is generated). Simulate those
8720 // calls so that the right internal state is set up for generating
8721 // the response.
8722 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8723 writer_->path_challenge_frames().front()));
8724 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8725 // Cause the response to be created and sent. Result is that the response
8726 // should be stashed in writer's path_response_frames.
8727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8728 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
8729
8730 // The final check is to ensure that the random data in the response matches
8731 // the random data from the challenge.
8732 EXPECT_EQ(0, memcmp(&challenge_data,
8733 &(writer_->path_response_frames().front().data_buffer),
8734 sizeof(challenge_data)));
8735}
8736
8737// Regression test for b/110259444
8738TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8740 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8741 writer_->SetWriteBlocked();
8742
8743 ProcessPacket(1);
8744 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
8745 // Verify ack alarm is set.
8746 EXPECT_TRUE(ack_alarm->IsSet());
8747 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8748 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8749 connection_.GetAckAlarm()->Fire();
8750
8751 writer_->SetWritable();
8752 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8753 ProcessPacket(2);
8754 // Verify ack alarm is not set.
8755 EXPECT_FALSE(ack_alarm->IsSet());
8756}
8757
8758TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8759 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8760 writer_->set_supports_release_time(true);
8761 QuicConfig config;
8762 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8763 connection_.SetFromConfig(config);
8764 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8765
8766 QuicTagVector connection_options;
8767 connection_options.push_back(kNPCO);
8768 config.SetConnectionOptionsToSend(connection_options);
8769 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8770 connection_.SetFromConfig(config);
8771 // Verify pacing offload is disabled.
8772 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8773}
8774
8775// Regression test for b/110259444
8776// Get a path response without having issued a path challenge...
8777TEST_P(QuicConnectionTest, OrphanPathResponse) {
8778 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8779
8780 QuicPathResponseFrame frame(99, data);
8781 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8782 // If PATH_RESPONSE was accepted (payload matches the payload saved
8783 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8784 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8785 // Since this PATH_RESPONSE does not match, current_packet_content_
8786 // must not be FIRST_FRAME_IS_PING.
8787 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8788 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8789}
8790
8791// Regression test for b/120791670
8792TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8793 // This test mimics a problematic scenario where an IETF QUIC connection
8794 // receives a Google QUIC packet and continue processing it using Google QUIC
8795 // wire format.
fayangd4291e42019-05-30 10:31:21 -07008796 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008797 return;
8798 }
8799 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07008800 QuicFrame frame;
8801 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8802 frame = QuicFrame(&crypto_frame_);
8803 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8804 } else {
8805 frame = QuicFrame(QuicStreamFrame(
8806 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08008807 0u, quiche::QuicheStringPiece()));
nharper46833c32019-05-15 21:33:05 -07008808 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8809 }
nharper46833c32019-05-15 21:33:05 -07008810 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008811
8812 // Let connection process a Google QUIC packet.
8813 peer_framer_.set_version_for_tests(
8814 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07008815 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07008816 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07008817 char buffer[kMaxOutgoingPacketSize];
8818 size_t encrypted_length =
8819 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8820 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008821 // Make sure no stream frame is processed.
8822 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8823 connection_.ProcessUdpPacket(
8824 kSelfAddress, kPeerAddress,
8825 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8826
8827 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8828 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8829}
8830
8831TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07008832 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008833 return;
8834 }
8835 // Set first_sending_packet_number to be 0 to allow successfully processing
8836 // acks which ack packet number 0.
8837 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8839
8840 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07008841 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8842 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008843
8844 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07008845 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8846 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008847
8848 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07008849 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8850 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008851}
8852
QUICHE teamcd098022019-03-22 18:49:55 -07008853TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8854 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8855 return;
8856 }
8857 use_tagging_decrypter();
8858 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008859 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008860
8861 connection_.SendCryptoStreamData();
8862 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8863 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8864 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8866 QuicAckFrame frame1 = InitAckFrame(1);
8867 // Received ACK for packet 1.
8868 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8869
8870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8871 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8872 NO_FIN);
8873 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8874 NO_FIN);
8875 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8876 8, NO_FIN);
8877 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8878 12, FIN);
8879 // Received ACK for packets 2, 4, 5.
8880 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8881 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8883 QuicAckFrame frame2 =
8884 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8885 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8886 // Make sure although the same packet number is used, but they are in
8887 // different packet number spaces.
8888 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8889}
8890
8891TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8892 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8893 return;
8894 }
8895 use_tagging_decrypter();
8896 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008897 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07008898 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8899 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07008900
8901 connection_.SendCryptoStreamData();
8902 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8903 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8904 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8906 QuicAckFrame frame1 = InitAckFrame(1);
8907 // Received ACK for packet 1.
8908 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8909
8910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8911 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8912 NO_FIN);
8913 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8914 NO_FIN);
8915
8916 // Received ACK for packets 2 and 3 in wrong packet number space.
8917 QuicAckFrame invalid_ack =
8918 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07008919 EXPECT_CALL(visitor_,
8920 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07008921 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07008922 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07008923 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07008924}
8925
8926TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8927 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8928 return;
8929 }
8930 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008931 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8932 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8933 }
QUICHE teamcd098022019-03-22 18:49:55 -07008934 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8935 use_tagging_decrypter();
8936 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008937 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE teamcd098022019-03-22 18:49:55 -07008938 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8939 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008940 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008941 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008942 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008943 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008944 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008945 // Receives packet 1000 in application data.
8946 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8947 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8948 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8949 NO_FIN);
8950 // Verify application data ACK gets bundled with outgoing data.
8951 EXPECT_EQ(2u, writer_->frame_count());
8952 // Make sure ACK alarm is still set because initial data is not ACKed.
8953 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8954 // Receive packet 1001 in application data.
8955 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
8956 clock_.AdvanceTime(DefaultRetransmissionTime());
8957 // Simulates ACK alarm fires and verify two ACKs are flushed.
8958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8959 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008960 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008961 connection_.GetAckAlarm()->Fire();
8962 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8963 // Receives more packets in application data.
8964 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
8965 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8966
8967 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008968 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008969 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07008970 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07008971 // Verify zero rtt and forward secure packets get acked in the same packet.
8972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07008973 ProcessDataPacket(1003);
QUICHE teamcd098022019-03-22 18:49:55 -07008974 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
8975}
8976
QUICHE team552f71f2019-03-23 15:37:59 -07008977TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
8978 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8979 return;
8980 }
8981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07008982 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8983 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8984 }
QUICHE team552f71f2019-03-23 15:37:59 -07008985 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8986 use_tagging_decrypter();
8987 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07008988 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
QUICHE team552f71f2019-03-23 15:37:59 -07008989 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8990 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008991 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07008992 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07008993 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008994 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07008995 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07008996 // Receives packet 1000 in application data.
8997 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
8998 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
8999
9000 writer_->SetWriteBlocked();
9001 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9002 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9003 // blocked.
9004 clock_.AdvanceTime(DefaultDelayedAckTime());
9005 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9006 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009007 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009008 connection_.GetAckAlarm()->Fire();
9009 // Verify ACK alarm is not set.
9010 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9011
9012 writer_->SetWritable();
9013 // Verify 2 ACKs are sent when connection gets unblocked.
9014 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9015 connection_.OnCanWrite();
9016 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
9017}
9018
dschinazi346b7ce2019-06-05 01:38:18 -07009019// Make sure a packet received with the right client connection ID is processed.
9020TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009021 if (!framer_.version().SupportsClientConnectionIds()) {
9022 return;
9023 }
9024 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9025 connection_.set_client_connection_id(TestConnectionId(0x33));
9026 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9027 header.destination_connection_id = TestConnectionId(0x33);
9028 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9029 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9030 QuicFrames frames;
9031 QuicPingFrame ping_frame;
9032 QuicPaddingFrame padding_frame;
9033 frames.push_back(QuicFrame(ping_frame));
9034 frames.push_back(QuicFrame(padding_frame));
9035 std::unique_ptr<QuicPacket> packet =
9036 BuildUnsizedDataPacket(&framer_, header, frames);
9037 char buffer[kMaxOutgoingPacketSize];
9038 size_t encrypted_length = peer_framer_.EncryptPayload(
9039 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9040 kMaxOutgoingPacketSize);
9041 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9042 false);
9043 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9044 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9045 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9046}
9047
9048// Make sure a packet received with a different client connection ID is dropped.
9049TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009050 if (!framer_.version().SupportsClientConnectionIds()) {
9051 return;
9052 }
9053 connection_.set_client_connection_id(TestConnectionId(0x33));
9054 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9055 header.destination_connection_id = TestConnectionId(0xbad);
9056 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9057 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9058 QuicFrames frames;
9059 QuicPingFrame ping_frame;
9060 QuicPaddingFrame padding_frame;
9061 frames.push_back(QuicFrame(ping_frame));
9062 frames.push_back(QuicFrame(padding_frame));
9063 std::unique_ptr<QuicPacket> packet =
9064 BuildUnsizedDataPacket(&framer_, header, frames);
9065 char buffer[kMaxOutgoingPacketSize];
9066 size_t encrypted_length = peer_framer_.EncryptPayload(
9067 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9068 kMaxOutgoingPacketSize);
9069 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9070 false);
9071 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9072 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9073 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9074}
9075
9076// Make sure the first packet received with a different client connection ID on
9077// the server is processed and it changes the client connection ID.
9078TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009079 if (!framer_.version().SupportsClientConnectionIds()) {
9080 return;
9081 }
dschinazi346b7ce2019-06-05 01:38:18 -07009082 set_perspective(Perspective::IS_SERVER);
9083 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9084 header.source_connection_id = TestConnectionId(0x33);
9085 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9086 QuicFrames frames;
9087 QuicPingFrame ping_frame;
9088 QuicPaddingFrame padding_frame;
9089 frames.push_back(QuicFrame(ping_frame));
9090 frames.push_back(QuicFrame(padding_frame));
9091 std::unique_ptr<QuicPacket> packet =
9092 BuildUnsizedDataPacket(&framer_, header, frames);
9093 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009094 size_t encrypted_length =
9095 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9096 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009097 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9098 false);
9099 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9100 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9101 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9102 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9103}
9104
fayang40ec3ac2019-06-05 09:07:54 -07009105// Regression test for b/134416344.
9106TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9107 // This test mimics a scenario where a connection processes 2 packets and the
9108 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9109 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9110 // because connection is disconnected.
9111 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009112 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009113 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009114 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009115 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009116 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9117 "",
9118 /*transport_close_frame_type=*/0));
9119
fayang40ec3ac2019-06-05 09:07:54 -07009120 // Received 2 packets.
9121 QuicFrame frame;
9122 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9123 frame = QuicFrame(&crypto_frame_);
9124 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9125 } else {
9126 frame = QuicFrame(QuicStreamFrame(
9127 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
dmcardlecf0bfcf2019-12-13 08:08:21 -08009128 0u, quiche::QuicheStringPiece()));
fayang40ec3ac2019-06-05 09:07:54 -07009129 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9130 }
9131 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
9132 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
9133 EXPECT_TRUE(ack_alarm->IsSet());
9134 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.get()),
9135 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009136 // Verify ack alarm is not set.
9137 EXPECT_FALSE(ack_alarm->IsSet());
fayang40ec3ac2019-06-05 09:07:54 -07009138}
9139
dschinazi8d551132019-08-02 19:17:16 -07009140// Verify that a packet containing three coalesced packets is parsed correctly.
9141TEST_P(QuicConnectionTest, CoalescedPacket) {
9142 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9143 // Coalesced packets can only be encoded using long header lengths.
9144 return;
9145 }
9146 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9147 EXPECT_TRUE(connection_.connected());
9148 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9149 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9150 } else {
9151 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9152 }
9153
9154 uint64_t packet_numbers[3] = {1, 2, 3};
9155 EncryptionLevel encryption_levels[3] = {
9156 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9157 char buffer[kMaxOutgoingPacketSize] = {};
9158 size_t total_encrypted_length = 0;
9159 for (int i = 0; i < 3; i++) {
9160 QuicPacketHeader header =
9161 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9162 QuicFrames frames;
9163 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9164 frames.push_back(QuicFrame(&crypto_frame_));
9165 } else {
9166 frames.push_back(QuicFrame(frame1_));
9167 }
9168 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9169 peer_creator_.set_encryption_level(encryption_levels[i]);
9170 size_t encrypted_length = peer_framer_.EncryptPayload(
9171 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9172 buffer + total_encrypted_length,
9173 sizeof(buffer) - total_encrypted_length);
9174 EXPECT_GT(encrypted_length, 0u);
9175 total_encrypted_length += encrypted_length;
9176 }
9177 connection_.ProcessUdpPacket(
9178 kSelfAddress, kPeerAddress,
9179 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9180 if (connection_.GetSendAlarm()->IsSet()) {
9181 connection_.GetSendAlarm()->Fire();
9182 }
9183
9184 EXPECT_TRUE(connection_.connected());
9185}
9186
dschinazi66fc0242019-08-16 10:00:25 -07009187// Regression test for crbug.com/992831.
9188TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9189 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9190 // Coalesced packets can only be encoded using long header lengths.
9191 return;
9192 }
9193 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9194 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9195 return;
9196 }
9197 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9198 EXPECT_TRUE(connection_.connected());
9199 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9200 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9201 .Times(3)
9202 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9203 // QuicFrame takes ownership of the QuicBlockedFrame.
9204 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9205 });
9206 } else {
9207 EXPECT_CALL(visitor_, OnStreamFrame(_))
9208 .Times(3)
9209 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9210 // QuicFrame takes ownership of the QuicBlockedFrame.
9211 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9212 });
9213 }
9214
9215 uint64_t packet_numbers[3] = {1, 2, 3};
9216 EncryptionLevel encryption_levels[3] = {
9217 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9218 char buffer[kMaxOutgoingPacketSize] = {};
9219 size_t total_encrypted_length = 0;
9220 for (int i = 0; i < 3; i++) {
9221 QuicPacketHeader header =
9222 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9223 QuicFrames frames;
9224 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9225 frames.push_back(QuicFrame(&crypto_frame_));
9226 } else {
9227 frames.push_back(QuicFrame(frame1_));
9228 }
9229 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9230 peer_creator_.set_encryption_level(encryption_levels[i]);
9231 size_t encrypted_length = peer_framer_.EncryptPayload(
9232 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9233 buffer + total_encrypted_length,
9234 sizeof(buffer) - total_encrypted_length);
9235 EXPECT_GT(encrypted_length, 0u);
9236 total_encrypted_length += encrypted_length;
9237 }
9238 connection_.ProcessUdpPacket(
9239 kSelfAddress, kPeerAddress,
9240 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9241 if (connection_.GetSendAlarm()->IsSet()) {
9242 connection_.GetSendAlarm()->Fire();
9243 }
9244
9245 EXPECT_TRUE(connection_.connected());
9246
9247 SendAckPacketToPeer();
9248}
9249
fayangd3016832019-08-08 07:24:45 -07009250// Regresstion test for b/138962304.
9251TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009252 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9253
9254 QuicStreamId stream_id = 2;
9255 QuicPacketNumber last_data_packet;
9256 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9257 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9258
9259 // Writer gets blocked.
9260 writer_->SetWriteBlocked();
9261
9262 // Cancel the stream.
9263 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9264 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009265 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9266 .WillRepeatedly(
9267 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009268 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9269
9270 // Retransmission timer fires in RTO mode.
9271 connection_.GetRetransmissionAlarm()->Fire();
9272 // Verify no packets get flushed when writer is blocked.
9273 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9274}
9275
9276// Regresstion test for b/138962304.
9277TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009278 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9279 connection_.SetMaxTailLossProbes(1);
9280
9281 QuicStreamId stream_id = 2;
9282 QuicPacketNumber last_data_packet;
9283 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9284 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9285 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9286
9287 // Writer gets blocked.
9288 writer_->SetWriteBlocked();
9289
9290 // Cancel stream 2.
9291 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9292 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9293 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9294
fayange62e63c2019-12-04 07:16:25 -08009295 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009296 // Retransmission timer fires in TLP mode.
9297 connection_.GetRetransmissionAlarm()->Fire();
9298 // Verify one packets is forced flushed when writer is blocked.
9299 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9300}
9301
fayang67f82272019-08-14 16:08:45 -07009302// Regresstion test for b/139375344.
9303TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009304 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009305 return;
9306 }
9307 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9308 connection_.SetMaxTailLossProbes(2);
9309 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9310 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9311
9312 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9313 QuicTime retransmission_time =
9314 connection_.GetRetransmissionAlarm()->deadline();
9315 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9316 // TLP fires.
9317 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9318 clock_.AdvanceTime(retransmission_time - clock_.Now());
9319 connection_.GetRetransmissionAlarm()->Fire();
9320 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9321 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9322 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9323
9324 // Packet 1 gets acked.
9325 QuicAckFrame frame = InitAckFrame(1);
9326 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9327 ProcessAckPacket(1, &frame);
9328 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9329 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9330
9331 // RTO fires, verify a PING packet gets sent because there is no data to send.
9332 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9333 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9334 clock_.AdvanceTime(retransmission_time - clock_.Now());
9335 connection_.GetRetransmissionAlarm()->Fire();
9336 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9337 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9338 EXPECT_EQ(1u, writer_->ping_frames().size());
9339}
9340
fayangce0a3162019-08-15 09:05:36 -07009341TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009342 QuicConfig config;
9343 QuicTagVector connection_options;
9344 connection_options.push_back(k2PTO);
9345 config.SetConnectionOptionsToSend(connection_options);
9346 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9347 connection_.SetFromConfig(config);
9348 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9349
9350 QuicStreamId stream_id = 2;
9351 QuicPacketNumber last_packet;
9352 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9353 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9354 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9355
9356 // Reset stream.
9357 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9358 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9359
9360 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9361 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9362 connection_.GetRetransmissionAlarm()->Fire();
9363 EXPECT_EQ(0u, writer_->stream_frames().size());
9364 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9365 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9366}
9367
fayang97ce41e2019-10-07 08:37:29 -07009368TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009369 QuicConfig config;
9370 QuicTagVector connection_options;
9371 connection_options.push_back(k1PTO);
9372 connection_options.push_back(k6PTO);
9373 config.SetConnectionOptionsToSend(connection_options);
9374 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9375 connection_.SetFromConfig(config);
9376 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9377
9378 // Send stream data.
9379 SendStreamDataToPeer(
9380 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9381 0, FIN, nullptr);
9382
9383 // 5PTO + 1 connection close.
rch39c88ab2019-10-16 19:24:40 -07009384 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(6));
fayang97ce41e2019-10-07 08:37:29 -07009385
9386 // Fire the retransmission alarm 5 times.
9387 for (int i = 0; i < 5; ++i) {
9388 connection_.GetRetransmissionAlarm()->Fire();
9389 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9390 EXPECT_TRUE(connection_.connected());
9391 }
9392
9393 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9394 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9395 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9396 // Closes connection on 6th PTO.
9397 EXPECT_CALL(visitor_,
9398 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9399 connection_.GetRetransmissionAlarm()->Fire();
9400 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9401 EXPECT_FALSE(connection_.connected());
9402 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9403}
9404
fayangce0a3162019-08-15 09:05:36 -07009405TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009406 QuicConfig config;
9407 QuicTagVector connection_options;
9408 connection_options.push_back(k2PTO);
9409 connection_options.push_back(k7PTO);
9410 config.SetConnectionOptionsToSend(connection_options);
9411 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9412 connection_.SetFromConfig(config);
9413 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9414
9415 // Send stream data.
9416 SendStreamDataToPeer(
9417 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9418 0, FIN, nullptr);
9419
9420 // Fire the retransmission alarm 6 times.
9421 for (int i = 0; i < 6; ++i) {
9422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9423 connection_.GetRetransmissionAlarm()->Fire();
9424 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9425 EXPECT_TRUE(connection_.connected());
9426 }
9427
9428 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9429 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9430 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9431 // Closes connection on 7th PTO.
9432 EXPECT_CALL(visitor_,
9433 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangce0a3162019-08-15 09:05:36 -07009435 connection_.GetRetransmissionAlarm()->Fire();
9436 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9437 EXPECT_FALSE(connection_.connected());
9438 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9439}
9440
9441TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009442 QuicConfig config;
9443 QuicTagVector connection_options;
9444 connection_options.push_back(k2PTO);
9445 connection_options.push_back(k8PTO);
9446 config.SetConnectionOptionsToSend(connection_options);
9447 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9448 connection_.SetFromConfig(config);
9449 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9450
9451 // Send stream data.
9452 SendStreamDataToPeer(
9453 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9454 0, FIN, nullptr);
9455
9456 // Fire the retransmission alarm 7 times.
9457 for (int i = 0; i < 7; ++i) {
9458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9459 connection_.GetRetransmissionAlarm()->Fire();
9460 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9461 EXPECT_TRUE(connection_.connected());
9462 }
9463
9464 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9465 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9466 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9467 // Closes connection on 8th PTO.
9468 EXPECT_CALL(visitor_,
9469 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayangce0a3162019-08-15 09:05:36 -07009471 connection_.GetRetransmissionAlarm()->Fire();
9472 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9473 EXPECT_FALSE(connection_.connected());
9474 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9475}
9476
fayang5f135052019-08-22 17:59:40 -07009477TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9478 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9479 return;
9480 }
9481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9482 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9483
9484 // Send CHLO.
9485 connection_.SendCryptoStreamData();
9486 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9487
9488 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9489 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9491 QuicAckFrame frame1 = InitAckFrame(1);
9492 // Received ACK for packet 1.
9493 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9494
9495 // Verify retransmission alarm is still set because handshake is not
9496 // confirmed although there is nothing in flight.
9497 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9498 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9499 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9500
9501 // PTO fires, verify a PING packet gets sent because there is no data to send.
9502 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9503 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9504 connection_.GetRetransmissionAlarm()->Fire();
9505 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9506 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9507 EXPECT_EQ(1u, writer_->ping_frames().size());
9508}
9509
9510TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
9511 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9512 return;
9513 }
fayang5f135052019-08-22 17:59:40 -07009514 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9515
9516 set_perspective(Perspective::IS_SERVER);
9517 // Verify no data can be sent at the beginning because bytes received is 0.
9518 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9519 connection_.SendCryptoDataWithString("foo", 0);
9520 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9521
9522 // Receives packet 1.
9523 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9524
9525 const size_t anti_amplification_factor =
9526 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
9527 // Verify now packets can be sent.
9528 for (size_t i = 0; i < anti_amplification_factor; ++i) {
9529 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9530 connection_.SendCryptoDataWithString("foo", i * 3);
9531 // Verify retransmission alarm is not set if throttled by anti-amplification
9532 // limit.
9533 EXPECT_EQ(i != anti_amplification_factor - 1,
9534 connection_.GetRetransmissionAlarm()->IsSet());
9535 }
9536 // Verify server is throttled by anti-amplification limit.
9537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9538 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9539
9540 // Receives packet 2.
9541 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9542 // Verify more packets can be sent.
9543 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
9544 ++i) {
9545 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9546 connection_.SendCryptoDataWithString("foo", i * 3);
9547 }
9548 // Verify server is throttled by anti-amplification limit.
9549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9550 connection_.SendCryptoDataWithString("foo",
9551 2 * anti_amplification_factor * 3);
9552
9553 ProcessPacket(3);
9554 // Verify anti-amplification limit is gone after address validation.
9555 for (size_t i = 0; i < 100; ++i) {
9556 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9557 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9558 }
9559}
9560
fkastenholza3660102019-08-28 05:19:24 -07009561TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9562 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9563 // Test relevent only for IETF QUIC.
9564 return;
9565 }
9566 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9567 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9568 // which might be associated with the processing of a known frame type.
9569 const uint64_t kTransportCloseFrameType = 9999u;
9570 QuicFramerPeer::set_current_received_frame_type(
9571 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9572 // Do a transport connection close
9573 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9574 connection_.CloseConnection(
9575 kQuicErrorCode, "Some random error message",
9576 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9577 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9578 writer_->connection_close_frames();
9579 ASSERT_EQ(1u, connection_close_frames.size());
9580 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9581 connection_close_frames[0].close_type);
9582 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].extracted_error_code);
9583 EXPECT_EQ(kTransportCloseFrameType,
9584 connection_close_frames[0].transport_close_frame_type);
9585}
9586
fayang0fcbf352019-08-30 11:15:58 -07009587// Regression test for b/137401387 and b/138962304.
9588TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -07009589 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -07009590 return;
9591 }
9592 connection_.SetMaxTailLossProbes(1);
9593 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9594 std::string stream_data(3000, 's');
9595 // Send packets 1 - 66 and exhaust cwnd.
9596 for (size_t i = 0; i < 22; ++i) {
9597 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
9598 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
9599 }
9600 CongestionBlockWrites();
9601
9602 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
9603 // compared to packet 1 because packet number length increases.
9604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
9605 connection_.GetRetransmissionAlarm()->Fire();
9606 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
9607 // packet 2 gets RTOed to two packets because packet number length increases.
9608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
9609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
9610 connection_.GetRetransmissionAlarm()->Fire();
9611
9612 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9613 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
9614 // only one containing retransmittable frames.
9615 for (size_t i = 1; i < 22; ++i) {
9616 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
9617 }
9618 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9619 QuicAckFrame frame =
9620 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
9621 ProcessAckPacket(1, &frame);
9622 CongestionUnblockWrites();
9623
9624 // Fires TLP, verify a PING gets sent because packet 3 is marked
9625 // RTO_RETRANSMITTED.
9626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
9627 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9628 connection_.GetRetransmissionAlarm()->Fire();
9629}
9630
fayang4c1c2362019-09-13 07:20:01 -07009631TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -07009632 QuicConfig config;
9633 QuicTagVector connection_options;
9634 connection_options.push_back(k1PTO);
9635 connection_options.push_back(kPTOS);
9636 config.SetConnectionOptionsToSend(connection_options);
9637 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9638 connection_.SetFromConfig(config);
9639 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9640
9641 QuicStreamId stream_id = 2;
9642 QuicPacketNumber last_packet;
9643 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9644 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9645 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9646 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9647
9648 // Fire PTO and verify the PTO retransmission skips one packet number.
9649 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9650 connection_.GetRetransmissionAlarm()->Fire();
9651 EXPECT_EQ(1u, writer_->stream_frames().size());
9652 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9653 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9654}
9655
fayang58f71072019-11-05 08:47:02 -08009656TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9657 if (!connection_.version().CanSendCoalescedPackets()) {
9658 return;
9659 }
9660 {
9661 QuicConnection::ScopedPacketFlusher flusher(&connection_);
9662 use_tagging_decrypter();
9663 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9664 std::make_unique<TaggingEncrypter>(0x01));
9665 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9666 connection_.SendCryptoDataWithString("foo", 0);
9667 // Verify this packet is on hold.
9668 EXPECT_EQ(0u, writer_->packets_write_attempts());
9669
9670 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9671 std::make_unique<TaggingEncrypter>(0x02));
9672 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9673 connection_.SendCryptoDataWithString("bar", 3);
9674 EXPECT_EQ(0u, writer_->packets_write_attempts());
9675
9676 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9677 std::make_unique<TaggingEncrypter>(0x03));
9678 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9679 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
9680 }
9681 // Verify all 3 packets are coalesced in the same UDP datagram.
9682 EXPECT_EQ(1u, writer_->packets_write_attempts());
9683 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
9684 // Verify the packet is padded to full.
9685 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
9686
9687 // Verify packet process.
9688 EXPECT_EQ(1u, writer_->crypto_frames().size());
9689 EXPECT_EQ(0u, writer_->stream_frames().size());
9690 // Verify there is coalesced packet.
9691 EXPECT_NE(nullptr, writer_->coalesced_packet());
9692}
9693
QUICHE teama6ef0a62019-03-07 20:34:33 -05009694} // namespace
9695} // namespace test
9696} // namespace quic