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