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