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