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