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