Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(24)

Side by Side Diff: net/quic/quic_connection_test.cc

Issue 992733002: Remove //net (except for Android test stuff) and sdch (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/quic/quic_connection_stats.cc ('k') | net/quic/quic_crypto_client_stream.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/quic/quic_connection.h"
6
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/stl_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/quic/congestion_control/loss_detection_interface.h"
12 #include "net/quic/congestion_control/send_algorithm_interface.h"
13 #include "net/quic/crypto/null_encrypter.h"
14 #include "net/quic/crypto/quic_decrypter.h"
15 #include "net/quic/crypto/quic_encrypter.h"
16 #include "net/quic/quic_ack_notifier.h"
17 #include "net/quic/quic_flags.h"
18 #include "net/quic/quic_protocol.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/mock_clock.h"
21 #include "net/quic/test_tools/mock_random.h"
22 #include "net/quic/test_tools/quic_config_peer.h"
23 #include "net/quic/test_tools/quic_connection_peer.h"
24 #include "net/quic/test_tools/quic_framer_peer.h"
25 #include "net/quic/test_tools/quic_packet_creator_peer.h"
26 #include "net/quic/test_tools/quic_packet_generator_peer.h"
27 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
28 #include "net/quic/test_tools/quic_test_utils.h"
29 #include "net/quic/test_tools/simple_quic_framer.h"
30 #include "net/test/gtest_util.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33
34 using base::StringPiece;
35 using std::map;
36 using std::string;
37 using std::vector;
38 using testing::AnyNumber;
39 using testing::AtLeast;
40 using testing::ContainerEq;
41 using testing::Contains;
42 using testing::DoAll;
43 using testing::InSequence;
44 using testing::InvokeWithoutArgs;
45 using testing::NiceMock;
46 using testing::Ref;
47 using testing::Return;
48 using testing::SaveArg;
49 using testing::StrictMock;
50 using testing::_;
51
52 namespace net {
53 namespace test {
54 namespace {
55
56 const char data1[] = "foo";
57 const char data2[] = "bar";
58
59 const bool kFin = true;
60 const bool kEntropyFlag = true;
61
62 const QuicPacketEntropyHash kTestEntropyHash = 76;
63
64 const int kDefaultRetransmissionTimeMs = 500;
65
66 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
67 class TaggingEncrypter : public QuicEncrypter {
68 public:
69 explicit TaggingEncrypter(uint8 tag)
70 : tag_(tag) {
71 }
72
73 ~TaggingEncrypter() override {}
74
75 // QuicEncrypter interface.
76 bool SetKey(StringPiece key) override { return true; }
77
78 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
79
80 bool Encrypt(StringPiece nonce,
81 StringPiece associated_data,
82 StringPiece plaintext,
83 unsigned char* output) override {
84 memcpy(output, plaintext.data(), plaintext.size());
85 output += plaintext.size();
86 memset(output, tag_, kTagSize);
87 return true;
88 }
89
90 bool EncryptPacket(QuicPacketSequenceNumber sequence_number,
91 StringPiece associated_data,
92 StringPiece plaintext,
93 char* output,
94 size_t* output_length,
95 size_t max_output_length) override {
96 const size_t len = plaintext.size() + kTagSize;
97 if (max_output_length < len) {
98 return false;
99 }
100 Encrypt(StringPiece(), associated_data, plaintext,
101 reinterpret_cast<unsigned char*>(output));
102 *output_length = len;
103 return true;
104 }
105
106 size_t GetKeySize() const override { return 0; }
107 size_t GetNoncePrefixSize() const override { return 0; }
108
109 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
110 return ciphertext_size - kTagSize;
111 }
112
113 size_t GetCiphertextSize(size_t plaintext_size) const override {
114 return plaintext_size + kTagSize;
115 }
116
117 StringPiece GetKey() const override { return StringPiece(); }
118
119 StringPiece GetNoncePrefix() const override { return StringPiece(); }
120
121 private:
122 enum {
123 kTagSize = 12,
124 };
125
126 const uint8 tag_;
127
128 DISALLOW_COPY_AND_ASSIGN(TaggingEncrypter);
129 };
130
131 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
132 // have the same value and then removes them.
133 class TaggingDecrypter : public QuicDecrypter {
134 public:
135 ~TaggingDecrypter() override {}
136
137 // QuicDecrypter interface
138 bool SetKey(StringPiece key) override { return true; }
139
140 bool SetNoncePrefix(StringPiece nonce_prefix) override { return true; }
141
142 bool DecryptPacket(QuicPacketSequenceNumber sequence_number,
143 const StringPiece& associated_data,
144 const StringPiece& ciphertext,
145 char* output,
146 size_t* output_length,
147 size_t max_output_length) override {
148 if (ciphertext.size() < kTagSize) {
149 return false;
150 }
151 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
152 return false;
153 }
154 *output_length = ciphertext.size() - kTagSize;
155 memcpy(output, ciphertext.data(), *output_length);
156 return true;
157 }
158
159 StringPiece GetKey() const override { return StringPiece(); }
160 StringPiece GetNoncePrefix() const override { return StringPiece(); }
161
162 protected:
163 virtual uint8 GetTag(StringPiece ciphertext) {
164 return ciphertext.data()[ciphertext.size()-1];
165 }
166
167 private:
168 enum {
169 kTagSize = 12,
170 };
171
172 bool CheckTag(StringPiece ciphertext, uint8 tag) {
173 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
174 if (ciphertext.data()[i] != tag) {
175 return false;
176 }
177 }
178
179 return true;
180 }
181 };
182
183 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
184 // match the expected value.
185 class StrictTaggingDecrypter : public TaggingDecrypter {
186 public:
187 explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
188 ~StrictTaggingDecrypter() override {}
189
190 // TaggingQuicDecrypter
191 uint8 GetTag(StringPiece ciphertext) override { return tag_; }
192
193 private:
194 const uint8 tag_;
195 };
196
197 class TestConnectionHelper : public QuicConnectionHelperInterface {
198 public:
199 class TestAlarm : public QuicAlarm {
200 public:
201 explicit TestAlarm(QuicAlarm::Delegate* delegate)
202 : QuicAlarm(delegate) {
203 }
204
205 void SetImpl() override {}
206 void CancelImpl() override {}
207 using QuicAlarm::Fire;
208 };
209
210 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
211 : clock_(clock),
212 random_generator_(random_generator) {
213 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
214 }
215
216 // QuicConnectionHelperInterface
217 const QuicClock* GetClock() const override { return clock_; }
218
219 QuicRandom* GetRandomGenerator() override { return random_generator_; }
220
221 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
222 return new TestAlarm(delegate);
223 }
224
225 private:
226 MockClock* clock_;
227 MockRandom* random_generator_;
228
229 DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
230 };
231
232 class TestPacketWriter : public QuicPacketWriter {
233 public:
234 TestPacketWriter(QuicVersion version, MockClock *clock)
235 : version_(version),
236 framer_(SupportedVersions(version_)),
237 last_packet_size_(0),
238 write_blocked_(false),
239 block_on_next_write_(false),
240 is_write_blocked_data_buffered_(false),
241 final_bytes_of_last_packet_(0),
242 final_bytes_of_previous_packet_(0),
243 use_tagging_decrypter_(false),
244 packets_write_attempts_(0),
245 clock_(clock),
246 write_pause_time_delta_(QuicTime::Delta::Zero()) {
247 }
248
249 // QuicPacketWriter interface
250 WriteResult WritePacket(const char* buffer,
251 size_t buf_len,
252 const IPAddressNumber& self_address,
253 const IPEndPoint& peer_address) override {
254 QuicEncryptedPacket packet(buffer, buf_len);
255 ++packets_write_attempts_;
256
257 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
258 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
259 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
260 sizeof(final_bytes_of_last_packet_));
261 }
262
263 if (use_tagging_decrypter_) {
264 framer_.framer()->SetDecrypter(new TaggingDecrypter, ENCRYPTION_NONE);
265 }
266 EXPECT_TRUE(framer_.ProcessPacket(packet));
267 if (block_on_next_write_) {
268 write_blocked_ = true;
269 block_on_next_write_ = false;
270 }
271 if (IsWriteBlocked()) {
272 return WriteResult(WRITE_STATUS_BLOCKED, -1);
273 }
274 last_packet_size_ = packet.length();
275
276 if (!write_pause_time_delta_.IsZero()) {
277 clock_->AdvanceTime(write_pause_time_delta_);
278 }
279 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
280 }
281
282 bool IsWriteBlockedDataBuffered() const override {
283 return is_write_blocked_data_buffered_;
284 }
285
286 bool IsWriteBlocked() const override { return write_blocked_; }
287
288 void SetWritable() override { write_blocked_ = false; }
289
290 void BlockOnNextWrite() { block_on_next_write_ = true; }
291
292 // Sets the amount of time that the writer should before the actual write.
293 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
294 write_pause_time_delta_ = delta;
295 }
296
297 const QuicPacketHeader& header() { return framer_.header(); }
298
299 size_t frame_count() const { return framer_.num_frames(); }
300
301 const vector<QuicAckFrame>& ack_frames() const {
302 return framer_.ack_frames();
303 }
304
305 const vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
306 return framer_.stop_waiting_frames();
307 }
308
309 const vector<QuicConnectionCloseFrame>& connection_close_frames() const {
310 return framer_.connection_close_frames();
311 }
312
313 const vector<QuicStreamFrame>& stream_frames() const {
314 return framer_.stream_frames();
315 }
316
317 const vector<QuicPingFrame>& ping_frames() const {
318 return framer_.ping_frames();
319 }
320
321 size_t last_packet_size() {
322 return last_packet_size_;
323 }
324
325 const QuicVersionNegotiationPacket* version_negotiation_packet() {
326 return framer_.version_negotiation_packet();
327 }
328
329 void set_is_write_blocked_data_buffered(bool buffered) {
330 is_write_blocked_data_buffered_ = buffered;
331 }
332
333 void set_is_server(bool is_server) {
334 // We invert is_server here, because the framer needs to parse packets
335 // we send.
336 QuicFramerPeer::SetIsServer(framer_.framer(), !is_server);
337 }
338
339 // final_bytes_of_last_packet_ returns the last four bytes of the previous
340 // packet as a little-endian, uint32. This is intended to be used with a
341 // TaggingEncrypter so that tests can determine which encrypter was used for
342 // a given packet.
343 uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
344
345 // Returns the final bytes of the second to last packet.
346 uint32 final_bytes_of_previous_packet() {
347 return final_bytes_of_previous_packet_;
348 }
349
350 void use_tagging_decrypter() {
351 use_tagging_decrypter_ = true;
352 }
353
354 uint32 packets_write_attempts() { return packets_write_attempts_; }
355
356 void Reset() { framer_.Reset(); }
357
358 void SetSupportedVersions(const QuicVersionVector& versions) {
359 framer_.SetSupportedVersions(versions);
360 }
361
362 private:
363 QuicVersion version_;
364 SimpleQuicFramer framer_;
365 size_t last_packet_size_;
366 bool write_blocked_;
367 bool block_on_next_write_;
368 bool is_write_blocked_data_buffered_;
369 uint32 final_bytes_of_last_packet_;
370 uint32 final_bytes_of_previous_packet_;
371 bool use_tagging_decrypter_;
372 uint32 packets_write_attempts_;
373 MockClock *clock_;
374 // If non-zero, the clock will pause during WritePacket for this amount of
375 // time.
376 QuicTime::Delta write_pause_time_delta_;
377
378 DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
379 };
380
381 class TestConnection : public QuicConnection {
382 public:
383 TestConnection(QuicConnectionId connection_id,
384 IPEndPoint address,
385 TestConnectionHelper* helper,
386 const PacketWriterFactory& factory,
387 bool is_server,
388 QuicVersion version)
389 : QuicConnection(connection_id,
390 address,
391 helper,
392 factory,
393 /* owns_writer= */ false,
394 is_server,
395 /* is_secure= */ false,
396 SupportedVersions(version)) {
397 // Disable tail loss probes for most tests.
398 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
399 QuicConnectionPeer::GetSentPacketManager(this), 0);
400 writer()->set_is_server(is_server);
401 }
402
403 void SendAck() {
404 QuicConnectionPeer::SendAck(this);
405 }
406
407 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
408 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
409 }
410
411 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
412 QuicSentPacketManagerPeer::SetLossAlgorithm(
413 QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
414 }
415
416 void SendPacket(EncryptionLevel level,
417 QuicPacketSequenceNumber sequence_number,
418 QuicPacket* packet,
419 QuicPacketEntropyHash entropy_hash,
420 HasRetransmittableData retransmittable) {
421 RetransmittableFrames* retransmittable_frames =
422 retransmittable == HAS_RETRANSMITTABLE_DATA
423 ? new RetransmittableFrames()
424 : nullptr;
425 QuicEncryptedPacket* encrypted =
426 QuicConnectionPeer::GetFramer(this)
427 ->EncryptPacket(ENCRYPTION_NONE, sequence_number, *packet);
428 delete packet;
429 OnSerializedPacket(SerializedPacket(sequence_number,
430 PACKET_6BYTE_SEQUENCE_NUMBER, encrypted,
431 entropy_hash, retransmittable_frames));
432 }
433
434 QuicConsumedData SendStreamDataWithString(
435 QuicStreamId id,
436 StringPiece data,
437 QuicStreamOffset offset,
438 bool fin,
439 QuicAckNotifier::DelegateInterface* delegate) {
440 return SendStreamDataWithStringHelper(id, data, offset, fin,
441 MAY_FEC_PROTECT, delegate);
442 }
443
444 QuicConsumedData SendStreamDataWithStringWithFec(
445 QuicStreamId id,
446 StringPiece data,
447 QuicStreamOffset offset,
448 bool fin,
449 QuicAckNotifier::DelegateInterface* delegate) {
450 return SendStreamDataWithStringHelper(id, data, offset, fin,
451 MUST_FEC_PROTECT, delegate);
452 }
453
454 QuicConsumedData SendStreamDataWithStringHelper(
455 QuicStreamId id,
456 StringPiece data,
457 QuicStreamOffset offset,
458 bool fin,
459 FecProtection fec_protection,
460 QuicAckNotifier::DelegateInterface* delegate) {
461 IOVector data_iov;
462 if (!data.empty()) {
463 data_iov.Append(const_cast<char*>(data.data()), data.size());
464 }
465 return QuicConnection::SendStreamData(id, data_iov, offset, fin,
466 fec_protection, delegate);
467 }
468
469 QuicConsumedData SendStreamData3() {
470 return SendStreamDataWithString(kClientDataStreamId1, "food", 0, !kFin,
471 nullptr);
472 }
473
474 QuicConsumedData SendStreamData3WithFec() {
475 return SendStreamDataWithStringWithFec(kClientDataStreamId1, "food", 0,
476 !kFin, nullptr);
477 }
478
479 QuicConsumedData SendStreamData5() {
480 return SendStreamDataWithString(kClientDataStreamId2, "food2", 0, !kFin,
481 nullptr);
482 }
483
484 QuicConsumedData SendStreamData5WithFec() {
485 return SendStreamDataWithStringWithFec(kClientDataStreamId2, "food2", 0,
486 !kFin, nullptr);
487 }
488 // Ensures the connection can write stream data before writing.
489 QuicConsumedData EnsureWritableAndSendStreamData5() {
490 EXPECT_TRUE(CanWriteStreamData());
491 return SendStreamData5();
492 }
493
494 // The crypto stream has special semantics so that it is not blocked by a
495 // congestion window limitation, and also so that it gets put into a separate
496 // packet (so that it is easier to reason about a crypto frame not being
497 // split needlessly across packet boundaries). As a result, we have separate
498 // tests for some cases for this stream.
499 QuicConsumedData SendCryptoStreamData() {
500 return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr);
501 }
502
503 bool is_server() {
504 return QuicConnectionPeer::IsServer(this);
505 }
506
507 void set_version(QuicVersion version) {
508 QuicConnectionPeer::GetFramer(this)->set_version(version);
509 }
510
511 void SetSupportedVersions(const QuicVersionVector& versions) {
512 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
513 writer()->SetSupportedVersions(versions);
514 }
515
516 void set_is_server(bool is_server) {
517 writer()->set_is_server(is_server);
518 QuicConnectionPeer::SetIsServer(this, is_server);
519 }
520
521 TestConnectionHelper::TestAlarm* GetAckAlarm() {
522 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
523 QuicConnectionPeer::GetAckAlarm(this));
524 }
525
526 TestConnectionHelper::TestAlarm* GetPingAlarm() {
527 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
528 QuicConnectionPeer::GetPingAlarm(this));
529 }
530
531 TestConnectionHelper::TestAlarm* GetFecAlarm() {
532 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
533 QuicConnectionPeer::GetFecAlarm(this));
534 }
535
536 TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
537 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
538 QuicConnectionPeer::GetResumeWritesAlarm(this));
539 }
540
541 TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
542 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
543 QuicConnectionPeer::GetRetransmissionAlarm(this));
544 }
545
546 TestConnectionHelper::TestAlarm* GetSendAlarm() {
547 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
548 QuicConnectionPeer::GetSendAlarm(this));
549 }
550
551 TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
552 return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
553 QuicConnectionPeer::GetTimeoutAlarm(this));
554 }
555
556 using QuicConnection::SelectMutualVersion;
557
558 private:
559 TestPacketWriter* writer() {
560 return static_cast<TestPacketWriter*>(QuicConnection::writer());
561 }
562
563 DISALLOW_COPY_AND_ASSIGN(TestConnection);
564 };
565
566 // Used for testing packets revived from FEC packets.
567 class FecQuicConnectionDebugVisitor
568 : public QuicConnectionDebugVisitor {
569 public:
570 void OnRevivedPacket(const QuicPacketHeader& header,
571 StringPiece data) override {
572 revived_header_ = header;
573 }
574
575 // Public accessor method.
576 QuicPacketHeader revived_header() const {
577 return revived_header_;
578 }
579
580 private:
581 QuicPacketHeader revived_header_;
582 };
583
584 class MockPacketWriterFactory : public QuicConnection::PacketWriterFactory {
585 public:
586 explicit MockPacketWriterFactory(QuicPacketWriter* writer) {
587 ON_CALL(*this, Create(_)).WillByDefault(Return(writer));
588 }
589 ~MockPacketWriterFactory() override {}
590
591 MOCK_CONST_METHOD1(Create, QuicPacketWriter*(QuicConnection* connection));
592 };
593
594 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
595 protected:
596 QuicConnectionTest()
597 : connection_id_(42),
598 framer_(SupportedVersions(version()), QuicTime::Zero(), false),
599 peer_creator_(connection_id_, &framer_, &random_generator_),
600 send_algorithm_(new StrictMock<MockSendAlgorithm>),
601 loss_algorithm_(new MockLossAlgorithm()),
602 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
603 writer_(new TestPacketWriter(version(), &clock_)),
604 factory_(writer_.get()),
605 connection_(connection_id_,
606 IPEndPoint(),
607 helper_.get(),
608 factory_,
609 false,
610 version()),
611 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
612 generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)),
613 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
614 frame1_(1, false, 0, MakeIOVector(data1)),
615 frame2_(1, false, 3, MakeIOVector(data2)),
616 sequence_number_length_(PACKET_6BYTE_SEQUENCE_NUMBER),
617 connection_id_length_(PACKET_8BYTE_CONNECTION_ID) {
618 connection_.set_visitor(&visitor_);
619 connection_.SetSendAlgorithm(send_algorithm_);
620 connection_.SetLossAlgorithm(loss_algorithm_);
621 framer_.set_received_entropy_calculator(&entropy_calculator_);
622 EXPECT_CALL(
623 *send_algorithm_, TimeUntilSend(_, _, _)).WillRepeatedly(Return(
624 QuicTime::Delta::Zero()));
625 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
626 .Times(AnyNumber());
627 EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
628 Return(QuicTime::Delta::Zero()));
629 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
630 Return(kMaxPacketSize));
631 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
632 .WillByDefault(Return(true));
633 EXPECT_CALL(*send_algorithm_, HasReliableBandwidthEstimate())
634 .Times(AnyNumber());
635 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
636 .Times(AnyNumber())
637 .WillRepeatedly(Return(QuicBandwidth::Zero()));
638 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
639 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
640 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
641 EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
642 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
643 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
644 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
645
646 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
647 .WillRepeatedly(Return(QuicTime::Zero()));
648 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
649 .WillRepeatedly(Return(SequenceNumberSet()));
650 }
651
652 QuicVersion version() {
653 return GetParam();
654 }
655
656 QuicAckFrame* outgoing_ack() {
657 QuicConnectionPeer::PopulateAckFrame(&connection_, &ack_);
658 return &ack_;
659 }
660
661 QuicStopWaitingFrame* stop_waiting() {
662 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
663 return &stop_waiting_;
664 }
665
666 QuicPacketSequenceNumber least_unacked() {
667 if (writer_->stop_waiting_frames().empty()) {
668 return 0;
669 }
670 return writer_->stop_waiting_frames()[0].least_unacked;
671 }
672
673 void use_tagging_decrypter() {
674 writer_->use_tagging_decrypter();
675 }
676
677 void ProcessPacket(QuicPacketSequenceNumber number) {
678 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
679 ProcessDataPacket(number, 0, !kEntropyFlag);
680 }
681
682 QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
683 QuicFrames frames;
684 frames.push_back(QuicFrame(frame));
685 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_,
686 connection_.is_server());
687 SerializedPacket serialized_packet =
688 peer_creator_.SerializeAllFrames(frames);
689 scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet);
690 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
691 return serialized_packet.entropy_hash;
692 }
693
694 size_t ProcessDataPacket(QuicPacketSequenceNumber number,
695 QuicFecGroupNumber fec_group,
696 bool entropy_flag) {
697 return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
698 ENCRYPTION_NONE);
699 }
700
701 size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
702 QuicFecGroupNumber fec_group,
703 bool entropy_flag,
704 EncryptionLevel level) {
705 scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
706 entropy_flag));
707 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
708 level, number, *packet));
709 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
710 return encrypted->length();
711 }
712
713 void ProcessPingPacket(QuicPacketSequenceNumber number) {
714 scoped_ptr<QuicPacket> packet(ConstructPingPacket(number));
715 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
716 ENCRYPTION_NONE, number, *packet));
717 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
718 }
719
720 void ProcessClosePacket(QuicPacketSequenceNumber number,
721 QuicFecGroupNumber fec_group) {
722 scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
723 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
724 ENCRYPTION_NONE, number, *packet));
725 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
726 }
727
728 size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
729 bool expect_revival, bool entropy_flag) {
730 if (expect_revival) {
731 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
732 }
733 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1).
734 RetiresOnSaturation();
735 return ProcessDataPacket(number, 1, entropy_flag);
736 }
737
738 // Processes an FEC packet that covers the packets that would have been
739 // received.
740 size_t ProcessFecPacket(QuicPacketSequenceNumber number,
741 QuicPacketSequenceNumber min_protected_packet,
742 bool expect_revival,
743 bool entropy_flag,
744 QuicPacket* packet) {
745 if (expect_revival) {
746 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
747 }
748
749 // Construct the decrypted data packet so we can compute the correct
750 // redundancy. If |packet| has been provided then use that, otherwise
751 // construct a default data packet.
752 scoped_ptr<QuicPacket> data_packet;
753 if (packet) {
754 data_packet.reset(packet);
755 } else {
756 data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
757 }
758
759 header_.public_header.connection_id = connection_id_;
760 header_.public_header.reset_flag = false;
761 header_.public_header.version_flag = false;
762 header_.public_header.sequence_number_length = sequence_number_length_;
763 header_.public_header.connection_id_length = connection_id_length_;
764 header_.packet_sequence_number = number;
765 header_.entropy_flag = entropy_flag;
766 header_.fec_flag = true;
767 header_.is_in_fec_group = IN_FEC_GROUP;
768 header_.fec_group = min_protected_packet;
769 QuicFecData fec_data;
770 fec_data.fec_group = header_.fec_group;
771
772 // Since all data packets in this test have the same payload, the
773 // redundancy is either equal to that payload or the xor of that payload
774 // with itself, depending on the number of packets.
775 if (((number - min_protected_packet) % 2) == 0) {
776 for (size_t i = GetStartOfFecProtectedData(
777 header_.public_header.connection_id_length,
778 header_.public_header.version_flag,
779 header_.public_header.sequence_number_length);
780 i < data_packet->length(); ++i) {
781 data_packet->mutable_data()[i] ^= data_packet->data()[i];
782 }
783 }
784 fec_data.redundancy = data_packet->FecProtectedData();
785
786 scoped_ptr<QuicPacket> fec_packet(
787 framer_.BuildFecPacket(header_, fec_data));
788 scoped_ptr<QuicEncryptedPacket> encrypted(
789 framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
790
791 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
792 return encrypted->length();
793 }
794
795 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
796 StringPiece data,
797 QuicStreamOffset offset,
798 bool fin,
799 QuicPacketSequenceNumber* last_packet) {
800 QuicByteCount packet_size;
801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
802 .WillOnce(DoAll(SaveArg<3>(&packet_size), Return(true)));
803 connection_.SendStreamDataWithString(id, data, offset, fin, nullptr);
804 if (last_packet != nullptr) {
805 *last_packet = creator_->sequence_number();
806 }
807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
808 .Times(AnyNumber());
809 return packet_size;
810 }
811
812 void SendAckPacketToPeer() {
813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
814 connection_.SendAck();
815 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
816 .Times(AnyNumber());
817 }
818
819 QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
820 return ProcessFramePacket(QuicFrame(frame));
821 }
822
823 QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
824 return ProcessFramePacket(QuicFrame(frame));
825 }
826
827 QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
828 return ProcessFramePacket(QuicFrame(frame));
829 }
830
831 bool IsMissing(QuicPacketSequenceNumber number) {
832 return IsAwaitingPacket(*outgoing_ack(), number);
833 }
834
835 QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
836 QuicFecGroupNumber fec_group,
837 bool entropy_flag) {
838 header_.public_header.connection_id = connection_id_;
839 header_.public_header.reset_flag = false;
840 header_.public_header.version_flag = false;
841 header_.public_header.sequence_number_length = sequence_number_length_;
842 header_.public_header.connection_id_length = connection_id_length_;
843 header_.entropy_flag = entropy_flag;
844 header_.fec_flag = false;
845 header_.packet_sequence_number = number;
846 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
847 header_.fec_group = fec_group;
848
849 QuicFrames frames;
850 QuicFrame frame(&frame1_);
851 frames.push_back(frame);
852 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
853 EXPECT_TRUE(packet != nullptr);
854 return packet;
855 }
856
857 QuicPacket* ConstructPingPacket(QuicPacketSequenceNumber number) {
858 header_.public_header.connection_id = connection_id_;
859 header_.packet_sequence_number = number;
860 header_.public_header.reset_flag = false;
861 header_.public_header.version_flag = false;
862 header_.entropy_flag = false;
863 header_.fec_flag = false;
864 header_.is_in_fec_group = NOT_IN_FEC_GROUP;
865 header_.fec_group = 0;
866
867 QuicPingFrame ping;
868
869 QuicFrames frames;
870 QuicFrame frame(&ping);
871 frames.push_back(frame);
872 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
873 EXPECT_TRUE(packet != nullptr);
874 return packet;
875 }
876
877 QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
878 QuicFecGroupNumber fec_group) {
879 header_.public_header.connection_id = connection_id_;
880 header_.packet_sequence_number = number;
881 header_.public_header.reset_flag = false;
882 header_.public_header.version_flag = false;
883 header_.entropy_flag = false;
884 header_.fec_flag = false;
885 header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
886 header_.fec_group = fec_group;
887
888 QuicConnectionCloseFrame qccf;
889 qccf.error_code = QUIC_PEER_GOING_AWAY;
890
891 QuicFrames frames;
892 QuicFrame frame(&qccf);
893 frames.push_back(frame);
894 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, header_, frames);
895 EXPECT_TRUE(packet != nullptr);
896 return packet;
897 }
898
899 QuicTime::Delta DefaultRetransmissionTime() {
900 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
901 }
902
903 QuicTime::Delta DefaultDelayedAckTime() {
904 return QuicTime::Delta::FromMilliseconds(kMaxDelayedAckTimeMs);
905 }
906
907 // Initialize a frame acknowledging all packets up to largest_observed.
908 const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed) {
909 QuicAckFrame frame(MakeAckFrame(largest_observed));
910 if (largest_observed > 0) {
911 frame.entropy_hash =
912 QuicConnectionPeer::GetSentEntropyHash(&connection_,
913 largest_observed);
914 }
915 return frame;
916 }
917
918 const QuicStopWaitingFrame InitStopWaitingFrame(
919 QuicPacketSequenceNumber least_unacked) {
920 QuicStopWaitingFrame frame;
921 frame.least_unacked = least_unacked;
922 return frame;
923 }
924
925 // Explicitly nack a packet.
926 void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
927 frame->missing_packets.insert(missing);
928 frame->entropy_hash ^=
929 QuicConnectionPeer::PacketEntropy(&connection_, missing);
930 }
931
932 // Undo nacking a packet within the frame.
933 void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
934 EXPECT_THAT(frame->missing_packets, Contains(arrived));
935 frame->missing_packets.erase(arrived);
936 frame->entropy_hash ^=
937 QuicConnectionPeer::PacketEntropy(&connection_, arrived);
938 }
939
940 void TriggerConnectionClose() {
941 // Send an erroneous packet to close the connection.
942 EXPECT_CALL(visitor_,
943 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
944 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
945 // packet call to the visitor.
946 ProcessDataPacket(6000, 0, !kEntropyFlag);
947 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
948 nullptr);
949 }
950
951 void BlockOnNextWrite() {
952 writer_->BlockOnNextWrite();
953 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
954 }
955
956 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
957 writer_->SetWritePauseTimeDelta(delta);
958 }
959
960 void CongestionBlockWrites() {
961 EXPECT_CALL(*send_algorithm_,
962 TimeUntilSend(_, _, _)).WillRepeatedly(
963 testing::Return(QuicTime::Delta::FromSeconds(1)));
964 }
965
966 void CongestionUnblockWrites() {
967 EXPECT_CALL(*send_algorithm_,
968 TimeUntilSend(_, _, _)).WillRepeatedly(
969 testing::Return(QuicTime::Delta::Zero()));
970 }
971
972 QuicConnectionId connection_id_;
973 QuicFramer framer_;
974 QuicPacketCreator peer_creator_;
975 MockEntropyCalculator entropy_calculator_;
976
977 MockSendAlgorithm* send_algorithm_;
978 MockLossAlgorithm* loss_algorithm_;
979 MockClock clock_;
980 MockRandom random_generator_;
981 scoped_ptr<TestConnectionHelper> helper_;
982 scoped_ptr<TestPacketWriter> writer_;
983 NiceMock<MockPacketWriterFactory> factory_;
984 TestConnection connection_;
985 QuicPacketCreator* creator_;
986 QuicPacketGenerator* generator_;
987 QuicSentPacketManager* manager_;
988 StrictMock<MockConnectionVisitor> visitor_;
989
990 QuicPacketHeader header_;
991 QuicStreamFrame frame1_;
992 QuicStreamFrame frame2_;
993 QuicAckFrame ack_;
994 QuicStopWaitingFrame stop_waiting_;
995 QuicSequenceNumberLength sequence_number_length_;
996 QuicConnectionIdLength connection_id_length_;
997
998 private:
999 DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
1000 };
1001
1002 // Run all end to end tests with all supported versions.
1003 INSTANTIATE_TEST_CASE_P(SupportedVersion,
1004 QuicConnectionTest,
1005 ::testing::ValuesIn(QuicSupportedVersions()));
1006
1007 TEST_P(QuicConnectionTest, MaxPacketSize) {
1008 EXPECT_FALSE(connection_.is_server());
1009 EXPECT_EQ(1350u, connection_.max_packet_length());
1010 }
1011
1012 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
1013 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, true);
1014 QuicConnectionId connection_id = 42;
1015 bool kIsServer = true;
1016 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1017 factory_, kIsServer, version());
1018 EXPECT_TRUE(connection.is_server());
1019 EXPECT_EQ(1000u, connection.max_packet_length());
1020 }
1021
1022 TEST_P(QuicConnectionTest, ServerMaxPacketSize) {
1023 ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, false);
1024 QuicConnectionId connection_id = 42;
1025 bool kIsServer = true;
1026 TestConnection connection(connection_id, IPEndPoint(), helper_.get(),
1027 factory_, kIsServer, version());
1028 EXPECT_TRUE(connection.is_server());
1029 EXPECT_EQ(1350u, connection.max_packet_length());
1030 }
1031
1032 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
1033 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1034
1035 connection_.set_is_server(true);
1036 connection_.set_max_packet_length(1000);
1037
1038 QuicPacketHeader header;
1039 header.public_header.connection_id = connection_id_;
1040 header.public_header.reset_flag = false;
1041 header.public_header.version_flag = true;
1042 header.entropy_flag = false;
1043 header.fec_flag = false;
1044 header.packet_sequence_number = 1;
1045 header.fec_group = 0;
1046
1047 QuicFrames frames;
1048 QuicPaddingFrame padding;
1049 frames.push_back(QuicFrame(&frame1_));
1050 frames.push_back(QuicFrame(&padding));
1051
1052 scoped_ptr<QuicPacket> packet(
1053 BuildUnsizedDataPacket(&framer_, header, frames));
1054 scoped_ptr<QuicEncryptedPacket> encrypted(
1055 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
1056 EXPECT_EQ(kMaxPacketSize, encrypted->length());
1057
1058 framer_.set_version(version());
1059 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
1060 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
1061
1062 EXPECT_EQ(kMaxPacketSize, connection_.max_packet_length());
1063 }
1064
1065 TEST_P(QuicConnectionTest, PacketsInOrder) {
1066 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1067
1068 ProcessPacket(1);
1069 EXPECT_EQ(1u, outgoing_ack()->largest_observed);
1070 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1071
1072 ProcessPacket(2);
1073 EXPECT_EQ(2u, outgoing_ack()->largest_observed);
1074 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1075
1076 ProcessPacket(3);
1077 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1078 EXPECT_EQ(0u, outgoing_ack()->missing_packets.size());
1079 }
1080
1081 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
1082 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1083
1084 ProcessPacket(3);
1085 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1086 EXPECT_TRUE(IsMissing(2));
1087 EXPECT_TRUE(IsMissing(1));
1088
1089 ProcessPacket(2);
1090 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1091 EXPECT_FALSE(IsMissing(2));
1092 EXPECT_TRUE(IsMissing(1));
1093
1094 ProcessPacket(1);
1095 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1096 EXPECT_FALSE(IsMissing(2));
1097 EXPECT_FALSE(IsMissing(1));
1098 }
1099
1100 TEST_P(QuicConnectionTest, DuplicatePacket) {
1101 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1102
1103 ProcessPacket(3);
1104 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1105 EXPECT_TRUE(IsMissing(2));
1106 EXPECT_TRUE(IsMissing(1));
1107
1108 // Send packet 3 again, but do not set the expectation that
1109 // the visitor OnStreamFrames() will be called.
1110 ProcessDataPacket(3, 0, !kEntropyFlag);
1111 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1112 EXPECT_TRUE(IsMissing(2));
1113 EXPECT_TRUE(IsMissing(1));
1114 }
1115
1116 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1117 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1118
1119 ProcessPacket(3);
1120 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1121 EXPECT_TRUE(IsMissing(2));
1122 EXPECT_TRUE(IsMissing(1));
1123
1124 ProcessPacket(2);
1125 EXPECT_EQ(3u, outgoing_ack()->largest_observed);
1126 EXPECT_TRUE(IsMissing(1));
1127
1128 ProcessPacket(5);
1129 EXPECT_EQ(5u, outgoing_ack()->largest_observed);
1130 EXPECT_TRUE(IsMissing(1));
1131 EXPECT_TRUE(IsMissing(4));
1132
1133 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1134 // packet the peer will not retransmit. It indicates this by sending 'least
1135 // awaiting' is 4. The connection should then realize 1 will not be
1136 // retransmitted, and will remove it from the missing list.
1137 peer_creator_.set_sequence_number(5);
1138 QuicAckFrame frame = InitAckFrame(1);
1139 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _));
1140 ProcessAckPacket(&frame);
1141
1142 // Force an ack to be sent.
1143 SendAckPacketToPeer();
1144 EXPECT_TRUE(IsMissing(4));
1145 }
1146
1147 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1148 EXPECT_CALL(visitor_,
1149 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1150 // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1151 // packet call to the visitor.
1152 ProcessDataPacket(6000, 0, !kEntropyFlag);
1153 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1154 nullptr);
1155 }
1156
1157 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
1158 // Process an unencrypted packet from the non-crypto stream.
1159 frame1_.stream_id = 3;
1160 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1161 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_UNENCRYPTED_STREAM_DATA,
1162 false));
1163 ProcessDataPacket(1, 0, !kEntropyFlag);
1164 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1165 nullptr);
1166 const vector<QuicConnectionCloseFrame>& connection_close_frames =
1167 writer_->connection_close_frames();
1168 EXPECT_EQ(1u, connection_close_frames.size());
1169 EXPECT_EQ(QUIC_UNENCRYPTED_STREAM_DATA,
1170 connection_close_frames[0].error_code);
1171 }
1172
1173 TEST_P(QuicConnectionTest, TruncatedAck) {
1174 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1175 QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1176 for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1177 SendStreamDataToPeer(3, "foo", i * 3, !kFin, nullptr);
1178 }
1179
1180 QuicAckFrame frame = InitAckFrame(num_packets);
1181 SequenceNumberSet lost_packets;
1182 // Create an ack with 256 nacks, none adjacent to one another.
1183 for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1184 NackPacket(i * 2, &frame);
1185 if (i < 256) { // Last packet is nacked, but not lost.
1186 lost_packets.insert(i * 2);
1187 }
1188 }
1189 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1190 .WillOnce(Return(lost_packets));
1191 EXPECT_CALL(entropy_calculator_, EntropyHash(511))
1192 .WillOnce(Return(static_cast<QuicPacketEntropyHash>(0)));
1193 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1194 ProcessAckPacket(&frame);
1195
1196 // A truncated ack will not have the true largest observed.
1197 EXPECT_GT(num_packets, manager_->largest_observed());
1198
1199 AckPacket(192, &frame);
1200
1201 // Removing one missing packet allows us to ack 192 and one more range, but
1202 // 192 has already been declared lost, so it doesn't register as an ack.
1203 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1204 .WillOnce(Return(SequenceNumberSet()));
1205 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1206 ProcessAckPacket(&frame);
1207 EXPECT_EQ(num_packets, manager_->largest_observed());
1208 }
1209
1210 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1211 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1212
1213 ProcessPacket(1);
1214 // Delay sending, then queue up an ack.
1215 EXPECT_CALL(*send_algorithm_,
1216 TimeUntilSend(_, _, _)).WillOnce(
1217 testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1218 QuicConnectionPeer::SendAck(&connection_);
1219
1220 // Process an ack with a least unacked of the received ack.
1221 // This causes an ack to be sent when TimeUntilSend returns 0.
1222 EXPECT_CALL(*send_algorithm_,
1223 TimeUntilSend(_, _, _)).WillRepeatedly(
1224 testing::Return(QuicTime::Delta::Zero()));
1225 // Skip a packet and then record an ack.
1226 peer_creator_.set_sequence_number(2);
1227 QuicAckFrame frame = InitAckFrame(0);
1228 ProcessAckPacket(&frame);
1229 }
1230
1231 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1232 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1233
1234 ProcessPacket(3);
1235 // Should ack immediately since we have missing packets.
1236 EXPECT_EQ(1u, writer_->packets_write_attempts());
1237
1238 ProcessPacket(2);
1239 // Should ack immediately since we have missing packets.
1240 EXPECT_EQ(2u, writer_->packets_write_attempts());
1241
1242 ProcessPacket(1);
1243 // Should ack immediately, since this fills the last hole.
1244 EXPECT_EQ(3u, writer_->packets_write_attempts());
1245
1246 ProcessPacket(4);
1247 // Should not cause an ack.
1248 EXPECT_EQ(3u, writer_->packets_write_attempts());
1249 }
1250
1251 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1252 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1253
1254 QuicPacketSequenceNumber original;
1255 QuicByteCount packet_size;
1256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1257 .WillOnce(DoAll(SaveArg<2>(&original), SaveArg<3>(&packet_size),
1258 Return(true)));
1259 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
1260 QuicAckFrame frame = InitAckFrame(original);
1261 NackPacket(original, &frame);
1262 // First nack triggers early retransmit.
1263 SequenceNumberSet lost_packets;
1264 lost_packets.insert(1);
1265 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1266 .WillOnce(Return(lost_packets));
1267 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1268 QuicPacketSequenceNumber retransmission;
1269 EXPECT_CALL(*send_algorithm_,
1270 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _))
1271 .WillOnce(DoAll(SaveArg<2>(&retransmission), Return(true)));
1272
1273 ProcessAckPacket(&frame);
1274
1275 QuicAckFrame frame2 = InitAckFrame(retransmission);
1276 NackPacket(original, &frame2);
1277 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1278 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1279 .WillOnce(Return(SequenceNumberSet()));
1280 ProcessAckPacket(&frame2);
1281
1282 // Now if the peer sends an ack which still reports the retransmitted packet
1283 // as missing, that will bundle an ack with data after two acks in a row
1284 // indicate the high water mark needs to be raised.
1285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1286 HAS_RETRANSMITTABLE_DATA));
1287 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1288 // No ack sent.
1289 EXPECT_EQ(1u, writer_->frame_count());
1290 EXPECT_EQ(1u, writer_->stream_frames().size());
1291
1292 // No more packet loss for the rest of the test.
1293 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1294 .WillRepeatedly(Return(SequenceNumberSet()));
1295 ProcessAckPacket(&frame2);
1296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _,
1297 HAS_RETRANSMITTABLE_DATA));
1298 connection_.SendStreamDataWithString(3, "foo", 3, !kFin, nullptr);
1299 // Ack bundled.
1300 EXPECT_EQ(3u, writer_->frame_count());
1301 EXPECT_EQ(1u, writer_->stream_frames().size());
1302 EXPECT_FALSE(writer_->ack_frames().empty());
1303
1304 // But an ack with no missing packets will not send an ack.
1305 AckPacket(original, &frame2);
1306 ProcessAckPacket(&frame2);
1307 ProcessAckPacket(&frame2);
1308 }
1309
1310 TEST_P(QuicConnectionTest, 20AcksCausesAckSend) {
1311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1312
1313 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1314
1315 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
1316 // But an ack with no missing packets will not send an ack.
1317 QuicAckFrame frame = InitAckFrame(1);
1318 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1319 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1320 .WillRepeatedly(Return(SequenceNumberSet()));
1321 for (int i = 0; i < 20; ++i) {
1322 EXPECT_FALSE(ack_alarm->IsSet());
1323 ProcessAckPacket(&frame);
1324 }
1325 EXPECT_TRUE(ack_alarm->IsSet());
1326 }
1327
1328 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1329 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1330
1331 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1332 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1333 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1334
1335 // Start out saying the least unacked is 2.
1336 peer_creator_.set_sequence_number(5);
1337 QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1338 ProcessStopWaitingPacket(&frame);
1339
1340 // Change it to 1, but lower the sequence number to fake out-of-order packets.
1341 // This should be fine.
1342 peer_creator_.set_sequence_number(1);
1343 // The scheduler will not process out of order acks, but all packet processing
1344 // causes the connection to try to write.
1345 EXPECT_CALL(visitor_, OnCanWrite());
1346 QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1347 ProcessStopWaitingPacket(&frame2);
1348
1349 // Now claim it's one, but set the ordering so it was sent "after" the first
1350 // one. This should cause a connection error.
1351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1352 peer_creator_.set_sequence_number(7);
1353 EXPECT_CALL(visitor_,
1354 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1355 QuicStopWaitingFrame frame3 = InitStopWaitingFrame(1);
1356 ProcessStopWaitingPacket(&frame3);
1357 }
1358
1359 TEST_P(QuicConnectionTest, TooManySentPackets) {
1360 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1361
1362 for (int i = 0; i < 1100; ++i) {
1363 SendStreamDataToPeer(1, "foo", 3 * i, !kFin, nullptr);
1364 }
1365
1366 // Ack packet 1, which leaves more than the limit outstanding.
1367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1368 EXPECT_CALL(visitor_, OnConnectionClosed(
1369 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, false));
1370 // We're receive buffer limited, so the connection won't try to write more.
1371 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1372
1373 // Nack every packet except the last one, leaving a huge gap.
1374 QuicAckFrame frame1 = InitAckFrame(1100);
1375 for (QuicPacketSequenceNumber i = 1; i < 1100; ++i) {
1376 NackPacket(i, &frame1);
1377 }
1378 ProcessAckPacket(&frame1);
1379 }
1380
1381 TEST_P(QuicConnectionTest, TooManyReceivedPackets) {
1382 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1383 EXPECT_CALL(visitor_, OnConnectionClosed(
1384 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS, false));
1385
1386 // Miss every other packet for 1000 packets.
1387 for (QuicPacketSequenceNumber i = 1; i < 1000; ++i) {
1388 ProcessPacket(i * 2);
1389 if (!connection_.connected()) {
1390 break;
1391 }
1392 }
1393 }
1394
1395 TEST_P(QuicConnectionTest, LargestObservedLower) {
1396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1397
1398 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
1399 SendStreamDataToPeer(1, "bar", 3, !kFin, nullptr);
1400 SendStreamDataToPeer(1, "eep", 6, !kFin, nullptr);
1401 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1402
1403 // Start out saying the largest observed is 2.
1404 QuicAckFrame frame1 = InitAckFrame(1);
1405 QuicAckFrame frame2 = InitAckFrame(2);
1406 ProcessAckPacket(&frame2);
1407
1408 // Now change it to 1, and it should cause a connection error.
1409 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1410 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1411 ProcessAckPacket(&frame1);
1412 }
1413
1414 TEST_P(QuicConnectionTest, AckUnsentData) {
1415 // Ack a packet which has not been sent.
1416 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1417 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1418 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1419 QuicAckFrame frame(MakeAckFrame(1));
1420 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1421 ProcessAckPacket(&frame);
1422 }
1423
1424 TEST_P(QuicConnectionTest, AckAll) {
1425 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1426 ProcessPacket(1);
1427
1428 peer_creator_.set_sequence_number(1);
1429 QuicAckFrame frame1 = InitAckFrame(0);
1430 ProcessAckPacket(&frame1);
1431 }
1432
1433 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1434 QuicPacketSequenceNumber last_packet;
1435 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1436 EXPECT_EQ(1u, last_packet);
1437 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1438 creator_->next_sequence_number_length());
1439 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1440 writer_->header().public_header.sequence_number_length);
1441
1442 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1443 Return(kMaxPacketSize * 256));
1444
1445 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1446 EXPECT_EQ(2u, last_packet);
1447 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1448 creator_->next_sequence_number_length());
1449 // The 1 packet lag is due to the sequence number length being recalculated in
1450 // QuicConnection after a packet is sent.
1451 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1452 writer_->header().public_header.sequence_number_length);
1453
1454 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1455 Return(kMaxPacketSize * 256 * 256));
1456
1457 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1458 EXPECT_EQ(3u, last_packet);
1459 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1460 creator_->next_sequence_number_length());
1461 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1462 writer_->header().public_header.sequence_number_length);
1463
1464 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1465 Return(kMaxPacketSize * 256 * 256 * 256));
1466
1467 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1468 EXPECT_EQ(4u, last_packet);
1469 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1470 creator_->next_sequence_number_length());
1471 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1472 writer_->header().public_header.sequence_number_length);
1473
1474 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
1475 Return(kMaxPacketSize * 256 * 256 * 256 * 256));
1476
1477 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1478 EXPECT_EQ(5u, last_packet);
1479 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1480 creator_->next_sequence_number_length());
1481 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1482 writer_->header().public_header.sequence_number_length);
1483 }
1484
1485 // TODO(ianswett): Re-enable this test by finding a good way to test different
1486 // sequence number lengths without sending packets with giant gaps.
1487 TEST_P(QuicConnectionTest,
1488 DISABLED_SendingDifferentSequenceNumberLengthsUnackedDelta) {
1489 QuicPacketSequenceNumber last_packet;
1490 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1491 EXPECT_EQ(1u, last_packet);
1492 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1493 creator_->next_sequence_number_length());
1494 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1495 writer_->header().public_header.sequence_number_length);
1496
1497 creator_->set_sequence_number(100);
1498
1499 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1500 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1501 creator_->next_sequence_number_length());
1502 EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1503 writer_->header().public_header.sequence_number_length);
1504
1505 creator_->set_sequence_number(100 * 256);
1506
1507 SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1508 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1509 creator_->next_sequence_number_length());
1510 EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1511 writer_->header().public_header.sequence_number_length);
1512
1513 creator_->set_sequence_number(100 * 256 * 256);
1514
1515 SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1516 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1517 creator_->next_sequence_number_length());
1518 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1519 writer_->header().public_header.sequence_number_length);
1520
1521 creator_->set_sequence_number(100 * 256 * 256 * 256);
1522
1523 SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1524 EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1525 creator_->next_sequence_number_length());
1526 EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1527 writer_->header().public_header.sequence_number_length);
1528 }
1529
1530 TEST_P(QuicConnectionTest, BasicSending) {
1531 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1532 QuicPacketSequenceNumber last_packet;
1533 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
1534 EXPECT_EQ(1u, last_packet);
1535 SendAckPacketToPeer(); // Packet 2
1536
1537 EXPECT_EQ(1u, least_unacked());
1538
1539 SendAckPacketToPeer(); // Packet 3
1540 EXPECT_EQ(1u, least_unacked());
1541
1542 SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet); // Packet 4
1543 EXPECT_EQ(4u, last_packet);
1544 SendAckPacketToPeer(); // Packet 5
1545 EXPECT_EQ(1u, least_unacked());
1546
1547 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1548
1549 // Peer acks up to packet 3.
1550 QuicAckFrame frame = InitAckFrame(3);
1551 ProcessAckPacket(&frame);
1552 SendAckPacketToPeer(); // Packet 6
1553
1554 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1555 // ack for 4.
1556 EXPECT_EQ(4u, least_unacked());
1557
1558 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1559
1560 // Peer acks up to packet 4, the last packet.
1561 QuicAckFrame frame2 = InitAckFrame(6);
1562 ProcessAckPacket(&frame2); // Acks don't instigate acks.
1563
1564 // Verify that we did not send an ack.
1565 EXPECT_EQ(6u, writer_->header().packet_sequence_number);
1566
1567 // So the last ack has not changed.
1568 EXPECT_EQ(4u, least_unacked());
1569
1570 // If we force an ack, we shouldn't change our retransmit state.
1571 SendAckPacketToPeer(); // Packet 7
1572 EXPECT_EQ(7u, least_unacked());
1573
1574 // But if we send more data it should.
1575 SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet); // Packet 8
1576 EXPECT_EQ(8u, last_packet);
1577 SendAckPacketToPeer(); // Packet 9
1578 EXPECT_EQ(7u, least_unacked());
1579 }
1580
1581 // If FLAGS_quic_record_send_time_before_write is disabled, QuicConnection
1582 // should record the packet sen-tdime after the packet is sent.
1583 TEST_P(QuicConnectionTest, RecordSentTimeAfterPacketSent) {
1584 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, false);
1585 // We're using a MockClock for the tests, so we have complete control over the
1586 // time.
1587 // Our recorded timestamp for the last packet sent time will be passed in to
1588 // the send_algorithm. Make sure that it is set to the correct value.
1589 QuicTime actual_recorded_send_time = QuicTime::Zero();
1590 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1591 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1592
1593 // First send without any pause and check the result.
1594 QuicTime expected_recorded_send_time = clock_.Now();
1595 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1596 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1597 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1598 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1599
1600 // Now pause during the write, and check the results.
1601 actual_recorded_send_time = QuicTime::Zero();
1602 const QuicTime::Delta kWritePauseTimeDelta =
1603 QuicTime::Delta::FromMilliseconds(5000);
1604 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1605 expected_recorded_send_time = clock_.Now().Add(kWritePauseTimeDelta);
1606
1607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1608 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1609 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1610 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1611 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1612 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1613 }
1614
1615 // If FLAGS_quic_record_send_time_before_write is enabled, QuicConnection should
1616 // record the the packet sent-time prior to sending the packet.
1617 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
1618 ValueRestore<bool> old_flag(&FLAGS_quic_record_send_time_before_write, true);
1619 // We're using a MockClock for the tests, so we have complete control over the
1620 // time.
1621 // Our recorded timestamp for the last packet sent time will be passed in to
1622 // the send_algorithm. Make sure that it is set to the correct value.
1623 QuicTime actual_recorded_send_time = QuicTime::Zero();
1624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1625 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1626
1627 // First send without any pause and check the result.
1628 QuicTime expected_recorded_send_time = clock_.Now();
1629 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
1630 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1631 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1632 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1633
1634 // Now pause during the write, and check the results.
1635 actual_recorded_send_time = QuicTime::Zero();
1636 const QuicTime::Delta kWritePauseTimeDelta =
1637 QuicTime::Delta::FromMilliseconds(5000);
1638 SetWritePauseTimeDelta(kWritePauseTimeDelta);
1639 expected_recorded_send_time = clock_.Now();
1640
1641 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1642 .WillOnce(DoAll(SaveArg<0>(&actual_recorded_send_time), Return(true)));
1643 connection_.SendStreamDataWithString(2, "baz", 0, !kFin, nullptr);
1644 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
1645 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
1646 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
1647 }
1648
1649 TEST_P(QuicConnectionTest, FECSending) {
1650 // All packets carry version info till version is negotiated.
1651 size_t payload_length;
1652 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
1653 // packet length. The size of the offset field in a stream frame is 0 for
1654 // offset 0, and 2 for non-zero offsets up through 64K. Increase
1655 // max_packet_length by 2 so that subsequent packets containing subsequent
1656 // stream frames with non-zero offets will fit within the packet length.
1657 size_t length = 2 + GetPacketLengthForOneStream(
1658 connection_.version(), kIncludeVersion,
1659 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1660 IN_FEC_GROUP, &payload_length);
1661 creator_->set_max_packet_length(length);
1662
1663 // Send 4 protected data packets, which should also trigger 1 FEC packet.
1664 EXPECT_CALL(*send_algorithm_,
1665 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(5);
1666 // The first stream frame will have 2 fewer overhead bytes than the other 3.
1667 const string payload(payload_length * 4 + 2, 'a');
1668 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1669 // Expect the FEC group to be closed after SendStreamDataWithString.
1670 EXPECT_FALSE(creator_->IsFecGroupOpen());
1671 EXPECT_FALSE(creator_->IsFecProtected());
1672 }
1673
1674 TEST_P(QuicConnectionTest, FECQueueing) {
1675 // All packets carry version info till version is negotiated.
1676 size_t payload_length;
1677 size_t length = GetPacketLengthForOneStream(
1678 connection_.version(), kIncludeVersion,
1679 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
1680 IN_FEC_GROUP, &payload_length);
1681 creator_->set_max_packet_length(length);
1682 EXPECT_TRUE(creator_->IsFecEnabled());
1683
1684 EXPECT_EQ(0u, connection_.NumQueuedPackets());
1685 BlockOnNextWrite();
1686 const string payload(payload_length, 'a');
1687 connection_.SendStreamDataWithStringWithFec(1, payload, 0, !kFin, nullptr);
1688 EXPECT_FALSE(creator_->IsFecGroupOpen());
1689 EXPECT_FALSE(creator_->IsFecProtected());
1690 // Expect the first data packet and the fec packet to be queued.
1691 EXPECT_EQ(2u, connection_.NumQueuedPackets());
1692 }
1693
1694 TEST_P(QuicConnectionTest, FECAlarmStoppedWhenFECPacketSent) {
1695 EXPECT_TRUE(creator_->IsFecEnabled());
1696 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1697 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1698
1699 creator_->set_max_packets_per_fec_group(2);
1700
1701 // 1 Data packet. FEC alarm should be set.
1702 EXPECT_CALL(*send_algorithm_,
1703 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1704 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, true, nullptr);
1705 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1706
1707 // Second data packet triggers FEC packet out. FEC alarm should not be set.
1708 EXPECT_CALL(*send_algorithm_,
1709 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(2);
1710 connection_.SendStreamDataWithStringWithFec(5, "foo", 0, true, nullptr);
1711 EXPECT_TRUE(writer_->header().fec_flag);
1712 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1713 }
1714
1715 TEST_P(QuicConnectionTest, FECAlarmStoppedOnConnectionClose) {
1716 EXPECT_TRUE(creator_->IsFecEnabled());
1717 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1718 creator_->set_max_packets_per_fec_group(100);
1719
1720 // 1 Data packet. FEC alarm should be set.
1721 EXPECT_CALL(*send_algorithm_,
1722 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1723 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1724 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1725
1726 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_NO_ERROR, false));
1727 // Closing connection should stop the FEC alarm.
1728 connection_.CloseConnection(QUIC_NO_ERROR, /*from_peer=*/false);
1729 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1730 }
1731
1732 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnRetransmissionTimeout) {
1733 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1734 EXPECT_TRUE(creator_->IsFecEnabled());
1735 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1736 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1737
1738 // 1 Data packet. FEC alarm should be set.
1739 EXPECT_CALL(*send_algorithm_,
1740 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1741 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1742 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1743 size_t protected_packet =
1744 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1745
1746 // Force FEC timeout to send FEC packet out.
1747 EXPECT_CALL(*send_algorithm_,
1748 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1749 connection_.GetFecAlarm()->Fire();
1750 EXPECT_TRUE(writer_->header().fec_flag);
1751
1752 size_t fec_packet = protected_packet;
1753 EXPECT_EQ(protected_packet + fec_packet,
1754 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1755 clock_.AdvanceTime(DefaultRetransmissionTime());
1756
1757 // On RTO, both data and FEC packets are removed from inflight, only the data
1758 // packet is retransmitted, and this retransmission (but not FEC) gets added
1759 // back into the inflight.
1760 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1761 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1762 connection_.GetRetransmissionAlarm()->Fire();
1763
1764 // The retransmission of packet 1 will be 3 bytes smaller than packet 1, since
1765 // the first transmission will have 1 byte for FEC group number and 2 bytes of
1766 // stream frame size, which are absent in the retransmission.
1767 size_t retransmitted_packet = protected_packet - 3;
1768 if (FLAGS_quic_use_new_rto) {
1769 EXPECT_EQ(protected_packet + retransmitted_packet,
1770 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1771 } else {
1772 EXPECT_EQ(retransmitted_packet,
1773 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1774 }
1775 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1776
1777 // Receive ack for the retransmission. No data should be outstanding.
1778 QuicAckFrame ack = InitAckFrame(3);
1779 NackPacket(1, &ack);
1780 NackPacket(2, &ack);
1781 SequenceNumberSet lost_packets;
1782 if (FLAGS_quic_use_new_rto) {
1783 lost_packets.insert(1);
1784 }
1785 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1786 .WillOnce(Return(lost_packets));
1787 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1788 ProcessAckPacket(&ack);
1789
1790 // Ensure the alarm is not set since all packets have been acked or abandoned.
1791 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1792 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1793 }
1794
1795 TEST_P(QuicConnectionTest, RemoveFECFromInflightOnLossRetransmission) {
1796 EXPECT_TRUE(creator_->IsFecEnabled());
1797 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1798
1799 // 1 FEC-protected data packet. FEC alarm should be set.
1800 EXPECT_CALL(*send_algorithm_,
1801 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1802 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1803 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1804 size_t protected_packet =
1805 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1806
1807 // Force FEC timeout to send FEC packet out.
1808 EXPECT_CALL(*send_algorithm_,
1809 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1810 connection_.GetFecAlarm()->Fire();
1811 EXPECT_TRUE(writer_->header().fec_flag);
1812 size_t fec_packet = protected_packet;
1813 EXPECT_EQ(protected_packet + fec_packet,
1814 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1815
1816 // Send more data to trigger NACKs. Note that all data starts at stream offset
1817 // 0 to ensure the same packet size, for ease of testing.
1818 EXPECT_CALL(*send_algorithm_,
1819 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(4);
1820 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1821 connection_.SendStreamDataWithString(7, "foo", 0, kFin, nullptr);
1822 connection_.SendStreamDataWithString(9, "foo", 0, kFin, nullptr);
1823 connection_.SendStreamDataWithString(11, "foo", 0, kFin, nullptr);
1824
1825 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1826 // since the protected packet will have 1 byte for FEC group number and
1827 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1828 size_t unprotected_packet = protected_packet - 3;
1829 EXPECT_EQ(protected_packet + fec_packet + 4 * unprotected_packet,
1830 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1831 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1832
1833 // Ack data packets, and NACK FEC packet and one data packet. Triggers
1834 // NACK-based loss detection of both packets, but only data packet is
1835 // retransmitted and considered oustanding.
1836 QuicAckFrame ack = InitAckFrame(6);
1837 NackPacket(2, &ack);
1838 NackPacket(3, &ack);
1839 SequenceNumberSet lost_packets;
1840 lost_packets.insert(2);
1841 lost_packets.insert(3);
1842 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1843 .WillOnce(Return(lost_packets));
1844 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1845 EXPECT_CALL(*send_algorithm_,
1846 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1847 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1848 ProcessAckPacket(&ack);
1849 // On receiving this ack from the server, the client will no longer send
1850 // version number in subsequent packets, including in this retransmission.
1851 size_t unprotected_packet_no_version = unprotected_packet - 4;
1852 EXPECT_EQ(unprotected_packet_no_version,
1853 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1854
1855 // Receive ack for the retransmission. No data should be outstanding.
1856 QuicAckFrame ack2 = InitAckFrame(7);
1857 NackPacket(2, &ack2);
1858 NackPacket(3, &ack2);
1859 SequenceNumberSet lost_packets2;
1860 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1861 .WillOnce(Return(lost_packets2));
1862 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1863 ProcessAckPacket(&ack2);
1864 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1865 }
1866
1867 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfEarlierData) {
1868 // This test checks if TLP is sent correctly when a data and an FEC packet
1869 // are outstanding. TLP should be sent for the data packet when the
1870 // retransmission alarm fires.
1871 // Turn on TLP for this test.
1872 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1873 EXPECT_TRUE(creator_->IsFecEnabled());
1874 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1875 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1876
1877 // 1 Data packet. FEC alarm should be set.
1878 EXPECT_CALL(*send_algorithm_,
1879 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1880 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1881 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1882 size_t protected_packet =
1883 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1884 EXPECT_LT(0u, protected_packet);
1885
1886 // Force FEC timeout to send FEC packet out.
1887 EXPECT_CALL(*send_algorithm_,
1888 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1889 connection_.GetFecAlarm()->Fire();
1890 EXPECT_TRUE(writer_->header().fec_flag);
1891 size_t fec_packet = protected_packet;
1892 EXPECT_EQ(protected_packet + fec_packet,
1893 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1894
1895 // TLP alarm should be set.
1896 QuicTime retransmission_time =
1897 connection_.GetRetransmissionAlarm()->deadline();
1898 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1899 // Simulate the retransmission alarm firing and sending a TLP, so send
1900 // algorithm's OnRetransmissionTimeout is not called.
1901 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1902 EXPECT_CALL(*send_algorithm_,
1903 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1904 connection_.GetRetransmissionAlarm()->Fire();
1905 // The TLP retransmission of packet 1 will be 3 bytes smaller than packet 1,
1906 // since packet 1 will have 1 byte for FEC group number and 2 bytes of stream
1907 // frame size, which are absent in the the TLP retransmission.
1908 size_t tlp_packet = protected_packet - 3;
1909 EXPECT_EQ(protected_packet + fec_packet + tlp_packet,
1910 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1911 }
1912
1913 TEST_P(QuicConnectionTest, FECRemainsInflightOnTLPOfLaterData) {
1914 // Tests if TLP is sent correctly when data packet 1 and an FEC packet are
1915 // sent followed by data packet 2, and data packet 1 is acked. TLP should be
1916 // sent for data packet 2 when the retransmission alarm fires. Turn on TLP for
1917 // this test.
1918 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1919 EXPECT_TRUE(creator_->IsFecEnabled());
1920 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1921 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1922
1923 // 1 Data packet. FEC alarm should be set.
1924 EXPECT_CALL(*send_algorithm_,
1925 OnPacketSent(_, _, 1u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1926 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, kFin, nullptr);
1927 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1928 size_t protected_packet =
1929 QuicSentPacketManagerPeer::GetBytesInFlight(manager_);
1930 EXPECT_LT(0u, protected_packet);
1931
1932 // Force FEC timeout to send FEC packet out.
1933 EXPECT_CALL(*send_algorithm_,
1934 OnPacketSent(_, _, 2u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1935 connection_.GetFecAlarm()->Fire();
1936 EXPECT_TRUE(writer_->header().fec_flag);
1937 // Protected data packet and FEC packet oustanding.
1938 size_t fec_packet = protected_packet;
1939 EXPECT_EQ(protected_packet + fec_packet,
1940 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1941
1942 // Send 1 unprotected data packet. No FEC alarm should be set.
1943 EXPECT_CALL(*send_algorithm_,
1944 OnPacketSent(_, _, 3u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1945 connection_.SendStreamDataWithString(5, "foo", 0, kFin, nullptr);
1946 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
1947 // Protected data packet, FEC packet, and unprotected data packet oustanding.
1948 // An unprotected packet will be 3 bytes smaller than an FEC-protected packet,
1949 // since the protected packet will have 1 byte for FEC group number and
1950 // 2 bytes of stream frame size, which are absent in the unprotected packet.
1951 size_t unprotected_packet = protected_packet - 3;
1952 EXPECT_EQ(protected_packet + fec_packet + unprotected_packet,
1953 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1954
1955 // Receive ack for first data packet. FEC and second data packet are still
1956 // outstanding.
1957 QuicAckFrame ack = InitAckFrame(1);
1958 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
1959 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1960 ProcessAckPacket(&ack);
1961 // FEC packet and unprotected data packet oustanding.
1962 EXPECT_EQ(fec_packet + unprotected_packet,
1963 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1964
1965 // TLP alarm should be set.
1966 QuicTime retransmission_time =
1967 connection_.GetRetransmissionAlarm()->deadline();
1968 EXPECT_NE(QuicTime::Zero(), retransmission_time);
1969 // Simulate the retransmission alarm firing and sending a TLP, so send
1970 // algorithm's OnRetransmissionTimeout is not called.
1971 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
1972 EXPECT_CALL(*send_algorithm_,
1973 OnPacketSent(_, _, 4u, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1974 connection_.GetRetransmissionAlarm()->Fire();
1975
1976 // Having received an ack from the server, the client will no longer send
1977 // version number in subsequent packets, including in this retransmission.
1978 size_t tlp_packet_no_version = unprotected_packet - 4;
1979 EXPECT_EQ(fec_packet + unprotected_packet + tlp_packet_no_version,
1980 QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
1981 }
1982
1983 TEST_P(QuicConnectionTest, NoTLPForFECPacket) {
1984 // Turn on TLP for this test.
1985 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
1986 EXPECT_TRUE(creator_->IsFecEnabled());
1987 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1988
1989 // Send 1 FEC-protected data packet. FEC alarm should be set.
1990 EXPECT_CALL(*send_algorithm_,
1991 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1992 connection_.SendStreamDataWithStringWithFec(3, "foo", 0, !kFin, nullptr);
1993 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
1994 // Force FEC timeout to send FEC packet out.
1995 EXPECT_CALL(*send_algorithm_,
1996 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)).Times(1);
1997 connection_.GetFecAlarm()->Fire();
1998 EXPECT_TRUE(writer_->header().fec_flag);
1999
2000 // Ack data packet, but not FEC packet.
2001 QuicAckFrame ack = InitAckFrame(1);
2002 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2003 ProcessAckPacket(&ack);
2004
2005 // No TLP alarm for FEC, but retransmission alarm should be set for an RTO.
2006 EXPECT_LT(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2007 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2008 QuicTime rto_time = connection_.GetRetransmissionAlarm()->deadline();
2009 EXPECT_NE(QuicTime::Zero(), rto_time);
2010
2011 // Simulate the retransmission alarm firing. FEC packet is no longer
2012 // outstanding.
2013 if (!FLAGS_quic_use_new_rto) {
2014 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(false));
2015 }
2016 clock_.AdvanceTime(rto_time.Subtract(clock_.Now()));
2017 connection_.GetRetransmissionAlarm()->Fire();
2018
2019 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2020 EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetBytesInFlight(manager_));
2021 }
2022
2023 TEST_P(QuicConnectionTest, FramePacking) {
2024 CongestionBlockWrites();
2025
2026 // Send an ack and two stream frames in 1 packet by queueing them.
2027 connection_.SendAck();
2028 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2029 IgnoreResult(InvokeWithoutArgs(&connection_,
2030 &TestConnection::SendStreamData3)),
2031 IgnoreResult(InvokeWithoutArgs(&connection_,
2032 &TestConnection::SendStreamData5))));
2033
2034 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2035 CongestionUnblockWrites();
2036 connection_.GetSendAlarm()->Fire();
2037 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2038 EXPECT_FALSE(connection_.HasQueuedData());
2039
2040 // Parse the last packet and ensure it's an ack and two stream frames from
2041 // two different streams.
2042 EXPECT_EQ(4u, writer_->frame_count());
2043 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2044 EXPECT_FALSE(writer_->ack_frames().empty());
2045 ASSERT_EQ(2u, writer_->stream_frames().size());
2046 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2047 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2048 }
2049
2050 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
2051 CongestionBlockWrites();
2052
2053 // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
2054 // packets by queueing them.
2055 connection_.SendAck();
2056 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2057 IgnoreResult(InvokeWithoutArgs(&connection_,
2058 &TestConnection::SendStreamData3)),
2059 IgnoreResult(InvokeWithoutArgs(&connection_,
2060 &TestConnection::SendCryptoStreamData))));
2061
2062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2063 CongestionUnblockWrites();
2064 connection_.GetSendAlarm()->Fire();
2065 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2066 EXPECT_FALSE(connection_.HasQueuedData());
2067
2068 // Parse the last packet and ensure it's the crypto stream frame.
2069 EXPECT_EQ(1u, writer_->frame_count());
2070 ASSERT_EQ(1u, writer_->stream_frames().size());
2071 EXPECT_EQ(kCryptoStreamId, writer_->stream_frames()[0].stream_id);
2072 }
2073
2074 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
2075 CongestionBlockWrites();
2076
2077 // Send an ack and two stream frames (one crypto, then one non-crypto) in 2
2078 // packets by queueing them.
2079 connection_.SendAck();
2080 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2081 IgnoreResult(InvokeWithoutArgs(&connection_,
2082 &TestConnection::SendCryptoStreamData)),
2083 IgnoreResult(InvokeWithoutArgs(&connection_,
2084 &TestConnection::SendStreamData3))));
2085
2086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2087 CongestionUnblockWrites();
2088 connection_.GetSendAlarm()->Fire();
2089 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2090 EXPECT_FALSE(connection_.HasQueuedData());
2091
2092 // Parse the last packet and ensure it's the stream frame from stream 3.
2093 EXPECT_EQ(1u, writer_->frame_count());
2094 ASSERT_EQ(1u, writer_->stream_frames().size());
2095 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2096 }
2097
2098 TEST_P(QuicConnectionTest, FramePackingFEC) {
2099 EXPECT_TRUE(creator_->IsFecEnabled());
2100
2101 CongestionBlockWrites();
2102
2103 // Queue an ack and two stream frames. Ack gets flushed when FEC is turned on
2104 // for sending protected data; two stream frames are packed in 1 packet.
2105 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2106 IgnoreResult(InvokeWithoutArgs(
2107 &connection_, &TestConnection::SendStreamData3WithFec)),
2108 IgnoreResult(InvokeWithoutArgs(
2109 &connection_, &TestConnection::SendStreamData5WithFec))));
2110 connection_.SendAck();
2111
2112 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2113 CongestionUnblockWrites();
2114 connection_.GetSendAlarm()->Fire();
2115 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2116 EXPECT_FALSE(connection_.HasQueuedData());
2117
2118 // Parse the last packet and ensure it's in an fec group.
2119 EXPECT_EQ(2u, writer_->header().fec_group);
2120 EXPECT_EQ(2u, writer_->frame_count());
2121
2122 // FEC alarm should be set.
2123 EXPECT_TRUE(connection_.GetFecAlarm()->IsSet());
2124 }
2125
2126 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
2127 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2128 // Process a data packet to queue up a pending ack.
2129 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2130 ProcessDataPacket(1, 1, kEntropyFlag);
2131
2132 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2133 IgnoreResult(InvokeWithoutArgs(&connection_,
2134 &TestConnection::SendStreamData3)),
2135 IgnoreResult(InvokeWithoutArgs(&connection_,
2136 &TestConnection::SendStreamData5))));
2137
2138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2139
2140 // Process an ack to cause the visitor's OnCanWrite to be invoked.
2141 peer_creator_.set_sequence_number(2);
2142 QuicAckFrame ack_one = InitAckFrame(0);
2143 ProcessAckPacket(&ack_one);
2144
2145 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2146 EXPECT_FALSE(connection_.HasQueuedData());
2147
2148 // Parse the last packet and ensure it's an ack and two stream frames from
2149 // two different streams.
2150 EXPECT_EQ(4u, writer_->frame_count());
2151 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
2152 EXPECT_FALSE(writer_->ack_frames().empty());
2153 ASSERT_EQ(2u, writer_->stream_frames().size());
2154 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2155 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2156 }
2157
2158 TEST_P(QuicConnectionTest, FramePackingSendv) {
2159 // Send data in 1 packet by writing multiple blocks in a single iovector
2160 // using writev.
2161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2162
2163 char data[] = "ABCD";
2164 IOVector data_iov;
2165 data_iov.AppendNoCoalesce(data, 2);
2166 data_iov.AppendNoCoalesce(data + 2, 2);
2167 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2168
2169 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2170 EXPECT_FALSE(connection_.HasQueuedData());
2171
2172 // Parse the last packet and ensure multiple iovector blocks have
2173 // been packed into a single stream frame from one stream.
2174 EXPECT_EQ(1u, writer_->frame_count());
2175 EXPECT_EQ(1u, writer_->stream_frames().size());
2176 QuicStreamFrame frame = writer_->stream_frames()[0];
2177 EXPECT_EQ(1u, frame.stream_id);
2178 EXPECT_EQ("ABCD", string(static_cast<char*>
2179 (frame.data.iovec()[0].iov_base),
2180 (frame.data.iovec()[0].iov_len)));
2181 }
2182
2183 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
2184 // Try to send two stream frames in 1 packet by using writev.
2185 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2186
2187 BlockOnNextWrite();
2188 char data[] = "ABCD";
2189 IOVector data_iov;
2190 data_iov.AppendNoCoalesce(data, 2);
2191 data_iov.AppendNoCoalesce(data + 2, 2);
2192 connection_.SendStreamData(1, data_iov, 0, !kFin, MAY_FEC_PROTECT, nullptr);
2193
2194 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2195 EXPECT_TRUE(connection_.HasQueuedData());
2196
2197 // Unblock the writes and actually send.
2198 writer_->SetWritable();
2199 connection_.OnCanWrite();
2200 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2201
2202 // Parse the last packet and ensure it's one stream frame from one stream.
2203 EXPECT_EQ(1u, writer_->frame_count());
2204 EXPECT_EQ(1u, writer_->stream_frames().size());
2205 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2206 }
2207
2208 TEST_P(QuicConnectionTest, SendingZeroBytes) {
2209 // Send a zero byte write with a fin using writev.
2210 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2211 IOVector empty_iov;
2212 connection_.SendStreamData(1, empty_iov, 0, kFin, MAY_FEC_PROTECT, nullptr);
2213
2214 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2215 EXPECT_FALSE(connection_.HasQueuedData());
2216
2217 // Parse the last packet and ensure it's one stream frame from one stream.
2218 EXPECT_EQ(1u, writer_->frame_count());
2219 EXPECT_EQ(1u, writer_->stream_frames().size());
2220 EXPECT_EQ(1u, writer_->stream_frames()[0].stream_id);
2221 EXPECT_TRUE(writer_->stream_frames()[0].fin);
2222 }
2223
2224 TEST_P(QuicConnectionTest, OnCanWrite) {
2225 // Visitor's OnCanWrite will send data, but will have more pending writes.
2226 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
2227 IgnoreResult(InvokeWithoutArgs(&connection_,
2228 &TestConnection::SendStreamData3)),
2229 IgnoreResult(InvokeWithoutArgs(&connection_,
2230 &TestConnection::SendStreamData5))));
2231 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
2232 EXPECT_CALL(*send_algorithm_,
2233 TimeUntilSend(_, _, _)).WillRepeatedly(
2234 testing::Return(QuicTime::Delta::Zero()));
2235
2236 connection_.OnCanWrite();
2237
2238 // Parse the last packet and ensure it's the two stream frames from
2239 // two different streams.
2240 EXPECT_EQ(2u, writer_->frame_count());
2241 EXPECT_EQ(2u, writer_->stream_frames().size());
2242 EXPECT_EQ(kClientDataStreamId1, writer_->stream_frames()[0].stream_id);
2243 EXPECT_EQ(kClientDataStreamId2, writer_->stream_frames()[1].stream_id);
2244 }
2245
2246 TEST_P(QuicConnectionTest, RetransmitOnNack) {
2247 QuicPacketSequenceNumber last_packet;
2248 QuicByteCount second_packet_size;
2249 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 1
2250 second_packet_size =
2251 SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet); // Packet 2
2252 SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet); // Packet 3
2253
2254 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2255
2256 // Don't lose a packet on an ack, and nothing is retransmitted.
2257 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2258 QuicAckFrame ack_one = InitAckFrame(1);
2259 ProcessAckPacket(&ack_one);
2260
2261 // Lose a packet and ensure it triggers retransmission.
2262 QuicAckFrame nack_two = InitAckFrame(3);
2263 NackPacket(2, &nack_two);
2264 SequenceNumberSet lost_packets;
2265 lost_packets.insert(2);
2266 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2267 .WillOnce(Return(lost_packets));
2268 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2269 EXPECT_CALL(*send_algorithm_,
2270 OnPacketSent(_, _, _, second_packet_size - kQuicVersionSize, _)).
2271 Times(1);
2272 ProcessAckPacket(&nack_two);
2273 }
2274
2275 TEST_P(QuicConnectionTest, DiscardRetransmit) {
2276 QuicPacketSequenceNumber last_packet;
2277 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2278 SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet); // Packet 2
2279 SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet); // Packet 3
2280
2281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2282
2283 // Instigate a loss with an ack.
2284 QuicAckFrame nack_two = InitAckFrame(3);
2285 NackPacket(2, &nack_two);
2286 // The first nack should trigger a fast retransmission, but we'll be
2287 // write blocked, so the packet will be queued.
2288 BlockOnNextWrite();
2289 SequenceNumberSet lost_packets;
2290 lost_packets.insert(2);
2291 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2292 .WillOnce(Return(lost_packets));
2293 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2294 ProcessAckPacket(&nack_two);
2295 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2296
2297 // Now, ack the previous transmission.
2298 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2299 .WillOnce(Return(SequenceNumberSet()));
2300 QuicAckFrame ack_all = InitAckFrame(3);
2301 ProcessAckPacket(&ack_all);
2302
2303 // Unblock the socket and attempt to send the queued packets. However,
2304 // since the previous transmission has been acked, we will not
2305 // send the retransmission.
2306 EXPECT_CALL(*send_algorithm_,
2307 OnPacketSent(_, _, _, _, _)).Times(0);
2308
2309 writer_->SetWritable();
2310 connection_.OnCanWrite();
2311
2312 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2313 }
2314
2315 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
2316 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2317 QuicPacketSequenceNumber largest_observed;
2318 QuicByteCount packet_size;
2319 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2320 .WillOnce(DoAll(SaveArg<2>(&largest_observed), SaveArg<3>(&packet_size),
2321 Return(true)));
2322 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2323
2324 QuicAckFrame frame = InitAckFrame(1);
2325 NackPacket(largest_observed, &frame);
2326 // The first nack should retransmit the largest observed packet.
2327 SequenceNumberSet lost_packets;
2328 lost_packets.insert(1);
2329 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2330 .WillOnce(Return(lost_packets));
2331 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2332 EXPECT_CALL(*send_algorithm_,
2333 OnPacketSent(_, _, _, packet_size - kQuicVersionSize, _));
2334 ProcessAckPacket(&frame);
2335 }
2336
2337 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
2338 for (int i = 0; i < 10; ++i) {
2339 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2340 connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, nullptr);
2341 }
2342
2343 // Block the writer and ensure they're queued.
2344 BlockOnNextWrite();
2345 clock_.AdvanceTime(DefaultRetransmissionTime());
2346 // Only one packet should be retransmitted.
2347 if (!FLAGS_quic_use_new_rto) {
2348 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2349 }
2350 connection_.GetRetransmissionAlarm()->Fire();
2351 EXPECT_TRUE(connection_.HasQueuedData());
2352
2353 // Unblock the writer.
2354 writer_->SetWritable();
2355 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2356 2 * DefaultRetransmissionTime().ToMicroseconds()));
2357 // Retransmit already retransmitted packets event though the sequence number
2358 // greater than the largest observed.
2359 if (FLAGS_quic_use_new_rto) {
2360 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
2361 } else {
2362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(10);
2363 }
2364 connection_.GetRetransmissionAlarm()->Fire();
2365 connection_.OnCanWrite();
2366 }
2367
2368 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
2369 BlockOnNextWrite();
2370 writer_->set_is_write_blocked_data_buffered(true);
2371 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2372 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2373 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2374
2375 writer_->SetWritable();
2376 connection_.OnCanWrite();
2377 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2378 }
2379
2380 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
2381 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2382 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2383 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2384
2385 BlockOnNextWrite();
2386 writer_->set_is_write_blocked_data_buffered(true);
2387 // Simulate the retransmission alarm firing.
2388 if (!FLAGS_quic_use_new_rto) {
2389 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(_));
2390 }
2391 clock_.AdvanceTime(DefaultRetransmissionTime());
2392 connection_.GetRetransmissionAlarm()->Fire();
2393
2394 // Ack the sent packet before the callback returns, which happens in
2395 // rare circumstances with write blocked sockets.
2396 QuicAckFrame ack = InitAckFrame(1);
2397 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2398 if (!FLAGS_quic_use_new_rto) {
2399 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
2400 }
2401 ProcessAckPacket(&ack);
2402
2403 writer_->SetWritable();
2404 connection_.OnCanWrite();
2405 // There is now a pending packet, but with no retransmittable frames.
2406 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2407 EXPECT_FALSE(connection_.sent_packet_manager().HasRetransmittableFrames(2));
2408 }
2409
2410 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2411 // Block the connection.
2412 BlockOnNextWrite();
2413 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
2414 EXPECT_EQ(1u, writer_->packets_write_attempts());
2415 EXPECT_TRUE(writer_->IsWriteBlocked());
2416
2417 // Set the send and resumption alarms. Fire the alarms and ensure they don't
2418 // attempt to write.
2419 connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2420 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2421 connection_.GetResumeWritesAlarm()->Fire();
2422 connection_.GetSendAlarm()->Fire();
2423 EXPECT_TRUE(writer_->IsWriteBlocked());
2424 EXPECT_EQ(1u, writer_->packets_write_attempts());
2425 }
2426
2427 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2428 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2429 int offset = 0;
2430 // Send packets 1 to 15.
2431 for (int i = 0; i < 15; ++i) {
2432 SendStreamDataToPeer(1, "foo", offset, !kFin, nullptr);
2433 offset += 3;
2434 }
2435
2436 // Ack 15, nack 1-14.
2437 SequenceNumberSet lost_packets;
2438 QuicAckFrame nack = InitAckFrame(15);
2439 for (int i = 1; i < 15; ++i) {
2440 NackPacket(i, &nack);
2441 lost_packets.insert(i);
2442 }
2443
2444 // 14 packets have been NACK'd and lost. In TCP cubic, PRR limits
2445 // the retransmission rate in the case of burst losses.
2446 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2447 .WillOnce(Return(lost_packets));
2448 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2449 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2450 ProcessAckPacket(&nack);
2451 }
2452
2453 // Test sending multiple acks from the connection to the session.
2454 TEST_P(QuicConnectionTest, MultipleAcks) {
2455 QuicPacketSequenceNumber last_packet;
2456 SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet); // Packet 1
2457 EXPECT_EQ(1u, last_packet);
2458 SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet); // Packet 2
2459 EXPECT_EQ(2u, last_packet);
2460 SendAckPacketToPeer(); // Packet 3
2461 SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet); // Packet 4
2462 EXPECT_EQ(4u, last_packet);
2463 SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet); // Packet 5
2464 EXPECT_EQ(5u, last_packet);
2465 SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet); // Packet 6
2466 EXPECT_EQ(6u, last_packet);
2467
2468 // Client will ack packets 1, 2, [!3], 4, 5.
2469 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2470 QuicAckFrame frame1 = InitAckFrame(5);
2471 NackPacket(3, &frame1);
2472 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2473 ProcessAckPacket(&frame1);
2474
2475 // Now the client implicitly acks 3, and explicitly acks 6.
2476 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2477 QuicAckFrame frame2 = InitAckFrame(6);
2478 ProcessAckPacket(&frame2);
2479 }
2480
2481 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2482 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr); // Packet 1;
2483 // From now on, we send acks, so the send algorithm won't mark them pending.
2484 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2485 .WillByDefault(Return(false));
2486 SendAckPacketToPeer(); // Packet 2
2487
2488 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2489 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2490 QuicAckFrame frame = InitAckFrame(1);
2491 ProcessAckPacket(&frame);
2492
2493 // Verify that our internal state has least-unacked as 2, because we're still
2494 // waiting for a potential ack for 2.
2495
2496 EXPECT_EQ(2u, stop_waiting()->least_unacked);
2497
2498 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2499 frame = InitAckFrame(2);
2500 ProcessAckPacket(&frame);
2501 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2502
2503 // When we send an ack, we make sure our least-unacked makes sense. In this
2504 // case since we're not waiting on an ack for 2 and all packets are acked, we
2505 // set it to 3.
2506 SendAckPacketToPeer(); // Packet 3
2507 // Least_unacked remains at 3 until another ack is received.
2508 EXPECT_EQ(3u, stop_waiting()->least_unacked);
2509 // Check that the outgoing ack had its sequence number as least_unacked.
2510 EXPECT_EQ(3u, least_unacked());
2511
2512 // Ack the ack, which updates the rtt and raises the least unacked.
2513 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2514 frame = InitAckFrame(3);
2515 ProcessAckPacket(&frame);
2516
2517 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2518 .WillByDefault(Return(true));
2519 SendStreamDataToPeer(1, "bar", 3, false, nullptr); // Packet 4
2520 EXPECT_EQ(4u, stop_waiting()->least_unacked);
2521 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2522 .WillByDefault(Return(false));
2523 SendAckPacketToPeer(); // Packet 5
2524 EXPECT_EQ(4u, least_unacked());
2525
2526 // Send two data packets at the end, and ensure if the last one is acked,
2527 // the least unacked is raised above the ack packets.
2528 ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2529 .WillByDefault(Return(true));
2530 SendStreamDataToPeer(1, "bar", 6, false, nullptr); // Packet 6
2531 SendStreamDataToPeer(1, "bar", 9, false, nullptr); // Packet 7
2532
2533 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2534 frame = InitAckFrame(7);
2535 NackPacket(5, &frame);
2536 NackPacket(6, &frame);
2537 ProcessAckPacket(&frame);
2538
2539 EXPECT_EQ(6u, stop_waiting()->least_unacked);
2540 }
2541
2542 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2544
2545 // Don't send missing packet 1.
2546 ProcessFecPacket(2, 1, true, !kEntropyFlag, nullptr);
2547 // Entropy flag should be false, so entropy should be 0.
2548 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2549 }
2550
2551 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingSeqNumLengths) {
2552 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2553
2554 // Set up a debug visitor to the connection.
2555 FecQuicConnectionDebugVisitor* fec_visitor =
2556 new FecQuicConnectionDebugVisitor();
2557 connection_.set_debug_visitor(fec_visitor);
2558
2559 QuicPacketSequenceNumber fec_packet = 0;
2560 QuicSequenceNumberLength lengths[] = {PACKET_6BYTE_SEQUENCE_NUMBER,
2561 PACKET_4BYTE_SEQUENCE_NUMBER,
2562 PACKET_2BYTE_SEQUENCE_NUMBER,
2563 PACKET_1BYTE_SEQUENCE_NUMBER};
2564 // For each sequence number length size, revive a packet and check sequence
2565 // number length in the revived packet.
2566 for (size_t i = 0; i < arraysize(lengths); ++i) {
2567 // Set sequence_number_length_ (for data and FEC packets).
2568 sequence_number_length_ = lengths[i];
2569 fec_packet += 2;
2570 // Don't send missing packet, but send fec packet right after it.
2571 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2572 // Sequence number length in the revived header should be the same as
2573 // in the original data/fec packet headers.
2574 EXPECT_EQ(sequence_number_length_, fec_visitor->revived_header().
2575 public_header.sequence_number_length);
2576 }
2577 }
2578
2579 TEST_P(QuicConnectionTest, ReviveMissingPacketWithVaryingConnectionIdLengths) {
2580 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2581
2582 // Set up a debug visitor to the connection.
2583 FecQuicConnectionDebugVisitor* fec_visitor =
2584 new FecQuicConnectionDebugVisitor();
2585 connection_.set_debug_visitor(fec_visitor);
2586
2587 QuicPacketSequenceNumber fec_packet = 0;
2588 QuicConnectionIdLength lengths[] = {PACKET_8BYTE_CONNECTION_ID,
2589 PACKET_4BYTE_CONNECTION_ID,
2590 PACKET_1BYTE_CONNECTION_ID,
2591 PACKET_0BYTE_CONNECTION_ID};
2592 // For each connection id length size, revive a packet and check connection
2593 // id length in the revived packet.
2594 for (size_t i = 0; i < arraysize(lengths); ++i) {
2595 // Set connection id length (for data and FEC packets).
2596 connection_id_length_ = lengths[i];
2597 fec_packet += 2;
2598 // Don't send missing packet, but send fec packet right after it.
2599 ProcessFecPacket(fec_packet, fec_packet - 1, true, !kEntropyFlag, nullptr);
2600 // Connection id length in the revived header should be the same as
2601 // in the original data/fec packet headers.
2602 EXPECT_EQ(connection_id_length_,
2603 fec_visitor->revived_header().public_header.connection_id_length);
2604 }
2605 }
2606
2607 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2608 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2609
2610 ProcessFecProtectedPacket(1, false, kEntropyFlag);
2611 // Don't send missing packet 2.
2612 ProcessFecPacket(3, 1, true, !kEntropyFlag, nullptr);
2613 // Entropy flag should be true, so entropy should not be 0.
2614 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2615 }
2616
2617 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2618 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2619
2620 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2621 // Don't send missing packet 2.
2622 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2623 ProcessFecPacket(4, 1, true, kEntropyFlag, nullptr);
2624 // Ensure QUIC no longer revives entropy for lost packets.
2625 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2626 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2627 }
2628
2629 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2630 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2631
2632 // Don't send missing packet 1.
2633 ProcessFecPacket(3, 1, false, !kEntropyFlag, nullptr);
2634 // Out of order.
2635 ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2636 // Entropy flag should be false, so entropy should be 0.
2637 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2638 }
2639
2640 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2642
2643 ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2644 // Don't send missing packet 2.
2645 ProcessFecPacket(6, 1, false, kEntropyFlag, nullptr);
2646 ProcessFecProtectedPacket(3, false, kEntropyFlag);
2647 ProcessFecProtectedPacket(4, false, kEntropyFlag);
2648 ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2649 // Ensure entropy is not revived for the missing packet.
2650 EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2651 EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2652 }
2653
2654 TEST_P(QuicConnectionTest, TLP) {
2655 QuicSentPacketManagerPeer::SetMaxTailLossProbes(manager_, 1);
2656
2657 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2658 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2659 QuicTime retransmission_time =
2660 connection_.GetRetransmissionAlarm()->deadline();
2661 EXPECT_NE(QuicTime::Zero(), retransmission_time);
2662
2663 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2664 // Simulate the retransmission alarm firing and sending a tlp,
2665 // so send algorithm's OnRetransmissionTimeout is not called.
2666 clock_.AdvanceTime(retransmission_time.Subtract(clock_.Now()));
2667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2668 connection_.GetRetransmissionAlarm()->Fire();
2669 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2670 // We do not raise the high water mark yet.
2671 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2672 }
2673
2674 TEST_P(QuicConnectionTest, RTO) {
2675 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2676 DefaultRetransmissionTime());
2677 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2678 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2679
2680 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
2681 EXPECT_EQ(default_retransmission_time,
2682 connection_.GetRetransmissionAlarm()->deadline());
2683 // Simulate the retransmission alarm firing.
2684 clock_.AdvanceTime(DefaultRetransmissionTime());
2685 if (!FLAGS_quic_use_new_rto) {
2686 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2687 }
2688 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
2689 connection_.GetRetransmissionAlarm()->Fire();
2690 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
2691 // We do not raise the high water mark yet.
2692 EXPECT_EQ(1u, stop_waiting()->least_unacked);
2693 }
2694
2695 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2696 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2697 DefaultRetransmissionTime());
2698 use_tagging_decrypter();
2699
2700 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2701 // the end of the packet. We can test this to check which encrypter was used.
2702 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2703 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2704 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2705
2706 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2707 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2708 SendStreamDataToPeer(3, "foo", 0, !kFin, nullptr);
2709 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2710
2711 EXPECT_EQ(default_retransmission_time,
2712 connection_.GetRetransmissionAlarm()->deadline());
2713 {
2714 InSequence s;
2715 if (!FLAGS_quic_use_new_rto) {
2716 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2717 }
2718 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 3, _, _));
2719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 4, _, _));
2720 }
2721
2722 // Simulate the retransmission alarm firing.
2723 clock_.AdvanceTime(DefaultRetransmissionTime());
2724 connection_.GetRetransmissionAlarm()->Fire();
2725
2726 // Packet should have been sent with ENCRYPTION_NONE.
2727 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_previous_packet());
2728
2729 // Packet should have been sent with ENCRYPTION_INITIAL.
2730 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2731 }
2732
2733 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2734 use_tagging_decrypter();
2735 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2736 // the end of the packet. We can test this to check which encrypter was used.
2737 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2738
2739 // Attempt to send a handshake message and have the socket block.
2740 EXPECT_CALL(*send_algorithm_,
2741 TimeUntilSend(_, _, _)).WillRepeatedly(
2742 testing::Return(QuicTime::Delta::Zero()));
2743 BlockOnNextWrite();
2744 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2745 // The packet should be serialized, but not queued.
2746 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2747
2748 // Switch to the new encrypter.
2749 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2750 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2751
2752 // Now become writeable and flush the packets.
2753 writer_->SetWritable();
2754 EXPECT_CALL(visitor_, OnCanWrite());
2755 connection_.OnCanWrite();
2756 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2757
2758 // Verify that the handshake packet went out at the null encryption.
2759 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
2760 }
2761
2762 TEST_P(QuicConnectionTest,
2763 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2764 use_tagging_decrypter();
2765 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2766 QuicPacketSequenceNumber sequence_number;
2767 SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2768
2769 // Simulate the retransmission alarm firing and the socket blocking.
2770 BlockOnNextWrite();
2771 if (!FLAGS_quic_use_new_rto) {
2772 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2773 }
2774 clock_.AdvanceTime(DefaultRetransmissionTime());
2775 connection_.GetRetransmissionAlarm()->Fire();
2776
2777 // Go forward secure.
2778 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2779 new TaggingEncrypter(0x02));
2780 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2781 connection_.NeuterUnencryptedPackets();
2782
2783 EXPECT_EQ(QuicTime::Zero(),
2784 connection_.GetRetransmissionAlarm()->deadline());
2785 // Unblock the socket and ensure that no packets are sent.
2786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2787 writer_->SetWritable();
2788 connection_.OnCanWrite();
2789 }
2790
2791 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2792 use_tagging_decrypter();
2793 connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2794 connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2795
2796 SendStreamDataToPeer(1, "foo", 0, !kFin, nullptr);
2797
2798 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2799 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2800
2801 SendStreamDataToPeer(2, "bar", 0, !kFin, nullptr);
2802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2803
2804 connection_.RetransmitUnackedPackets(ALL_INITIAL_RETRANSMISSION);
2805 }
2806
2807 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilClientIsReady) {
2808 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2809 // the end of the packet. We can test this to check which encrypter was used.
2810 use_tagging_decrypter();
2811 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2812 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2813 SendAckPacketToPeer();
2814 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2815
2816 // Set a forward-secure encrypter but do not make it the default, and verify
2817 // that it is not yet used.
2818 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2819 new TaggingEncrypter(0x03));
2820 SendAckPacketToPeer();
2821 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2822
2823 // Now simulate receipt of a forward-secure packet and verify that the
2824 // forward-secure encrypter is now used.
2825 connection_.OnDecryptedPacket(ENCRYPTION_FORWARD_SECURE);
2826 SendAckPacketToPeer();
2827 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2828 }
2829
2830 TEST_P(QuicConnectionTest, DelayForwardSecureEncryptionUntilManyPacketSent) {
2831 // Set a congestion window of 10 packets.
2832 QuicPacketCount congestion_window = 10;
2833 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
2834 Return(congestion_window * kDefaultMaxPacketSize));
2835
2836 // A TaggingEncrypter puts kTagSize copies of the given byte (0x02 here) at
2837 // the end of the packet. We can test this to check which encrypter was used.
2838 use_tagging_decrypter();
2839 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2840 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2841 SendAckPacketToPeer();
2842 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2843
2844 // Set a forward-secure encrypter but do not make it the default, and
2845 // verify that it is not yet used.
2846 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2847 new TaggingEncrypter(0x03));
2848 SendAckPacketToPeer();
2849 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2850
2851 // Now send a packet "Far enough" after the encrypter was set and verify that
2852 // the forward-secure encrypter is now used.
2853 for (uint64 i = 0; i < 3 * congestion_window - 1; ++i) {
2854 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
2855 SendAckPacketToPeer();
2856 }
2857 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
2858 }
2859
2860 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2861 // SetFromConfig is always called after construction from InitializeSession.
2862 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2863 QuicConfig config;
2864 connection_.SetFromConfig(config);
2865 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2866 use_tagging_decrypter();
2867
2868 const uint8 tag = 0x07;
2869 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2870
2871 // Process an encrypted packet which can not yet be decrypted which should
2872 // result in the packet being buffered.
2873 ProcessDataPacketAtLevel(1, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2874
2875 // Transition to the new encryption state and process another encrypted packet
2876 // which should result in the original packet being processed.
2877 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
2878 ENCRYPTION_INITIAL);
2879 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2880 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2881 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2);
2882 ProcessDataPacketAtLevel(2, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2883
2884 // Finally, process a third packet and note that we do not reprocess the
2885 // buffered packet.
2886 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2887 ProcessDataPacketAtLevel(3, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2888 }
2889
2890 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePackets) {
2891 // SetFromConfig is always called after construction from InitializeSession.
2892 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
2893 QuicConfig config;
2894 config.set_max_undecryptable_packets(100);
2895 connection_.SetFromConfig(config);
2896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2897 use_tagging_decrypter();
2898
2899 const uint8 tag = 0x07;
2900 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2901
2902 // Process an encrypted packet which can not yet be decrypted which should
2903 // result in the packet being buffered.
2904 for (QuicPacketSequenceNumber i = 1; i <= 100; ++i) {
2905 ProcessDataPacketAtLevel(i, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2906 }
2907
2908 // Transition to the new encryption state and process another encrypted packet
2909 // which should result in the original packets being processed.
2910 connection_.SetDecrypter(new StrictTaggingDecrypter(tag), ENCRYPTION_INITIAL);
2911 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2912 connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2913 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(101);
2914 ProcessDataPacketAtLevel(101, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2915
2916 // Finally, process a third packet and note that we do not reprocess the
2917 // buffered packet.
2918 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
2919 ProcessDataPacketAtLevel(102, 0, kEntropyFlag, ENCRYPTION_INITIAL);
2920 }
2921
2922 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2923 QuicByteCount first_packet_size;
2924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2925 DoAll(SaveArg<3>(&first_packet_size), Return(true)));
2926
2927 connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, nullptr);
2928 QuicByteCount second_packet_size;
2929 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2930 DoAll(SaveArg<3>(&second_packet_size), Return(true)));
2931 connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, nullptr);
2932 EXPECT_NE(first_packet_size, second_packet_size);
2933 // Advance the clock by huge time to make sure packets will be retransmitted.
2934 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2935 if (!FLAGS_quic_use_new_rto) {
2936 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2937 }
2938 {
2939 InSequence s;
2940 EXPECT_CALL(*send_algorithm_,
2941 OnPacketSent(_, _, _, first_packet_size, _));
2942 EXPECT_CALL(*send_algorithm_,
2943 OnPacketSent(_, _, _, second_packet_size, _));
2944 }
2945 connection_.GetRetransmissionAlarm()->Fire();
2946
2947 // Advance again and expect the packets to be sent again in the same order.
2948 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2949 if (!FLAGS_quic_use_new_rto) {
2950 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2951 }
2952 {
2953 InSequence s;
2954 EXPECT_CALL(*send_algorithm_,
2955 OnPacketSent(_, _, _, first_packet_size, _));
2956 EXPECT_CALL(*send_algorithm_,
2957 OnPacketSent(_, _, _, second_packet_size, _));
2958 }
2959 connection_.GetRetransmissionAlarm()->Fire();
2960 }
2961
2962 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2963 BlockOnNextWrite();
2964 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
2965 // Make sure that RTO is not started when the packet is queued.
2966 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2967
2968 // Test that RTO is started once we write to the socket.
2969 writer_->SetWritable();
2970 connection_.OnCanWrite();
2971 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2972 }
2973
2974 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2975 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2976 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2977 .Times(2);
2978 connection_.SendStreamDataWithString(2, "foo", 0, !kFin, nullptr);
2979 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, nullptr);
2980 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2981 EXPECT_TRUE(retransmission_alarm->IsSet());
2982 EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2983 retransmission_alarm->deadline());
2984
2985 // Advance the time right before the RTO, then receive an ack for the first
2986 // packet to delay the RTO.
2987 clock_.AdvanceTime(DefaultRetransmissionTime());
2988 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
2989 QuicAckFrame ack = InitAckFrame(1);
2990 ProcessAckPacket(&ack);
2991 EXPECT_TRUE(retransmission_alarm->IsSet());
2992 EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2993
2994 // Move forward past the original RTO and ensure the RTO is still pending.
2995 clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2996
2997 // Ensure the second packet gets retransmitted when it finally fires.
2998 EXPECT_TRUE(retransmission_alarm->IsSet());
2999 EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
3000 if (!FLAGS_quic_use_new_rto) {
3001 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3002 }
3003 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3004 // Manually cancel the alarm to simulate a real test.
3005 connection_.GetRetransmissionAlarm()->Fire();
3006
3007 // The new retransmitted sequence number should set the RTO to a larger value
3008 // than previously.
3009 EXPECT_TRUE(retransmission_alarm->IsSet());
3010 QuicTime next_rto_time = retransmission_alarm->deadline();
3011 QuicTime expected_rto_time =
3012 connection_.sent_packet_manager().GetRetransmissionTime();
3013 EXPECT_EQ(next_rto_time, expected_rto_time);
3014 }
3015
3016 TEST_P(QuicConnectionTest, TestQueued) {
3017 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3018 BlockOnNextWrite();
3019 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
3020 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3021
3022 // Unblock the writes and actually send.
3023 writer_->SetWritable();
3024 connection_.OnCanWrite();
3025 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3026 }
3027
3028 TEST_P(QuicConnectionTest, CloseFecGroup) {
3029 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3030 // Don't send missing packet 1.
3031 // Don't send missing packet 2.
3032 ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3033 // Don't send missing FEC packet 3.
3034 ASSERT_EQ(1u, connection_.NumFecGroups());
3035
3036 // Now send non-fec protected ack packet and close the group.
3037 peer_creator_.set_sequence_number(4);
3038 QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
3039 ProcessStopWaitingPacket(&frame);
3040 ASSERT_EQ(0u, connection_.NumFecGroups());
3041 }
3042
3043 TEST_P(QuicConnectionTest, InitialTimeout) {
3044 EXPECT_TRUE(connection_.connected());
3045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3046 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3047
3048 // SetFromConfig sets the initial timeouts before negotiation.
3049 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3050 QuicConfig config;
3051 connection_.SetFromConfig(config);
3052 // Subtract a second from the idle timeout on the client side.
3053 QuicTime default_timeout = clock_.ApproximateNow().Add(
3054 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3055 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3056
3057 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3058 // Simulate the timeout alarm firing.
3059 clock_.AdvanceTime(
3060 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
3061 connection_.GetTimeoutAlarm()->Fire();
3062
3063 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3064 EXPECT_FALSE(connection_.connected());
3065
3066 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3067 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3068 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3069 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3070 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3071 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3072 }
3073
3074 TEST_P(QuicConnectionTest, OverallTimeout) {
3075 // Use a shorter overall connection timeout than idle timeout for this test.
3076 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
3077 connection_.SetNetworkTimeouts(timeout, timeout);
3078 EXPECT_TRUE(connection_.connected());
3079 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
3080
3081 QuicTime overall_timeout = clock_.ApproximateNow().Add(timeout).Subtract(
3082 QuicTime::Delta::FromSeconds(1));
3083 EXPECT_EQ(overall_timeout, connection_.GetTimeoutAlarm()->deadline());
3084 EXPECT_TRUE(connection_.connected());
3085
3086 // Send and ack new data 3 seconds later to lengthen the idle timeout.
3087 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3088 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
3089 QuicAckFrame frame = InitAckFrame(1);
3090 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3091 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3092 ProcessAckPacket(&frame);
3093
3094 // Fire early to verify it wouldn't timeout yet.
3095 connection_.GetTimeoutAlarm()->Fire();
3096 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3097 EXPECT_TRUE(connection_.connected());
3098
3099 clock_.AdvanceTime(timeout.Subtract(QuicTime::Delta::FromSeconds(2)));
3100
3101 EXPECT_CALL(visitor_,
3102 OnConnectionClosed(QUIC_CONNECTION_OVERALL_TIMED_OUT, false));
3103 // Simulate the timeout alarm firing.
3104 connection_.GetTimeoutAlarm()->Fire();
3105
3106 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3107 EXPECT_FALSE(connection_.connected());
3108
3109 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3110 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3111 EXPECT_FALSE(connection_.GetFecAlarm()->IsSet());
3112 EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
3113 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3114 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
3115 }
3116
3117 TEST_P(QuicConnectionTest, PingAfterSend) {
3118 EXPECT_TRUE(connection_.connected());
3119 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(true));
3120 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3121
3122 // Advance to 5ms, and send a packet to the peer, which will set
3123 // the ping alarm.
3124 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3125 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
3126 SendStreamDataToPeer(1, "GET /", 0, kFin, nullptr);
3127 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3128 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15)),
3129 connection_.GetPingAlarm()->deadline());
3130
3131 // Now recevie and ACK of the previous packet, which will move the
3132 // ping alarm forward.
3133 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3134 QuicAckFrame frame = InitAckFrame(1);
3135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3136 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3137 ProcessAckPacket(&frame);
3138 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
3139 // The ping timer is set slightly less than 15 seconds in the future, because
3140 // of the 1s ping timer alarm granularity.
3141 EXPECT_EQ(clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(15))
3142 .Subtract(QuicTime::Delta::FromMilliseconds(5)),
3143 connection_.GetPingAlarm()->deadline());
3144
3145 writer_->Reset();
3146 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
3147 connection_.GetPingAlarm()->Fire();
3148 EXPECT_EQ(1u, writer_->frame_count());
3149 ASSERT_EQ(1u, writer_->ping_frames().size());
3150 writer_->Reset();
3151
3152 EXPECT_CALL(visitor_, HasOpenDataStreams()).WillRepeatedly(Return(false));
3153 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
3154 SendAckPacketToPeer();
3155
3156 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
3157 }
3158
3159 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
3160 EXPECT_TRUE(connection_.connected());
3161 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3162 QuicConfig config;
3163 connection_.SetFromConfig(config);
3164 EXPECT_FALSE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3165
3166 const QuicTime::Delta initial_idle_timeout =
3167 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
3168 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3169 QuicTime default_timeout = clock_.ApproximateNow().Add(initial_idle_timeout);
3170
3171 // When we send a packet, the timeout will change to 5ms +
3172 // kInitialIdleTimeoutSecs.
3173 clock_.AdvanceTime(five_ms);
3174
3175 // Send an ack so we don't set the retransmission alarm.
3176 SendAckPacketToPeer();
3177 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3178
3179 // The original alarm will fire. We should not time out because we had a
3180 // network event at t=5ms. The alarm will reregister.
3181 clock_.AdvanceTime(initial_idle_timeout.Subtract(five_ms));
3182 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3183 connection_.GetTimeoutAlarm()->Fire();
3184 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3185 EXPECT_TRUE(connection_.connected());
3186 EXPECT_EQ(default_timeout.Add(five_ms),
3187 connection_.GetTimeoutAlarm()->deadline());
3188
3189 // This time, we should time out.
3190 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3192 clock_.AdvanceTime(five_ms);
3193 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3194 connection_.GetTimeoutAlarm()->Fire();
3195 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3196 EXPECT_FALSE(connection_.connected());
3197 }
3198
3199 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentClose) {
3200 // Same test as above, but complete a handshake which enables silent close,
3201 // causing no connection close packet to be sent.
3202 EXPECT_TRUE(connection_.connected());
3203 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
3204 QuicConfig config;
3205
3206 // Create a handshake message that also enables silent close.
3207 CryptoHandshakeMessage msg;
3208 string error_details;
3209 QuicConfig client_config;
3210 client_config.SetInitialStreamFlowControlWindowToSend(
3211 kInitialStreamFlowControlWindowForTest);
3212 client_config.SetInitialSessionFlowControlWindowToSend(
3213 kInitialSessionFlowControlWindowForTest);
3214 client_config.SetIdleConnectionStateLifetime(
3215 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs),
3216 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs));
3217 client_config.ToHandshakeMessage(&msg);
3218 const QuicErrorCode error =
3219 config.ProcessPeerHello(msg, CLIENT, &error_details);
3220 EXPECT_EQ(QUIC_NO_ERROR, error);
3221
3222 connection_.SetFromConfig(config);
3223 EXPECT_TRUE(QuicConnectionPeer::IsSilentCloseEnabled(&connection_));
3224
3225 const QuicTime::Delta default_idle_timeout =
3226 QuicTime::Delta::FromSeconds(kDefaultIdleTimeoutSecs - 1);
3227 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
3228 QuicTime default_timeout = clock_.ApproximateNow().Add(default_idle_timeout);
3229
3230 // When we send a packet, the timeout will change to 5ms +
3231 // kInitialIdleTimeoutSecs.
3232 clock_.AdvanceTime(five_ms);
3233
3234 // Send an ack so we don't set the retransmission alarm.
3235 SendAckPacketToPeer();
3236 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
3237
3238 // The original alarm will fire. We should not time out because we had a
3239 // network event at t=5ms. The alarm will reregister.
3240 clock_.AdvanceTime(default_idle_timeout.Subtract(five_ms));
3241 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
3242 connection_.GetTimeoutAlarm()->Fire();
3243 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
3244 EXPECT_TRUE(connection_.connected());
3245 EXPECT_EQ(default_timeout.Add(five_ms),
3246 connection_.GetTimeoutAlarm()->deadline());
3247
3248 // This time, we should time out.
3249 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
3250 clock_.AdvanceTime(five_ms);
3251 EXPECT_EQ(default_timeout.Add(five_ms), clock_.ApproximateNow());
3252 connection_.GetTimeoutAlarm()->Fire();
3253 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
3254 EXPECT_FALSE(connection_.connected());
3255 }
3256
3257 TEST_P(QuicConnectionTest, SendScheduler) {
3258 // Test that if we send a packet without delay, it is not queued.
3259 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3261 connection_.SendPacket(
3262 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3263 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3264 }
3265
3266 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
3267 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3268 BlockOnNextWrite();
3269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3270 connection_.SendPacket(
3271 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3272 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3273 }
3274
3275 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
3276 // All packets carry version info till version is negotiated.
3277 size_t payload_length;
3278 size_t length = GetPacketLengthForOneStream(
3279 connection_.version(), kIncludeVersion,
3280 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3281 NOT_IN_FEC_GROUP, &payload_length);
3282 creator_->set_max_packet_length(length);
3283
3284 // Queue the first packet.
3285 EXPECT_CALL(*send_algorithm_,
3286 TimeUntilSend(_, _, _)).WillOnce(
3287 testing::Return(QuicTime::Delta::FromMicroseconds(10)));
3288 const string payload(payload_length, 'a');
3289 EXPECT_EQ(0u, connection_.SendStreamDataWithString(3, payload, 0, !kFin,
3290 nullptr).bytes_consumed);
3291 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3292 }
3293
3294 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
3295 // All packets carry version info till version is negotiated.
3296 size_t payload_length;
3297 // GetPacketLengthForOneStream() assumes a stream offset of 0 in determining
3298 // packet length. The size of the offset field in a stream frame is 0 for
3299 // offset 0, and 2 for non-zero offsets up through 16K. Increase
3300 // max_packet_length by 2 so that subsequent packets containing subsequent
3301 // stream frames with non-zero offets will fit within the packet length.
3302 size_t length = 2 + GetPacketLengthForOneStream(
3303 connection_.version(), kIncludeVersion,
3304 PACKET_8BYTE_CONNECTION_ID, PACKET_1BYTE_SEQUENCE_NUMBER,
3305 NOT_IN_FEC_GROUP, &payload_length);
3306 creator_->set_max_packet_length(length);
3307
3308 // Queue the first packet.
3309 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
3310 // The first stream frame will have 2 fewer overhead bytes than the other six.
3311 const string payload(payload_length * 7 + 2, 'a');
3312 EXPECT_EQ(payload.size(),
3313 connection_.SendStreamDataWithString(1, payload, 0, !kFin, nullptr)
3314 .bytes_consumed);
3315 }
3316
3317 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
3318 // Set up a larger payload than will fit in one packet.
3319 const string payload(connection_.max_packet_length(), 'a');
3320 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _)).Times(AnyNumber());
3321
3322 // Now send some packets with no truncation.
3323 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3324 EXPECT_EQ(payload.size(),
3325 connection_.SendStreamDataWithString(
3326 3, payload, 0, !kFin, nullptr).bytes_consumed);
3327 // Track the size of the second packet here. The overhead will be the largest
3328 // we see in this test, due to the non-truncated CID.
3329 size_t non_truncated_packet_size = writer_->last_packet_size();
3330
3331 // Change to a 4 byte CID.
3332 QuicConfig config;
3333 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 4);
3334 connection_.SetFromConfig(config);
3335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3336 EXPECT_EQ(payload.size(),
3337 connection_.SendStreamDataWithString(
3338 3, payload, 0, !kFin, nullptr).bytes_consumed);
3339 // Verify that we have 8 fewer bytes than in the non-truncated case. The
3340 // first packet got 4 bytes of extra payload due to the truncation, and the
3341 // headers here are also 4 byte smaller.
3342 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8);
3343
3344
3345 // Change to a 1 byte CID.
3346 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 1);
3347 connection_.SetFromConfig(config);
3348 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3349 EXPECT_EQ(payload.size(),
3350 connection_.SendStreamDataWithString(
3351 3, payload, 0, !kFin, nullptr).bytes_consumed);
3352 // Just like above, we save 7 bytes on payload, and 7 on truncation.
3353 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 7 * 2);
3354
3355 // Change to a 0 byte CID.
3356 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
3357 connection_.SetFromConfig(config);
3358 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3359 EXPECT_EQ(payload.size(),
3360 connection_.SendStreamDataWithString(
3361 3, payload, 0, !kFin, nullptr).bytes_consumed);
3362 // Just like above, we save 8 bytes on payload, and 8 on truncation.
3363 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() + 8 * 2);
3364 }
3365
3366 TEST_P(QuicConnectionTest, SendDelayedAck) {
3367 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3368 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3369 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3370 const uint8 tag = 0x07;
3371 connection_.SetDecrypter(new StrictTaggingDecrypter(tag),
3372 ENCRYPTION_INITIAL);
3373 framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
3374 // Process a packet from the non-crypto stream.
3375 frame1_.stream_id = 3;
3376
3377 // The same as ProcessPacket(1) except that ENCRYPTION_INITIAL is used
3378 // instead of ENCRYPTION_NONE.
3379 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3380 ProcessDataPacketAtLevel(1, 0, !kEntropyFlag, ENCRYPTION_INITIAL);
3381
3382 // Check if delayed ack timer is running for the expected interval.
3383 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3384 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3385 // Simulate delayed ack alarm firing.
3386 connection_.GetAckAlarm()->Fire();
3387 // Check that ack is sent and that delayed ack alarm is reset.
3388 EXPECT_EQ(2u, writer_->frame_count());
3389 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3390 EXPECT_FALSE(writer_->ack_frames().empty());
3391 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3392 }
3393
3394 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
3395 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3396 ProcessPacket(1);
3397 // Check that ack is sent and that delayed ack alarm is set.
3398 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3399 QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
3400 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3401
3402 // Completing the handshake as the server does nothing.
3403 QuicConnectionPeer::SetIsServer(&connection_, true);
3404 connection_.OnHandshakeComplete();
3405 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3406 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
3407
3408 // Complete the handshake as the client decreases the delayed ack time to 0ms.
3409 QuicConnectionPeer::SetIsServer(&connection_, false);
3410 connection_.OnHandshakeComplete();
3411 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3412 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
3413 }
3414
3415 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
3416 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3417 ProcessPacket(1);
3418 ProcessPacket(2);
3419 // Check that ack is sent and that delayed ack alarm is reset.
3420 EXPECT_EQ(2u, writer_->frame_count());
3421 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3422 EXPECT_FALSE(writer_->ack_frames().empty());
3423 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3424 }
3425
3426 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
3427 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3428 // Drop one packet, triggering a sequence of acks.
3429 ProcessPacket(2);
3430 size_t frames_per_ack = 2;
3431 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3432 EXPECT_FALSE(writer_->ack_frames().empty());
3433 writer_->Reset();
3434 ProcessPacket(3);
3435 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3436 EXPECT_FALSE(writer_->ack_frames().empty());
3437 writer_->Reset();
3438 ProcessPacket(4);
3439 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3440 EXPECT_FALSE(writer_->ack_frames().empty());
3441 writer_->Reset();
3442 ProcessPacket(5);
3443 EXPECT_EQ(frames_per_ack, writer_->frame_count());
3444 EXPECT_FALSE(writer_->ack_frames().empty());
3445 writer_->Reset();
3446 // Now only set the timer on the 6th packet, instead of sending another ack.
3447 ProcessPacket(6);
3448 EXPECT_EQ(0u, writer_->frame_count());
3449 EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
3450 }
3451
3452 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
3453 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3454 ProcessPacket(1);
3455 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3456 nullptr);
3457 // Check that ack is bundled with outgoing data and that delayed ack
3458 // alarm is reset.
3459 EXPECT_EQ(3u, writer_->frame_count());
3460 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3461 EXPECT_FALSE(writer_->ack_frames().empty());
3462 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3463 }
3464
3465 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
3466 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3467 ProcessPacket(1);
3468 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3469 nullptr);
3470 // Check that ack is bundled with outgoing crypto data.
3471 EXPECT_EQ(3u, writer_->frame_count());
3472 EXPECT_FALSE(writer_->ack_frames().empty());
3473 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3474 }
3475
3476 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
3477 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3478 ProcessPacket(1);
3479 BlockOnNextWrite();
3480 writer_->set_is_write_blocked_data_buffered(true);
3481 connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin,
3482 nullptr);
3483 EXPECT_TRUE(writer_->IsWriteBlocked());
3484 EXPECT_FALSE(connection_.HasQueuedData());
3485 connection_.SendStreamDataWithString(kCryptoStreamId, "bar", 3, !kFin,
3486 nullptr);
3487 EXPECT_TRUE(writer_->IsWriteBlocked());
3488 EXPECT_TRUE(connection_.HasQueuedData());
3489 }
3490
3491 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
3492 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3493 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3494 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3495 IgnoreResult(InvokeWithoutArgs(&connection_,
3496 &TestConnection::SendCryptoStreamData)));
3497 // Process a packet from the crypto stream, which is frame1_'s default.
3498 // Receiving the CHLO as packet 2 first will cause the connection to
3499 // immediately send an ack, due to the packet gap.
3500 ProcessPacket(2);
3501 // Check that ack is sent and that delayed ack alarm is reset.
3502 EXPECT_EQ(3u, writer_->frame_count());
3503 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3504 EXPECT_EQ(1u, writer_->stream_frames().size());
3505 EXPECT_FALSE(writer_->ack_frames().empty());
3506 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3507 }
3508
3509 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
3510 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3511 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 0, !kFin,
3512 nullptr);
3513 connection_.SendStreamDataWithString(kClientDataStreamId1, "foo", 3, !kFin,
3514 nullptr);
3515 // Ack the second packet, which will retransmit the first packet.
3516 QuicAckFrame ack = InitAckFrame(2);
3517 NackPacket(1, &ack);
3518 SequenceNumberSet lost_packets;
3519 lost_packets.insert(1);
3520 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3521 .WillOnce(Return(lost_packets));
3522 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3523 ProcessAckPacket(&ack);
3524 EXPECT_EQ(1u, writer_->frame_count());
3525 EXPECT_EQ(1u, writer_->stream_frames().size());
3526 writer_->Reset();
3527
3528 // Now ack the retransmission, which will both raise the high water mark
3529 // and see if there is more data to send.
3530 ack = InitAckFrame(3);
3531 NackPacket(1, &ack);
3532 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3533 .WillOnce(Return(SequenceNumberSet()));
3534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3535 ProcessAckPacket(&ack);
3536
3537 // Check that no packet is sent and the ack alarm isn't set.
3538 EXPECT_EQ(0u, writer_->frame_count());
3539 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3540 writer_->Reset();
3541
3542 // Send the same ack, but send both data and an ack together.
3543 ack = InitAckFrame(3);
3544 NackPacket(1, &ack);
3545 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3546 .WillOnce(Return(SequenceNumberSet()));
3547 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
3548 IgnoreResult(InvokeWithoutArgs(
3549 &connection_,
3550 &TestConnection::EnsureWritableAndSendStreamData5)));
3551 ProcessAckPacket(&ack);
3552
3553 // Check that ack is bundled with outgoing data and the delayed ack
3554 // alarm is reset.
3555 EXPECT_EQ(3u, writer_->frame_count());
3556 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3557 EXPECT_FALSE(writer_->ack_frames().empty());
3558 EXPECT_EQ(1u, writer_->stream_frames().size());
3559 EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
3560 }
3561
3562 TEST_P(QuicConnectionTest, NoAckSentForClose) {
3563 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3564 ProcessPacket(1);
3565 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3566 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3567 ProcessClosePacket(2, 0);
3568 }
3569
3570 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
3571 EXPECT_TRUE(connection_.connected());
3572 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
3573 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
3574 EXPECT_FALSE(connection_.connected());
3575 EXPECT_FALSE(connection_.CanWriteStreamData());
3576 QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
3577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 1, _, _)).Times(0);
3578 connection_.SendPacket(
3579 ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
3580 }
3581
3582 TEST_P(QuicConnectionTest, PublicReset) {
3583 QuicPublicResetPacket header;
3584 header.public_header.connection_id = connection_id_;
3585 header.public_header.reset_flag = true;
3586 header.public_header.version_flag = false;
3587 header.rejected_sequence_number = 10101;
3588 scoped_ptr<QuicEncryptedPacket> packet(
3589 framer_.BuildPublicResetPacket(header));
3590 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
3591 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3592 }
3593
3594 TEST_P(QuicConnectionTest, GoAway) {
3595 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3596
3597 QuicGoAwayFrame goaway;
3598 goaway.last_good_stream_id = 1;
3599 goaway.error_code = QUIC_PEER_GOING_AWAY;
3600 goaway.reason_phrase = "Going away.";
3601 EXPECT_CALL(visitor_, OnGoAway(_));
3602 ProcessGoAwayPacket(&goaway);
3603 }
3604
3605 TEST_P(QuicConnectionTest, WindowUpdate) {
3606 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3607
3608 QuicWindowUpdateFrame window_update;
3609 window_update.stream_id = 3;
3610 window_update.byte_offset = 1234;
3611 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3612 ProcessFramePacket(QuicFrame(&window_update));
3613 }
3614
3615 TEST_P(QuicConnectionTest, Blocked) {
3616 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3617
3618 QuicBlockedFrame blocked;
3619 blocked.stream_id = 3;
3620 EXPECT_CALL(visitor_, OnBlockedFrames(_));
3621 ProcessFramePacket(QuicFrame(&blocked));
3622 }
3623
3624 TEST_P(QuicConnectionTest, ZeroBytePacket) {
3625 // Don't close the connection for zero byte packets.
3626 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
3627 QuicEncryptedPacket encrypted(nullptr, 0);
3628 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3629 }
3630
3631 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3632 // Set the sequence number of the ack packet to be least unacked (4).
3633 peer_creator_.set_sequence_number(3);
3634 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3635 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3636 ProcessStopWaitingPacket(&frame);
3637 EXPECT_TRUE(outgoing_ack()->missing_packets.empty());
3638 }
3639
3640 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3641 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3642 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3643 ProcessDataPacket(1, 1, kEntropyFlag);
3644 ProcessDataPacket(4, 1, kEntropyFlag);
3645 ProcessDataPacket(3, 1, !kEntropyFlag);
3646 ProcessDataPacket(7, 1, kEntropyFlag);
3647 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3648 }
3649
3650 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3651 // FEC packets should not change the entropy hash calculation.
3652 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3653 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3654 ProcessDataPacket(1, 1, kEntropyFlag);
3655 ProcessFecPacket(4, 1, false, kEntropyFlag, nullptr);
3656 ProcessDataPacket(3, 3, !kEntropyFlag);
3657 ProcessFecPacket(7, 3, false, kEntropyFlag, nullptr);
3658 EXPECT_EQ(146u, outgoing_ack()->entropy_hash);
3659 }
3660
3661 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3662 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3664 ProcessDataPacket(1, 1, kEntropyFlag);
3665 ProcessDataPacket(5, 1, kEntropyFlag);
3666 ProcessDataPacket(4, 1, !kEntropyFlag);
3667 EXPECT_EQ(34u, outgoing_ack()->entropy_hash);
3668 // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3669 peer_creator_.set_sequence_number(5);
3670 QuicPacketEntropyHash six_packet_entropy_hash = 0;
3671 QuicPacketEntropyHash kRandomEntropyHash = 129u;
3672 QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3673 frame.entropy_hash = kRandomEntropyHash;
3674 if (ProcessStopWaitingPacket(&frame)) {
3675 six_packet_entropy_hash = 1 << 6;
3676 }
3677
3678 EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3679 outgoing_ack()->entropy_hash);
3680 }
3681
3682 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3683 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3684 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3685 ProcessDataPacket(1, 1, kEntropyFlag);
3686 ProcessDataPacket(5, 1, !kEntropyFlag);
3687 ProcessDataPacket(22, 1, kEntropyFlag);
3688 EXPECT_EQ(66u, outgoing_ack()->entropy_hash);
3689 peer_creator_.set_sequence_number(22);
3690 QuicPacketEntropyHash kRandomEntropyHash = 85u;
3691 // Current packet is the least unacked packet.
3692 QuicPacketEntropyHash ack_entropy_hash;
3693 QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3694 frame.entropy_hash = kRandomEntropyHash;
3695 ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3696 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3697 outgoing_ack()->entropy_hash);
3698 ProcessDataPacket(25, 1, kEntropyFlag);
3699 EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3700 outgoing_ack()->entropy_hash);
3701 }
3702
3703 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3704 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(AtLeast(1));
3705 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3706 QuicPacketEntropyHash entropy[51];
3707 entropy[0] = 0;
3708 for (int i = 1; i < 51; ++i) {
3709 bool should_send = i % 10 != 1;
3710 bool entropy_flag = (i & (i - 1)) != 0;
3711 if (!should_send) {
3712 entropy[i] = entropy[i - 1];
3713 continue;
3714 }
3715 if (entropy_flag) {
3716 entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3717 } else {
3718 entropy[i] = entropy[i - 1];
3719 }
3720 ProcessDataPacket(i, 1, entropy_flag);
3721 }
3722 for (int i = 1; i < 50; ++i) {
3723 EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3724 &connection_, i));
3725 }
3726 }
3727
3728 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3729 connection_.SetSupportedVersions(QuicSupportedVersions());
3730 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3731
3732 QuicPacketHeader header;
3733 header.public_header.connection_id = connection_id_;
3734 header.public_header.reset_flag = false;
3735 header.public_header.version_flag = true;
3736 header.entropy_flag = false;
3737 header.fec_flag = false;
3738 header.packet_sequence_number = 12;
3739 header.fec_group = 0;
3740
3741 QuicFrames frames;
3742 QuicFrame frame(&frame1_);
3743 frames.push_back(frame);
3744 scoped_ptr<QuicPacket> packet(
3745 BuildUnsizedDataPacket(&framer_, header, frames));
3746 scoped_ptr<QuicEncryptedPacket> encrypted(
3747 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3748
3749 framer_.set_version(version());
3750 connection_.set_is_server(true);
3751 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3752 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3753
3754 size_t num_versions = arraysize(kSupportedQuicVersions);
3755 ASSERT_EQ(num_versions,
3756 writer_->version_negotiation_packet()->versions.size());
3757
3758 // We expect all versions in kSupportedQuicVersions to be
3759 // included in the packet.
3760 for (size_t i = 0; i < num_versions; ++i) {
3761 EXPECT_EQ(kSupportedQuicVersions[i],
3762 writer_->version_negotiation_packet()->versions[i]);
3763 }
3764 }
3765
3766 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3767 connection_.SetSupportedVersions(QuicSupportedVersions());
3768 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3769
3770 QuicPacketHeader header;
3771 header.public_header.connection_id = connection_id_;
3772 header.public_header.reset_flag = false;
3773 header.public_header.version_flag = true;
3774 header.entropy_flag = false;
3775 header.fec_flag = false;
3776 header.packet_sequence_number = 12;
3777 header.fec_group = 0;
3778
3779 QuicFrames frames;
3780 QuicFrame frame(&frame1_);
3781 frames.push_back(frame);
3782 scoped_ptr<QuicPacket> packet(
3783 BuildUnsizedDataPacket(&framer_, header, frames));
3784 scoped_ptr<QuicEncryptedPacket> encrypted(
3785 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3786
3787 framer_.set_version(version());
3788 connection_.set_is_server(true);
3789 BlockOnNextWrite();
3790 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3791 EXPECT_EQ(0u, writer_->last_packet_size());
3792 EXPECT_TRUE(connection_.HasQueuedData());
3793
3794 writer_->SetWritable();
3795 connection_.OnCanWrite();
3796 EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr);
3797
3798 size_t num_versions = arraysize(kSupportedQuicVersions);
3799 ASSERT_EQ(num_versions,
3800 writer_->version_negotiation_packet()->versions.size());
3801
3802 // We expect all versions in kSupportedQuicVersions to be
3803 // included in the packet.
3804 for (size_t i = 0; i < num_versions; ++i) {
3805 EXPECT_EQ(kSupportedQuicVersions[i],
3806 writer_->version_negotiation_packet()->versions[i]);
3807 }
3808 }
3809
3810 TEST_P(QuicConnectionTest,
3811 ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3812 connection_.SetSupportedVersions(QuicSupportedVersions());
3813 framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3814
3815 QuicPacketHeader header;
3816 header.public_header.connection_id = connection_id_;
3817 header.public_header.reset_flag = false;
3818 header.public_header.version_flag = true;
3819 header.entropy_flag = false;
3820 header.fec_flag = false;
3821 header.packet_sequence_number = 12;
3822 header.fec_group = 0;
3823
3824 QuicFrames frames;
3825 QuicFrame frame(&frame1_);
3826 frames.push_back(frame);
3827 scoped_ptr<QuicPacket> packet(
3828 BuildUnsizedDataPacket(&framer_, header, frames));
3829 scoped_ptr<QuicEncryptedPacket> encrypted(
3830 framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3831
3832 framer_.set_version(version());
3833 connection_.set_is_server(true);
3834 BlockOnNextWrite();
3835 writer_->set_is_write_blocked_data_buffered(true);
3836 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3837 EXPECT_EQ(0u, writer_->last_packet_size());
3838 EXPECT_FALSE(connection_.HasQueuedData());
3839 }
3840
3841 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3842 // Start out with some unsupported version.
3843 QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3844 QUIC_VERSION_UNSUPPORTED);
3845
3846 QuicPacketHeader header;
3847 header.public_header.connection_id = connection_id_;
3848 header.public_header.reset_flag = false;
3849 header.public_header.version_flag = true;
3850 header.entropy_flag = false;
3851 header.fec_flag = false;
3852 header.packet_sequence_number = 12;
3853 header.fec_group = 0;
3854
3855 QuicVersionVector supported_versions;
3856 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3857 supported_versions.push_back(kSupportedQuicVersions[i]);
3858 }
3859
3860 // Send a version negotiation packet.
3861 scoped_ptr<QuicEncryptedPacket> encrypted(
3862 framer_.BuildVersionNegotiationPacket(
3863 header.public_header, supported_versions));
3864 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3865
3866 // Now force another packet. The connection should transition into
3867 // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3868 header.public_header.version_flag = false;
3869 QuicFrames frames;
3870 QuicFrame frame(&frame1_);
3871 frames.push_back(frame);
3872 scoped_ptr<QuicPacket> packet(
3873 BuildUnsizedDataPacket(&framer_, header, frames));
3874 encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3875 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3876 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3877 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3878
3879 ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3880 }
3881
3882 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3883 QuicPacketHeader header;
3884 header.public_header.connection_id = connection_id_;
3885 header.public_header.reset_flag = false;
3886 header.public_header.version_flag = true;
3887 header.entropy_flag = false;
3888 header.fec_flag = false;
3889 header.packet_sequence_number = 12;
3890 header.fec_group = 0;
3891
3892 QuicVersionVector supported_versions;
3893 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3894 supported_versions.push_back(kSupportedQuicVersions[i]);
3895 }
3896
3897 // Send a version negotiation packet with the version the client started with.
3898 // It should be rejected.
3899 EXPECT_CALL(visitor_,
3900 OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3901 false));
3902 scoped_ptr<QuicEncryptedPacket> encrypted(
3903 framer_.BuildVersionNegotiationPacket(
3904 header.public_header, supported_versions));
3905 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3906 }
3907
3908 TEST_P(QuicConnectionTest, CheckSendStats) {
3909 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3910 connection_.SendStreamDataWithString(3, "first", 0, !kFin, nullptr);
3911 size_t first_packet_size = writer_->last_packet_size();
3912
3913 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3914 connection_.SendStreamDataWithString(5, "second", 0, !kFin, nullptr);
3915 size_t second_packet_size = writer_->last_packet_size();
3916
3917 // 2 retransmissions due to rto, 1 due to explicit nack.
3918 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
3920
3921 // Retransmit due to RTO.
3922 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3923 connection_.GetRetransmissionAlarm()->Fire();
3924
3925 // Retransmit due to explicit nacks.
3926 QuicAckFrame nack_three = InitAckFrame(4);
3927 NackPacket(3, &nack_three);
3928 NackPacket(1, &nack_three);
3929 SequenceNumberSet lost_packets;
3930 lost_packets.insert(1);
3931 lost_packets.insert(3);
3932 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3933 .WillOnce(Return(lost_packets));
3934 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
3935 EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3937 if (!FLAGS_quic_use_new_rto) {
3938 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
3939 }
3940 ProcessAckPacket(&nack_three);
3941
3942 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3943 Return(QuicBandwidth::Zero()));
3944
3945 const QuicConnectionStats& stats = connection_.GetStats();
3946 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3947 stats.bytes_sent);
3948 EXPECT_EQ(5u, stats.packets_sent);
3949 EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3950 stats.bytes_retransmitted);
3951 EXPECT_EQ(3u, stats.packets_retransmitted);
3952 EXPECT_EQ(1u, stats.rto_count);
3953 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
3954 }
3955
3956 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3957 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3958
3959 size_t received_bytes = 0;
3960 received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3961 received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3962 // Should be counted against dropped packets.
3963 received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3964 received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, nullptr);
3965
3966 EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3967 Return(QuicBandwidth::Zero()));
3968
3969 const QuicConnectionStats& stats = connection_.GetStats();
3970 EXPECT_EQ(received_bytes, stats.bytes_received);
3971 EXPECT_EQ(4u, stats.packets_received);
3972
3973 EXPECT_EQ(1u, stats.packets_revived);
3974 EXPECT_EQ(1u, stats.packets_dropped);
3975 }
3976
3977 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3978 // Create and return a group for 1.
3979 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != nullptr);
3980
3981 // Create and return a group for 2.
3982 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3983
3984 // Create and return a group for 4. This should remove 1 but not 2.
3985 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3986 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == nullptr);
3987 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != nullptr);
3988
3989 // Create and return a group for 3. This will kill off 2.
3990 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != nullptr);
3991 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == nullptr);
3992
3993 // Verify that adding 5 kills off 3, despite 4 being created before 3.
3994 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != nullptr);
3995 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != nullptr);
3996 ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == nullptr);
3997 }
3998
3999 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
4000 // Construct a packet with stream frame and connection close frame.
4001 header_.public_header.connection_id = connection_id_;
4002 header_.packet_sequence_number = 1;
4003 header_.public_header.reset_flag = false;
4004 header_.public_header.version_flag = false;
4005 header_.entropy_flag = false;
4006 header_.fec_flag = false;
4007 header_.fec_group = 0;
4008
4009 QuicConnectionCloseFrame qccf;
4010 qccf.error_code = QUIC_PEER_GOING_AWAY;
4011 QuicFrame close_frame(&qccf);
4012 QuicFrame stream_frame(&frame1_);
4013
4014 QuicFrames frames;
4015 frames.push_back(stream_frame);
4016 frames.push_back(close_frame);
4017 scoped_ptr<QuicPacket> packet(
4018 BuildUnsizedDataPacket(&framer_, header_, frames));
4019 EXPECT_TRUE(nullptr != packet.get());
4020 scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
4021 ENCRYPTION_NONE, 1, *packet));
4022
4023 EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
4024 EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
4025 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4026
4027 connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
4028 }
4029
4030 TEST_P(QuicConnectionTest, SelectMutualVersion) {
4031 connection_.SetSupportedVersions(QuicSupportedVersions());
4032 // Set the connection to speak the lowest quic version.
4033 connection_.set_version(QuicVersionMin());
4034 EXPECT_EQ(QuicVersionMin(), connection_.version());
4035
4036 // Pass in available versions which includes a higher mutually supported
4037 // version. The higher mutually supported version should be selected.
4038 QuicVersionVector supported_versions;
4039 for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
4040 supported_versions.push_back(kSupportedQuicVersions[i]);
4041 }
4042 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
4043 EXPECT_EQ(QuicVersionMax(), connection_.version());
4044
4045 // Expect that the lowest version is selected.
4046 // Ensure the lowest supported version is less than the max, unless they're
4047 // the same.
4048 EXPECT_LE(QuicVersionMin(), QuicVersionMax());
4049 QuicVersionVector lowest_version_vector;
4050 lowest_version_vector.push_back(QuicVersionMin());
4051 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
4052 EXPECT_EQ(QuicVersionMin(), connection_.version());
4053
4054 // Shouldn't be able to find a mutually supported version.
4055 QuicVersionVector unsupported_version;
4056 unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
4057 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
4058 }
4059
4060 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
4061 EXPECT_FALSE(writer_->IsWriteBlocked());
4062
4063 // Send a packet.
4064 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4065 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4066 EXPECT_EQ(1u, writer_->packets_write_attempts());
4067
4068 TriggerConnectionClose();
4069 EXPECT_EQ(2u, writer_->packets_write_attempts());
4070 }
4071
4072 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
4073 BlockOnNextWrite();
4074 TriggerConnectionClose();
4075 EXPECT_EQ(1u, writer_->packets_write_attempts());
4076 EXPECT_TRUE(writer_->IsWriteBlocked());
4077 }
4078
4079 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
4080 BlockOnNextWrite();
4081 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4082 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4083 EXPECT_EQ(1u, writer_->packets_write_attempts());
4084 EXPECT_TRUE(writer_->IsWriteBlocked());
4085 TriggerConnectionClose();
4086 EXPECT_EQ(1u, writer_->packets_write_attempts());
4087 }
4088
4089 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
4090 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4091
4092 // Create a delegate which we expect to be called.
4093 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4094 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4095
4096 // Send some data, which will register the delegate to be notified.
4097 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4098
4099 // Process an ACK from the server which should trigger the callback.
4100 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4101 QuicAckFrame frame = InitAckFrame(1);
4102 ProcessAckPacket(&frame);
4103 }
4104
4105 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
4106 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4107
4108 // Create a delegate which we don't expect to be called.
4109 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4110 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(0);
4111
4112 // Send some data, which will register the delegate to be notified. This will
4113 // not be ACKed and so the delegate should never be called.
4114 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4115
4116 // Send some other data which we will ACK.
4117 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, nullptr);
4118 connection_.SendStreamDataWithString(1, "bar", 0, !kFin, nullptr);
4119
4120 // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
4121 // which we registered to be notified about.
4122 QuicAckFrame frame = InitAckFrame(3);
4123 NackPacket(1, &frame);
4124 SequenceNumberSet lost_packets;
4125 lost_packets.insert(1);
4126 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4127 .WillOnce(Return(lost_packets));
4128 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4129 ProcessAckPacket(&frame);
4130 }
4131
4132 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
4133 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4134
4135 // Create a delegate which we expect to be called.
4136 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4137 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4138
4139 // Send four packets, and register to be notified on ACK of packet 2.
4140 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4141 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4142 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4143 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4144
4145 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4146 QuicAckFrame frame = InitAckFrame(4);
4147 NackPacket(2, &frame);
4148 SequenceNumberSet lost_packets;
4149 lost_packets.insert(2);
4150 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4151 .WillOnce(Return(lost_packets));
4152 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4153 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4154 ProcessAckPacket(&frame);
4155
4156 // Now we get an ACK for packet 5 (retransmitted packet 2), which should
4157 // trigger the callback.
4158 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4159 .WillRepeatedly(Return(SequenceNumberSet()));
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4161 QuicAckFrame second_ack_frame = InitAckFrame(5);
4162 ProcessAckPacket(&second_ack_frame);
4163 }
4164
4165 // AckNotifierCallback is triggered by the ack of a packet that timed
4166 // out and was retransmitted, even though the retransmission has a
4167 // different sequence number.
4168 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
4169 InSequence s;
4170
4171 // Create a delegate which we expect to be called.
4172 scoped_refptr<MockAckNotifierDelegate> delegate(
4173 new StrictMock<MockAckNotifierDelegate>);
4174
4175 QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
4176 DefaultRetransmissionTime());
4177 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
4178 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4179
4180 EXPECT_EQ(1u, writer_->header().packet_sequence_number);
4181 EXPECT_EQ(default_retransmission_time,
4182 connection_.GetRetransmissionAlarm()->deadline());
4183 // Simulate the retransmission alarm firing.
4184 clock_.AdvanceTime(DefaultRetransmissionTime());
4185 if (!FLAGS_quic_use_new_rto) {
4186 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
4187 }
4188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, 2u, _, _));
4189 connection_.GetRetransmissionAlarm()->Fire();
4190 EXPECT_EQ(2u, writer_->header().packet_sequence_number);
4191 // We do not raise the high water mark yet.
4192 EXPECT_EQ(1u, stop_waiting()->least_unacked);
4193
4194 // Ack the original packet, which will revert the RTO.
4195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4196 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4197 if (!FLAGS_quic_use_new_rto) {
4198 EXPECT_CALL(*send_algorithm_, RevertRetransmissionTimeout());
4199 }
4200 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4201 QuicAckFrame ack_frame = InitAckFrame(1);
4202 ProcessAckPacket(&ack_frame);
4203
4204 // Delegate is not notified again when the retransmit is acked.
4205 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4206 QuicAckFrame second_ack_frame = InitAckFrame(2);
4207 ProcessAckPacket(&second_ack_frame);
4208 }
4209
4210 // AckNotifierCallback is triggered by the ack of a packet that was
4211 // previously nacked, even though the retransmission has a different
4212 // sequence number.
4213 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
4214 InSequence s;
4215
4216 // Create a delegate which we expect to be called.
4217 scoped_refptr<MockAckNotifierDelegate> delegate(
4218 new StrictMock<MockAckNotifierDelegate>);
4219
4220 // Send four packets, and register to be notified on ACK of packet 2.
4221 connection_.SendStreamDataWithString(3, "foo", 0, !kFin, nullptr);
4222 connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
4223 connection_.SendStreamDataWithString(3, "baz", 0, !kFin, nullptr);
4224 connection_.SendStreamDataWithString(3, "qux", 0, !kFin, nullptr);
4225
4226 // Now we receive ACK for packets 1, 3, and 4 and lose 2.
4227 QuicAckFrame frame = InitAckFrame(4);
4228 NackPacket(2, &frame);
4229 SequenceNumberSet lost_packets;
4230 lost_packets.insert(2);
4231 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4232 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4233 .WillOnce(Return(lost_packets));
4234 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4235 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4236 ProcessAckPacket(&frame);
4237
4238 // Now we get an ACK for packet 2, which was previously nacked.
4239 SequenceNumberSet no_lost_packets;
4240 EXPECT_CALL(*delegate.get(), OnAckNotification(1, _, _));
4241 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4242 .WillOnce(Return(no_lost_packets));
4243 QuicAckFrame second_ack_frame = InitAckFrame(4);
4244 ProcessAckPacket(&second_ack_frame);
4245
4246 // Verify that the delegate is not notified again when the
4247 // retransmit is acked.
4248 EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
4249 .WillOnce(Return(no_lost_packets));
4250 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4251 QuicAckFrame third_ack_frame = InitAckFrame(5);
4252 ProcessAckPacket(&third_ack_frame);
4253 }
4254
4255 TEST_P(QuicConnectionTest, AckNotifierFECTriggerCallback) {
4256 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4257
4258 // Create a delegate which we expect to be called.
4259 scoped_refptr<MockAckNotifierDelegate> delegate(
4260 new MockAckNotifierDelegate);
4261 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4262
4263 // Send some data, which will register the delegate to be notified.
4264 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4265 connection_.SendStreamDataWithString(2, "bar", 0, !kFin, nullptr);
4266
4267 // Process an ACK from the server with a revived packet, which should trigger
4268 // the callback.
4269 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4270 QuicAckFrame frame = InitAckFrame(2);
4271 NackPacket(1, &frame);
4272 frame.revived_packets.insert(1);
4273 ProcessAckPacket(&frame);
4274 // If the ack is processed again, the notifier should not be called again.
4275 ProcessAckPacket(&frame);
4276 }
4277
4278 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
4279 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4280 EXPECT_CALL(visitor_, OnCanWrite());
4281
4282 // Create a delegate which we expect to be called.
4283 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4284 EXPECT_CALL(*delegate.get(), OnAckNotification(_, _, _)).Times(1);
4285
4286 // Expect ACKs for 1 packet.
4287 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _));
4288
4289 // Send one packet, and register to be notified on ACK.
4290 connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
4291
4292 // Ack packet gets dropped, but we receive an FEC packet that covers it.
4293 // Should recover the Ack packet and trigger the notification callback.
4294 QuicFrames frames;
4295
4296 QuicAckFrame ack_frame = InitAckFrame(1);
4297 frames.push_back(QuicFrame(&ack_frame));
4298
4299 // Dummy stream frame to satisfy expectations set elsewhere.
4300 frames.push_back(QuicFrame(&frame1_));
4301
4302 QuicPacketHeader ack_header;
4303 ack_header.public_header.connection_id = connection_id_;
4304 ack_header.public_header.reset_flag = false;
4305 ack_header.public_header.version_flag = false;
4306 ack_header.entropy_flag = !kEntropyFlag;
4307 ack_header.fec_flag = true;
4308 ack_header.packet_sequence_number = 1;
4309 ack_header.is_in_fec_group = IN_FEC_GROUP;
4310 ack_header.fec_group = 1;
4311
4312 QuicPacket* packet = BuildUnsizedDataPacket(&framer_, ack_header, frames);
4313
4314 // Take the packet which contains the ACK frame, and construct and deliver an
4315 // FEC packet which allows the ACK packet to be recovered.
4316 ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
4317 }
4318
4319 TEST_P(QuicConnectionTest, NetworkChangeVisitorCwndCallbackChangesFecState) {
4320 size_t max_packets_per_fec_group = creator_->max_packets_per_fec_group();
4321
4322 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4323 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4324 EXPECT_TRUE(visitor);
4325
4326 // Increase FEC group size by increasing congestion window to a large number.
4327 EXPECT_CALL(*send_algorithm_, GetCongestionWindow()).WillRepeatedly(
4328 Return(1000 * kDefaultTCPMSS));
4329 visitor->OnCongestionWindowChange();
4330 EXPECT_LT(max_packets_per_fec_group, creator_->max_packets_per_fec_group());
4331 }
4332
4333 TEST_P(QuicConnectionTest, NetworkChangeVisitorConfigCallbackChangesFecState) {
4334 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4335 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4336 EXPECT_TRUE(visitor);
4337 EXPECT_EQ(QuicTime::Delta::Zero(),
4338 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4339
4340 // Verify that sending a config with a new initial rtt changes fec timeout.
4341 // Create and process a config with a non-zero initial RTT.
4342 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _));
4343 QuicConfig config;
4344 config.SetInitialRoundTripTimeUsToSend(300000);
4345 connection_.SetFromConfig(config);
4346 EXPECT_LT(QuicTime::Delta::Zero(),
4347 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4348 }
4349
4350 TEST_P(QuicConnectionTest, NetworkChangeVisitorRttCallbackChangesFecState) {
4351 // Verify that sending a config with a new initial rtt changes fec timeout.
4352 QuicSentPacketManager::NetworkChangeVisitor* visitor =
4353 QuicSentPacketManagerPeer::GetNetworkChangeVisitor(manager_);
4354 EXPECT_TRUE(visitor);
4355 EXPECT_EQ(QuicTime::Delta::Zero(),
4356 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4357
4358 // Increase FEC timeout by increasing RTT.
4359 RttStats* rtt_stats = QuicSentPacketManagerPeer::GetRttStats(manager_);
4360 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
4361 QuicTime::Delta::Zero(), QuicTime::Zero());
4362 visitor->OnRttChange();
4363 EXPECT_LT(QuicTime::Delta::Zero(),
4364 QuicPacketGeneratorPeer::GetFecTimeout(generator_));
4365 }
4366
4367 class MockQuicConnectionDebugVisitor
4368 : public QuicConnectionDebugVisitor {
4369 public:
4370 MOCK_METHOD1(OnFrameAddedToPacket,
4371 void(const QuicFrame&));
4372
4373 MOCK_METHOD6(OnPacketSent,
4374 void(const SerializedPacket&,
4375 QuicPacketSequenceNumber,
4376 EncryptionLevel,
4377 TransmissionType,
4378 const QuicEncryptedPacket&,
4379 QuicTime));
4380
4381 MOCK_METHOD3(OnPacketReceived,
4382 void(const IPEndPoint&,
4383 const IPEndPoint&,
4384 const QuicEncryptedPacket&));
4385
4386 MOCK_METHOD1(OnProtocolVersionMismatch,
4387 void(QuicVersion));
4388
4389 MOCK_METHOD1(OnPacketHeader,
4390 void(const QuicPacketHeader& header));
4391
4392 MOCK_METHOD1(OnStreamFrame,
4393 void(const QuicStreamFrame&));
4394
4395 MOCK_METHOD1(OnAckFrame,
4396 void(const QuicAckFrame& frame));
4397
4398 MOCK_METHOD1(OnStopWaitingFrame,
4399 void(const QuicStopWaitingFrame&));
4400
4401 MOCK_METHOD1(OnRstStreamFrame,
4402 void(const QuicRstStreamFrame&));
4403
4404 MOCK_METHOD1(OnConnectionCloseFrame,
4405 void(const QuicConnectionCloseFrame&));
4406
4407 MOCK_METHOD1(OnPublicResetPacket,
4408 void(const QuicPublicResetPacket&));
4409
4410 MOCK_METHOD1(OnVersionNegotiationPacket,
4411 void(const QuicVersionNegotiationPacket&));
4412
4413 MOCK_METHOD2(OnRevivedPacket,
4414 void(const QuicPacketHeader&, StringPiece payload));
4415 };
4416
4417 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
4418 QuicPacketHeader header;
4419
4420 MockQuicConnectionDebugVisitor* debug_visitor =
4421 new MockQuicConnectionDebugVisitor();
4422 connection_.set_debug_visitor(debug_visitor);
4423 EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
4424 connection_.OnPacketHeader(header);
4425 }
4426
4427 TEST_P(QuicConnectionTest, Pacing) {
4428 TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
4429 factory_, /* is_server= */ true, version());
4430 TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
4431 factory_, /* is_server= */ false, version());
4432 EXPECT_FALSE(client.sent_packet_manager().using_pacing());
4433 EXPECT_FALSE(server.sent_packet_manager().using_pacing());
4434 }
4435
4436 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
4437 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4438
4439 // Send a WINDOW_UPDATE frame.
4440 QuicWindowUpdateFrame window_update;
4441 window_update.stream_id = 3;
4442 window_update.byte_offset = 1234;
4443 EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
4444 ProcessFramePacket(QuicFrame(&window_update));
4445
4446 // Ensure that this has caused the ACK alarm to be set.
4447 QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
4448 EXPECT_TRUE(ack_alarm->IsSet());
4449
4450 // Cancel alarm, and try again with BLOCKED frame.
4451 ack_alarm->Cancel();
4452 QuicBlockedFrame blocked;
4453 blocked.stream_id = 3;
4454 EXPECT_CALL(visitor_, OnBlockedFrames(_));
4455 ProcessFramePacket(QuicFrame(&blocked));
4456 EXPECT_TRUE(ack_alarm->IsSet());
4457 }
4458
4459 TEST_P(QuicConnectionTest, NoDataNoFin) {
4460 // Make sure that a call to SendStreamWithData, with no data and no FIN, does
4461 // not result in a QuicAckNotifier being used-after-free (fail under ASAN).
4462 // Regression test for b/18594622
4463 scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
4464 EXPECT_DFATAL(
4465 connection_.SendStreamDataWithString(3, "", 0, !kFin, delegate.get()),
4466 "Attempt to send empty stream frame");
4467 }
4468
4469 } // namespace
4470 } // namespace test
4471 } // namespace net
OLDNEW
« no previous file with comments | « net/quic/quic_connection_stats.cc ('k') | net/quic/quic_crypto_client_stream.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698