summaryrefslogtreecommitdiffstats
path: root/net/quic/quic_session_test.cc
blob: 6d71a77d93997822cc2dcc4b568c0487bc901f26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/quic/quic_session.h"

#include <set>

#include "base/containers/hash_tables.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "net/quic/crypto/crypto_protocol.h"
#include "net/quic/quic_crypto_stream.h"
#include "net/quic/quic_flags.h"
#include "net/quic/quic_protocol.h"
#include "net/quic/quic_utils.h"
#include "net/quic/reliable_quic_stream.h"
#include "net/quic/test_tools/quic_config_peer.h"
#include "net/quic/test_tools/quic_connection_peer.h"
#include "net/quic/test_tools/quic_flow_controller_peer.h"
#include "net/quic/test_tools/quic_session_peer.h"
#include "net/quic/test_tools/quic_spdy_session_peer.h"
#include "net/quic/test_tools/quic_spdy_stream_peer.h"
#include "net/quic/test_tools/quic_test_utils.h"
#include "net/quic/test_tools/reliable_quic_stream_peer.h"
#include "net/spdy/spdy_framer.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::hash_map;
using std::set;
using std::string;
using std::vector;
using testing::CreateFunctor;
using testing::InSequence;
using testing::Invoke;
using testing::Return;
using testing::StrictMock;
using testing::_;

namespace net {
namespace test {
namespace {

const SpdyPriority kHighestPriority = kV3HighestPriority;

class TestCryptoStream : public QuicCryptoStream {
 public:
  explicit TestCryptoStream(QuicSession* session) : QuicCryptoStream(session) {}

  void OnHandshakeMessage(const CryptoHandshakeMessage& /*message*/) override {
    encryption_established_ = true;
    handshake_confirmed_ = true;
    CryptoHandshakeMessage msg;
    string error_details;
    session()->config()->SetInitialStreamFlowControlWindowToSend(
        kInitialStreamFlowControlWindowForTest);
    session()->config()->SetInitialSessionFlowControlWindowToSend(
        kInitialSessionFlowControlWindowForTest);
    session()->config()->ToHandshakeMessage(&msg);
    const QuicErrorCode error =
        session()->config()->ProcessPeerHello(msg, CLIENT, &error_details);
    EXPECT_EQ(QUIC_NO_ERROR, error);
    session()->OnConfigNegotiated();
    session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED);
  }

  MOCK_METHOD0(OnCanWrite, void());
};

class TestHeadersStream : public QuicHeadersStream {
 public:
  explicit TestHeadersStream(QuicSpdySession* session)
      : QuicHeadersStream(session) {}

  MOCK_METHOD0(OnCanWrite, void());
};

class TestStream : public QuicSpdyStream {
 public:
  TestStream(QuicStreamId id, QuicSpdySession* session)
      : QuicSpdyStream(id, session) {}

  using ReliableQuicStream::CloseWriteSide;

  void OnDataAvailable() override {}

  void SendBody(const string& data, bool fin) {
    WriteOrBufferData(data, fin, nullptr);
  }

  MOCK_METHOD0(OnCanWrite, void());
};

// Poor man's functor for use as callback in a mock.
class StreamBlocker {
 public:
  StreamBlocker(QuicSession* session, QuicStreamId stream_id)
      : session_(session), stream_id_(stream_id) {}

  void MarkConnectionLevelWriteBlocked() {
    session_->MarkConnectionLevelWriteBlocked(stream_id_, kDefaultPriority);
  }

  void MarkHighPriorityWriteBlocked() {
    session_->MarkConnectionLevelWriteBlocked(stream_id_, kHighestPriority);
  }

 private:
  QuicSession* const session_;
  const QuicStreamId stream_id_;
};

class TestSession : public QuicSpdySession {
 public:
  explicit TestSession(QuicConnection* connection)
      : QuicSpdySession(connection, DefaultQuicConfig()),
        crypto_stream_(this),
        writev_consumes_all_data_(false) {
    Initialize();
  }

  TestCryptoStream* GetCryptoStream() override { return &crypto_stream_; }

  TestStream* CreateOutgoingDynamicStream(SpdyPriority priority) override {
    TestStream* stream = new TestStream(GetNextOutgoingStreamId(), this);
    stream->SetPriority(priority);
    ActivateStream(stream);
    return stream;
  }

  TestStream* CreateIncomingDynamicStream(QuicStreamId id) override {
    // Enforce the limit on the number of open streams.
    if (GetNumOpenIncomingStreams() + 1 > get_max_open_streams()) {
      connection()->SendConnectionCloseWithDetails(QUIC_TOO_MANY_OPEN_STREAMS,
                                                   "Too many streams!");
      return nullptr;
    } else {
      return new TestStream(id, this);
    }
  }

  bool IsClosedStream(QuicStreamId id) {
    return QuicSession::IsClosedStream(id);
  }

  ReliableQuicStream* GetOrCreateDynamicStream(QuicStreamId stream_id) {
    return QuicSpdySession::GetOrCreateDynamicStream(stream_id);
  }

  QuicConsumedData WritevData(
      QuicStreamId id,
      QuicIOVector data,
      QuicStreamOffset offset,
      bool fin,
      FecProtection fec_protection,
      QuicAckListenerInterface* ack_notifier_delegate) override {
    QuicConsumedData consumed(data.total_length, fin);
    if (!writev_consumes_all_data_) {
      consumed = QuicSession::WritevData(id, data, offset, fin, fec_protection,
                                         ack_notifier_delegate);
    }
    QuicSessionPeer::GetWriteBlockedStreams(this)
        ->UpdateBytesForStream(id, consumed.bytes_consumed);
    return consumed;
  }

  void set_writev_consumes_all_data(bool val) {
    writev_consumes_all_data_ = val;
  }

  QuicConsumedData SendStreamData(QuicStreamId id) {
    struct iovec iov;
    return WritevData(id, MakeIOVector("not empty", &iov), 0, true,
                      MAY_FEC_PROTECT, nullptr);
  }

  QuicConsumedData SendLargeFakeData(QuicStreamId id, int bytes) {
    DCHECK(writev_consumes_all_data_);
    struct iovec iov;
    iov.iov_base = nullptr;  // should not be read.
    iov.iov_len = static_cast<size_t>(bytes);
    return WritevData(id, QuicIOVector(&iov, 1, bytes), 0, true,
                      MAY_FEC_PROTECT, nullptr);
  }

  using QuicSession::PostProcessAfterData;

 private:
  StrictMock<TestCryptoStream> crypto_stream_;

  bool writev_consumes_all_data_;
};

class QuicSessionTestBase : public ::testing::TestWithParam<QuicVersion> {
 protected:
  explicit QuicSessionTestBase(Perspective perspective)
      : connection_(
            new StrictMock<MockConnection>(&helper_,
                                           perspective,
                                           SupportedVersions(GetParam()))),
        session_(connection_) {
    FLAGS_quic_always_log_bugs_for_tests = true;
    session_.config()->SetInitialStreamFlowControlWindowToSend(
        kInitialStreamFlowControlWindowForTest);
    session_.config()->SetInitialSessionFlowControlWindowToSend(
        kInitialSessionFlowControlWindowForTest);
    headers_[":host"] = "www.google.com";
    headers_[":path"] = "/index.hml";
    headers_[":scheme"] = "http";
    headers_["cookie"] =
        "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
        "__utmc=160408618; "
        "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX"
        "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX"
        "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT"
        "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0"
        "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh"
        "1zFMi5vzcns38-8_Sns; "
        "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-"
        "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339"
        "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c"
        "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%"
        "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4"
        "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1"
        "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP"
        "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6"
        "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b"
        "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6"
        "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG"
        "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk"
        "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn"
        "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr"
        "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo ";
    connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
    // TODO(ianswett): Fix QuicSessionTests so they don't attempt to write
    // non-crypto stream data at ENCRYPTION_NONE.
    FLAGS_quic_never_write_unencrypted_data = false;
  }

  void CheckClosedStreams() {
    for (QuicStreamId i = kCryptoStreamId; i < 100; i++) {
      if (!ContainsKey(closed_streams_, i)) {
        EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
      } else {
        EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
      }
    }
  }

  void CloseStream(QuicStreamId id) {
    EXPECT_CALL(*connection_, SendRstStream(id, _, _));
    session_.CloseStream(id);
    closed_streams_.insert(id);
  }

  QuicVersion version() const { return connection_->version(); }

  MockConnectionHelper helper_;
  StrictMock<MockConnection>* connection_;
  TestSession session_;
  set<QuicStreamId> closed_streams_;
  SpdyHeaderBlock headers_;
};

class QuicSessionTestServer : public QuicSessionTestBase {
 protected:
  QuicSessionTestServer() : QuicSessionTestBase(Perspective::IS_SERVER) {}
};

INSTANTIATE_TEST_CASE_P(Tests,
                        QuicSessionTestServer,
                        ::testing::ValuesIn(QuicSupportedVersions()));

TEST_P(QuicSessionTestServer, PeerAddress) {
  EXPECT_EQ(IPEndPoint(Loopback4(), kTestPort), session_.peer_address());
}

TEST_P(QuicSessionTestServer, IsCryptoHandshakeConfirmed) {
  EXPECT_FALSE(session_.IsCryptoHandshakeConfirmed());
  CryptoHandshakeMessage message;
  session_.GetCryptoStream()->OnHandshakeMessage(message);
  EXPECT_TRUE(session_.IsCryptoHandshakeConfirmed());
}

TEST_P(QuicSessionTestServer, IsClosedStreamDefault) {
  // Ensure that no streams are initially closed.
  for (QuicStreamId i = kCryptoStreamId; i < 100; i++) {
    EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i;
  }
}

TEST_P(QuicSessionTestServer, AvailableStreams) {
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(9) != nullptr);
  // Both 5 and 7 should be available.
  EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(&session_, 5));
  EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(&session_, 7));
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(7) != nullptr);
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(5) != nullptr);
}

TEST_P(QuicSessionTestServer, IsClosedStreamLocallyCreated) {
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_EQ(2u, stream2->id());
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_EQ(4u, stream4->id());

  CheckClosedStreams();
  CloseStream(4);
  CheckClosedStreams();
  CloseStream(2);
  CheckClosedStreams();
}

TEST_P(QuicSessionTestServer, IsClosedStreamPeerCreated) {
  QuicStreamId stream_id1 = kClientDataStreamId1;
  QuicStreamId stream_id2 = kClientDataStreamId2;
  session_.GetOrCreateDynamicStream(stream_id1);
  session_.GetOrCreateDynamicStream(stream_id2);

  CheckClosedStreams();
  CloseStream(stream_id1);
  CheckClosedStreams();
  CloseStream(stream_id2);
  // Create a stream, and make another available.
  ReliableQuicStream* stream3 =
      session_.GetOrCreateDynamicStream(stream_id2 + 4);
  CheckClosedStreams();
  // Close one, but make sure the other is still not closed
  CloseStream(stream3->id());
  CheckClosedStreams();
}

TEST_P(QuicSessionTestServer, MaximumAvailableOpenedStreams) {
  QuicStreamId stream_id = kClientDataStreamId1;
  session_.GetOrCreateDynamicStream(stream_id);
  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(_, _)).Times(0);
  EXPECT_NE(nullptr,
            session_.GetOrCreateDynamicStream(
                stream_id + 2 * (session_.get_max_open_streams() - 1)));
}

TEST_P(QuicSessionTestServer, TooManyAvailableStreams) {
  QuicStreamId stream_id1 = kClientDataStreamId1;
  QuicStreamId stream_id2;
  EXPECT_NE(nullptr, session_.GetOrCreateDynamicStream(stream_id1));
  // A stream ID which is too large to create.
  stream_id2 = stream_id1 + 2 * session_.get_max_available_streams() + 4;
  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(
                                QUIC_TOO_MANY_AVAILABLE_STREAMS, _));
  EXPECT_EQ(nullptr, session_.GetOrCreateDynamicStream(stream_id2));
}

TEST_P(QuicSessionTestServer, ManyAvailableStreams) {
  // When max_open_streams_ is 200, should be able to create 200 streams
  // out-of-order, that is, creating the one with the largest stream ID first.
  QuicSessionPeer::SetMaxOpenStreams(&session_, 200);
  QuicStreamId stream_id = kClientDataStreamId1;
  // Create one stream.
  session_.GetOrCreateDynamicStream(stream_id);
  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(_, _)).Times(0);
  // Create the largest stream ID of a threatened total of 200 streams.
  session_.GetOrCreateDynamicStream(stream_id + 2 * (200 - 1));
}

TEST_P(QuicSessionTestServer, DebugDFatalIfMarkingClosedStreamWriteBlocked) {
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  QuicStreamId closed_stream_id = stream2->id();
  // Close the stream.
  EXPECT_CALL(*connection_, SendRstStream(closed_stream_id, _, _));
  stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
  EXPECT_DEBUG_DFATAL(session_.MarkConnectionLevelWriteBlocked(
                          closed_stream_id, kDefaultPriority),
                      "Marking unknown stream 2 blocked.");
}

TEST_P(QuicSessionTestServer,
       DebugDFatalIfMarkWriteBlockedCalledWithWrongPriority) {
  const SpdyPriority kDifferentPriority = 0;

  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_NE(kDifferentPriority, stream2->Priority());
  EXPECT_DEBUG_DFATAL(session_.MarkConnectionLevelWriteBlocked(
                          stream2->id(), kDifferentPriority),
                      "Priorities do not match.  Got: 0 Expected: 3");
}

TEST_P(QuicSessionTestServer, OnCanWrite) {
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream6 = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  session_.MarkConnectionLevelWriteBlocked(stream2->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream6->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream4->id(), kDefaultPriority);

  InSequence s;
  StreamBlocker stream2_blocker(&session_, stream2->id());

  if (FLAGS_quic_batch_writes) {
    // Reregister, to test the loop limit.
    EXPECT_CALL(*stream2, OnCanWrite())
        .WillOnce(Invoke(&stream2_blocker,
                         &StreamBlocker::MarkConnectionLevelWriteBlocked));
    // 2 will get called a second time as it didn't finish its block
    EXPECT_CALL(*stream2, OnCanWrite());
    EXPECT_CALL(*stream6, OnCanWrite());
    // 4 will not get called, as we exceeded the loop limit.
  } else {
    // Reregister, to test the loop limit.
    EXPECT_CALL(*stream2, OnCanWrite())
        .WillOnce(Invoke(&stream2_blocker,
                         &StreamBlocker::MarkConnectionLevelWriteBlocked));
    EXPECT_CALL(*stream6, OnCanWrite());
    EXPECT_CALL(*stream4, OnCanWrite());
  }
  session_.OnCanWrite();
  EXPECT_TRUE(session_.WillingAndAbleToWrite());
}

TEST_P(QuicSessionTestServer, TestBatchedWrites) {
  ValueRestore<bool> old_flag(&FLAGS_quic_batch_writes, true);
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream6 = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  session_.set_writev_consumes_all_data(true);
  session_.MarkConnectionLevelWriteBlocked(stream2->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream4->id(), kDefaultPriority);

  StreamBlocker stream2_blocker(&session_, stream2->id());
  StreamBlocker stream4_blocker(&session_, stream4->id());
  StreamBlocker stream6_blocker(&session_, stream6->id());
  // With two sessions blocked, we should get two write calls.  They should both
  // go to the first stream as it will only write 6k and mark itself blocked
  // again.
  InSequence s;
  EXPECT_CALL(*stream2, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream2->id(), 6000))),
                      Invoke(&stream2_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  EXPECT_CALL(*stream2, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream2->id(), 6000))),
                      Invoke(&stream2_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  session_.OnCanWrite();

  // We should get one more call for stream2, at which point it has used its
  // write quota and we move over to stream 4.
  EXPECT_CALL(*stream2, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream2->id(), 6000))),
                      Invoke(&stream2_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  EXPECT_CALL(*stream4, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream4->id(), 6000))),
                      Invoke(&stream4_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  session_.OnCanWrite();

  // Now let stream 4 do the 2nd of its 3 writes, but add a block for a high
  // priority stream 6.  4 should be preempted.  6 will write but *not* block so
  // will cede back to 4.
  stream6->SetPriority(kHighestPriority);
  EXPECT_CALL(*stream4, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream4->id(), 6000))),
                      Invoke(&stream4_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked),
                      Invoke(&stream6_blocker,
                             &StreamBlocker::MarkHighPriorityWriteBlocked)));
  EXPECT_CALL(*stream6, OnCanWrite())
      .WillOnce(testing::IgnoreResult(Invoke(CreateFunctor(
          &session_, &TestSession::SendLargeFakeData, stream4->id(), 6000))));
  session_.OnCanWrite();

  // Stream4 alread did 6k worth of writes, so after doing another 12k it should
  // cede and 2 should resume.
  EXPECT_CALL(*stream4, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream4->id(), 12000))),
                      Invoke(&stream4_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  EXPECT_CALL(*stream2, OnCanWrite())
      .WillOnce(DoAll(testing::IgnoreResult(Invoke(CreateFunctor(
                          &session_, &TestSession::SendLargeFakeData,
                          stream2->id(), 6000))),
                      Invoke(&stream2_blocker,
                             &StreamBlocker::MarkConnectionLevelWriteBlocked)));
  session_.OnCanWrite();
}

TEST_P(QuicSessionTestServer, OnCanWriteBundlesStreams) {
  // Encryption needs to be established before data can be sent.
  CryptoHandshakeMessage msg;
  session_.GetCryptoStream()->OnHandshakeMessage(msg);

  // Drive congestion control manually.
  MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
  QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);

  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream6 = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  session_.MarkConnectionLevelWriteBlocked(stream2->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream6->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream4->id(), kDefaultPriority);

  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillRepeatedly(Return(QuicTime::Delta::Zero()));
  EXPECT_CALL(*send_algorithm, GetCongestionWindow())
      .WillRepeatedly(Return(kMaxPacketSize * 10));
  EXPECT_CALL(*stream2, OnCanWrite())
      .WillOnce(testing::IgnoreResult(Invoke(CreateFunctor(
          &session_, &TestSession::SendStreamData, stream2->id()))));
  EXPECT_CALL(*stream4, OnCanWrite())
      .WillOnce(testing::IgnoreResult(Invoke(CreateFunctor(
          &session_, &TestSession::SendStreamData, stream4->id()))));
  EXPECT_CALL(*stream6, OnCanWrite())
      .WillOnce(testing::IgnoreResult(Invoke(CreateFunctor(
          &session_, &TestSession::SendStreamData, stream6->id()))));

  // Expect that we only send one packet, the writes from different streams
  // should be bundled together.
  MockPacketWriter* writer = static_cast<MockPacketWriter*>(
      QuicConnectionPeer::GetWriter(session_.connection()));
  EXPECT_CALL(*writer, WritePacket(_, _, _, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
  EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _));
  session_.OnCanWrite();
  EXPECT_FALSE(session_.WillingAndAbleToWrite());
}

TEST_P(QuicSessionTestServer, OnCanWriteCongestionControlBlocks) {
  InSequence s;

  // Drive congestion control manually.
  MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
  QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);

  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream6 = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  session_.MarkConnectionLevelWriteBlocked(stream2->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream6->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream4->id(), kDefaultPriority);

  StreamBlocker stream2_blocker(&session_, stream2->id());
  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillOnce(Return(QuicTime::Delta::Zero()));
  EXPECT_CALL(*stream2, OnCanWrite());
  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillOnce(Return(QuicTime::Delta::Zero()));
  EXPECT_CALL(*stream6, OnCanWrite());
  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillOnce(Return(QuicTime::Delta::Infinite()));
  // stream4->OnCanWrite is not called.

  session_.OnCanWrite();
  EXPECT_TRUE(session_.WillingAndAbleToWrite());

  // Still congestion-control blocked.
  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillOnce(Return(QuicTime::Delta::Infinite()));
  session_.OnCanWrite();
  EXPECT_TRUE(session_.WillingAndAbleToWrite());

  // stream4->OnCanWrite is called once the connection stops being
  // congestion-control blocked.
  EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _))
      .WillOnce(Return(QuicTime::Delta::Zero()));
  EXPECT_CALL(*stream4, OnCanWrite());
  session_.OnCanWrite();
  EXPECT_FALSE(session_.WillingAndAbleToWrite());
}

TEST_P(QuicSessionTestServer, BufferedHandshake) {
  EXPECT_FALSE(session_.HasPendingHandshake());  // Default value.

  // Test that blocking other streams does not change our status.
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  StreamBlocker stream2_blocker(&session_, stream2->id());
  stream2_blocker.MarkConnectionLevelWriteBlocked();
  EXPECT_FALSE(session_.HasPendingHandshake());

  TestStream* stream3 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  StreamBlocker stream3_blocker(&session_, stream3->id());
  stream3_blocker.MarkConnectionLevelWriteBlocked();
  EXPECT_FALSE(session_.HasPendingHandshake());

  // Blocking (due to buffering of) the Crypto stream is detected.
  session_.MarkConnectionLevelWriteBlocked(kCryptoStreamId, kHighestPriority);
  EXPECT_TRUE(session_.HasPendingHandshake());

  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  StreamBlocker stream4_blocker(&session_, stream4->id());
  stream4_blocker.MarkConnectionLevelWriteBlocked();
  EXPECT_TRUE(session_.HasPendingHandshake());

  InSequence s;
  // Force most streams to re-register, which is common scenario when we block
  // the Crypto stream, and only the crypto stream can "really" write.

  // Due to prioritization, we *should* be asked to write the crypto stream
  // first.
  // Don't re-register the crypto stream (which signals complete writing).
  TestCryptoStream* crypto_stream = session_.GetCryptoStream();
  EXPECT_CALL(*crypto_stream, OnCanWrite());

  EXPECT_CALL(*stream2, OnCanWrite());
  EXPECT_CALL(*stream3, OnCanWrite());
  EXPECT_CALL(*stream4, OnCanWrite())
      .WillOnce(Invoke(&stream4_blocker,
                       &StreamBlocker::MarkConnectionLevelWriteBlocked));

  session_.OnCanWrite();
  EXPECT_TRUE(session_.WillingAndAbleToWrite());
  EXPECT_FALSE(session_.HasPendingHandshake());  // Crypto stream wrote.
}

TEST_P(QuicSessionTestServer, OnCanWriteWithClosedStream) {
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream4 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  TestStream* stream6 = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  session_.MarkConnectionLevelWriteBlocked(stream2->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream6->id(), kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream4->id(), kDefaultPriority);
  CloseStream(stream6->id());

  InSequence s;
  EXPECT_CALL(*stream2, OnCanWrite());
  EXPECT_CALL(*stream4, OnCanWrite());
  session_.OnCanWrite();
  EXPECT_FALSE(session_.WillingAndAbleToWrite());
}

TEST_P(QuicSessionTestServer, OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
  // Ensure connection level flow control blockage.
  QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(), 0);
  EXPECT_TRUE(session_.flow_controller()->IsBlocked());
  EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());

  // Mark the crypto and headers streams as write blocked, we expect them to be
  // allowed to write later.
  session_.MarkConnectionLevelWriteBlocked(kCryptoStreamId, kHighestPriority);
  session_.MarkConnectionLevelWriteBlocked(kHeadersStreamId, kHighestPriority);

  // Create a data stream, and although it is write blocked we never expect it
  // to be allowed to write as we are connection level flow control blocked.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  session_.MarkConnectionLevelWriteBlocked(stream->id(), kDefaultPriority);
  EXPECT_CALL(*stream, OnCanWrite()).Times(0);

  // The crypto and headers streams should be called even though we are
  // connection flow control blocked.
  TestCryptoStream* crypto_stream = session_.GetCryptoStream();
  EXPECT_CALL(*crypto_stream, OnCanWrite());
  TestHeadersStream* headers_stream = new TestHeadersStream(&session_);
  QuicSpdySessionPeer::SetHeadersStream(&session_, headers_stream);
  EXPECT_CALL(*headers_stream, OnCanWrite());

  session_.OnCanWrite();
  EXPECT_FALSE(session_.WillingAndAbleToWrite());
}

TEST_P(QuicSessionTestServer, SendGoAway) {
  MockPacketWriter* writer = static_cast<MockPacketWriter*>(
      QuicConnectionPeer::GetWriter(session_.connection()));
  EXPECT_CALL(*writer, WritePacket(_, _, _, _))
      .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
  EXPECT_CALL(*connection_, SendGoAway(_, _, _))
      .WillOnce(Invoke(connection_, &MockConnection::ReallySendGoAway));
  session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
  EXPECT_TRUE(session_.goaway_sent());

  const QuicStreamId kTestStreamId = 5u;
  EXPECT_CALL(*connection_,
              SendRstStream(kTestStreamId, QUIC_STREAM_PEER_GOING_AWAY, 0))
      .Times(0);
  EXPECT_TRUE(session_.GetOrCreateDynamicStream(kTestStreamId));
}

TEST_P(QuicSessionTestServer, IncreasedTimeoutAfterCryptoHandshake) {
  EXPECT_EQ(kInitialIdleTimeoutSecs + 3,
            QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
  CryptoHandshakeMessage msg;
  session_.GetCryptoStream()->OnHandshakeMessage(msg);
  EXPECT_EQ(kMaximumIdleTimeoutSecs + 3,
            QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
}

TEST_P(QuicSessionTestServer, RstStreamBeforeHeadersDecompressed) {
  // Send two bytes of payload.
  QuicStreamFrame data1(kClientDataStreamId1, false, 0, StringPiece("HT"));
  session_.OnStreamFrame(data1);
  EXPECT_EQ(1u, session_.GetNumOpenIncomingStreams());

  EXPECT_CALL(*connection_, SendRstStream(kClientDataStreamId1, _, _));
  QuicRstStreamFrame rst1(kClientDataStreamId1, QUIC_ERROR_PROCESSING_STREAM,
                          0);
  session_.OnRstStream(rst1);
  EXPECT_EQ(0u, session_.GetNumOpenIncomingStreams());
  // Connection should remain alive.
  EXPECT_TRUE(connection_->connected());
}

TEST_P(QuicSessionTestServer, MultipleRstStreamsCauseSingleConnectionClose) {
  // If multiple invalid reset stream frames arrive in a single packet, this
  // should trigger a connection close. However there is no need to send
  // multiple connection close frames.

  // Create valid stream.
  QuicStreamFrame data1(kClientDataStreamId1, false, 0, StringPiece("HT"));
  session_.OnStreamFrame(data1);
  EXPECT_EQ(1u, session_.GetNumOpenIncomingStreams());

  // Process first invalid stream reset, resulting in the connection being
  // closed.
  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(
                                QUIC_TOO_MANY_AVAILABLE_STREAMS, _));

  const QuicStreamId kLargeInvalidStreamId = 99999999;
  QuicRstStreamFrame rst1(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
  session_.OnRstStream(rst1);
  QuicConnectionPeer::CloseConnection(connection_);

  // Processing of second invalid stream reset should not result in the
  // connection being closed for a second time.
  QuicRstStreamFrame rst2(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
  session_.OnRstStream(rst2);
}

TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedStream) {
  // Test that if a stream is flow control blocked, then on receipt of the SHLO
  // containing a suitable send window offset, the stream becomes unblocked.

  // Ensure that Writev consumes all the data it is given (simulate no socket
  // blocking).
  session_.set_writev_consumes_all_data(true);

  // Create a stream, and send enough data to make it flow control blocked.
  TestStream* stream2 = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  string body(kMinimumFlowControlSendWindow, '.');
  EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  EXPECT_CALL(*connection_, SendBlocked(stream2->id()));
  EXPECT_CALL(*connection_, SendBlocked(0));
  stream2->SendBody(body, false);
  EXPECT_TRUE(stream2->flow_controller()->IsBlocked());
  EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
  EXPECT_TRUE(session_.IsStreamFlowControlBlocked());

  // The handshake message will call OnCanWrite, so the stream can resume
  // writing.
  EXPECT_CALL(*stream2, OnCanWrite());
  // Now complete the crypto handshake, resulting in an increased flow control
  // send window.
  CryptoHandshakeMessage msg;
  session_.GetCryptoStream()->OnHandshakeMessage(msg);

  // Stream is now unblocked.
  EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
}

TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedCryptoStream) {
  // Test that if the crypto stream is flow control blocked, then if the SHLO
  // contains a larger send window offset, the stream becomes unblocked.
  session_.set_writev_consumes_all_data(true);
  TestCryptoStream* crypto_stream = session_.GetCryptoStream();
  EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  QuicHeadersStream* headers_stream =
      QuicSpdySessionPeer::GetHeadersStream(&session_);
  EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  // Write until the crypto stream is flow control blocked.
  EXPECT_CALL(*connection_, SendBlocked(kCryptoStreamId));
  for (QuicStreamId i = 0;
       !crypto_stream->flow_controller()->IsBlocked() && i < 1000u; i++) {
    EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
    EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
    QuicConfig config;
    CryptoHandshakeMessage crypto_message;
    config.ToHandshakeMessage(&crypto_message);
    crypto_stream->SendHandshakeMessage(crypto_message);
  }
  EXPECT_TRUE(crypto_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
  EXPECT_FALSE(session_.HasDataToWrite());
  EXPECT_TRUE(crypto_stream->HasBufferedData());

  // The handshake message will call OnCanWrite, so the stream can
  // resume writing.
  EXPECT_CALL(*crypto_stream, OnCanWrite());
  // Now complete the crypto handshake, resulting in an increased flow control
  // send window.
  CryptoHandshakeMessage msg;
  session_.GetCryptoStream()->OnHandshakeMessage(msg);

  // Stream is now unblocked and will no longer have buffered data.
  EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
}

#if !defined(OS_IOS)
// This test is failing flakily for iOS bots.
// http://crbug.com/425050
// NOTE: It's not possible to use the standard MAYBE_ convention to disable
// this test on iOS because when this test gets instantiated it ends up with
// various names that are dependent on the parameters passed.
TEST_P(QuicSessionTestServer,
       HandshakeUnblocksFlowControlBlockedHeadersStream) {
  // Test that if the header stream is flow control blocked, then if the SHLO
  // contains a larger send window offset, the stream becomes unblocked.
  session_.set_writev_consumes_all_data(true);
  TestCryptoStream* crypto_stream = session_.GetCryptoStream();
  EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  QuicHeadersStream* headers_stream =
      QuicSpdySessionPeer::GetHeadersStream(&session_);
  EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  QuicStreamId stream_id = 5;
  // Write until the header stream is flow control blocked.
  EXPECT_CALL(*connection_, SendBlocked(kHeadersStreamId));
  SpdyHeaderBlock headers;
  while (!headers_stream->flow_controller()->IsBlocked() && stream_id < 2000) {
    EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
    EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
    headers["header"] = base::Uint64ToString(base::RandUint64()) +
                        base::Uint64ToString(base::RandUint64()) +
                        base::Uint64ToString(base::RandUint64());
    headers_stream->WriteHeaders(stream_id, headers, true, 0, nullptr);
    stream_id += 2;
  }
  // Write once more to ensure that the headers stream has buffered data. The
  // random headers may have exactly filled the flow control window.
  headers_stream->WriteHeaders(stream_id, headers, true, 0, nullptr);
  EXPECT_TRUE(headers_stream->HasBufferedData());

  EXPECT_TRUE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
  EXPECT_FALSE(session_.HasDataToWrite());

  // Now complete the crypto handshake, resulting in an increased flow control
  // send window.
  CryptoHandshakeMessage msg;
  session_.GetCryptoStream()->OnHandshakeMessage(msg);

  // Stream is now unblocked and will no longer have buffered data.
  EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
  EXPECT_FALSE(headers_stream->HasBufferedData());
}
#endif  // !defined(OS_IOS)

TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstOutOfOrder) {
  // Test that when we receive an out of order stream RST we correctly adjust
  // our connection level flow control receive window.
  // On close, the stream should mark as consumed all bytes between the highest
  // byte consumed so far and the final byte offset from the RST frame.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  const QuicStreamOffset kByteOffset =
      1 + kInitialSessionFlowControlWindowForTest / 2;

  // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
  EXPECT_CALL(*connection_, SendWindowUpdate(stream->id(), _)).Times(0);
  // We do expect a connection level WINDOW_UPDATE when the stream is reset.
  EXPECT_CALL(*connection_,
              SendWindowUpdate(
                  0, kInitialSessionFlowControlWindowForTest + kByteOffset));

  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
                               kByteOffset);
  session_.OnRstStream(rst_frame);
  session_.PostProcessAfterData();
  EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
}

TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAndLocalReset) {
  // Test the situation where we receive a FIN on a stream, and before we fully
  // consume all the data from the sequencer buffer we locally RST the stream.
  // The bytes between highest consumed byte, and the final byte offset that we
  // determined when the FIN arrived, should be marked as consumed at the
  // connection level flow controller when the stream is reset.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);

  const QuicStreamOffset kByteOffset =
      kInitialSessionFlowControlWindowForTest / 2;
  QuicStreamFrame frame(stream->id(), true, kByteOffset, StringPiece());
  session_.OnStreamFrame(frame);
  session_.PostProcessAfterData();
  EXPECT_TRUE(connection_->connected());

  EXPECT_EQ(0u, stream->flow_controller()->bytes_consumed());
  EXPECT_EQ(kByteOffset,
            stream->flow_controller()->highest_received_byte_offset());

  // Reset stream locally.
  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  stream->Reset(QUIC_STREAM_CANCELLED);
  EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
}

TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAfterRst) {
  // Test that when we RST the stream (and tear down stream state), and then
  // receive a FIN from the peer, we correctly adjust our connection level flow
  // control receive window.

  // Connection starts with some non-zero highest received byte offset,
  // due to other active streams.
  const uint64_t kInitialConnectionBytesConsumed = 567;
  const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
  EXPECT_LT(kInitialConnectionBytesConsumed,
            kInitialConnectionHighestReceivedOffset);
  session_.flow_controller()->UpdateHighestReceivedOffset(
      kInitialConnectionHighestReceivedOffset);
  session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);

  // Reset our stream: this results in the stream being closed locally.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  stream->Reset(QUIC_STREAM_CANCELLED);

  // Now receive a response from the peer with a FIN. We should handle this by
  // adjusting the connection level flow control receive window to take into
  // account the total number of bytes sent by the peer.
  const QuicStreamOffset kByteOffset = 5678;
  string body = "hello";
  QuicStreamFrame frame(stream->id(), true, kByteOffset, StringPiece(body));
  session_.OnStreamFrame(frame);

  QuicStreamOffset total_stream_bytes_sent_by_peer =
      kByteOffset + body.length();
  EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer,
            session_.flow_controller()->bytes_consumed());
  EXPECT_EQ(
      kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer,
      session_.flow_controller()->highest_received_byte_offset());
}

TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstAfterRst) {
  // Test that when we RST the stream (and tear down stream state), and then
  // receive a RST from the peer, we correctly adjust our connection level flow
  // control receive window.

  // Connection starts with some non-zero highest received byte offset,
  // due to other active streams.
  const uint64_t kInitialConnectionBytesConsumed = 567;
  const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
  EXPECT_LT(kInitialConnectionBytesConsumed,
            kInitialConnectionHighestReceivedOffset);
  session_.flow_controller()->UpdateHighestReceivedOffset(
      kInitialConnectionHighestReceivedOffset);
  session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);

  // Reset our stream: this results in the stream being closed locally.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  stream->Reset(QUIC_STREAM_CANCELLED);
  EXPECT_TRUE(ReliableQuicStreamPeer::read_side_closed(stream));

  // Now receive a RST from the peer. We should handle this by adjusting the
  // connection level flow control receive window to take into account the total
  // number of bytes sent by the peer.
  const QuicStreamOffset kByteOffset = 5678;
  QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
                               kByteOffset);
  session_.OnRstStream(rst_frame);

  EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset,
            session_.flow_controller()->bytes_consumed());
  EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset,
            session_.flow_controller()->highest_received_byte_offset());
}

TEST_P(QuicSessionTestServer, InvalidStreamFlowControlWindowInHandshake) {
  // Test that receipt of an invalid (< default) stream flow control window from
  // the peer results in the connection being torn down.
  const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
  QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(),
                                                            kInvalidWindow);

  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(
                                QUIC_FLOW_CONTROL_INVALID_WINDOW, _));
  session_.OnConfigNegotiated();
}

TEST_P(QuicSessionTestServer, InvalidSessionFlowControlWindowInHandshake) {
  // Test that receipt of an invalid (< default) session flow control window
  // from the peer results in the connection being torn down.
  const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
  QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(),
                                                             kInvalidWindow);

  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(
                                QUIC_FLOW_CONTROL_INVALID_WINDOW, _));
  session_.OnConfigNegotiated();
}

TEST_P(QuicSessionTestServer, FlowControlWithInvalidFinalOffset) {
  // Test that if we receive a stream RST with a highest byte offset that
  // violates flow control, that we close the connection.
  const uint64_t kLargeOffset = kInitialSessionFlowControlWindowForTest + 1;
  EXPECT_CALL(*connection_, SendConnectionCloseWithDetails(
                                QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _))
      .Times(2);

  // Check that stream frame + FIN results in connection close.
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  stream->Reset(QUIC_STREAM_CANCELLED);
  QuicStreamFrame frame(stream->id(), true, kLargeOffset, StringPiece());
  session_.OnStreamFrame(frame);

  // Check that RST results in connection close.
  QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
                               kLargeOffset);
  session_.OnRstStream(rst_frame);
}

TEST_P(QuicSessionTestServer, WindowUpdateUnblocksHeadersStream) {
  // Test that a flow control blocked headers stream gets unblocked on recipt of
  // a WINDOW_UPDATE frame.

  // Set the headers stream to be flow control blocked.
  QuicHeadersStream* headers_stream =
      QuicSpdySessionPeer::GetHeadersStream(&session_);
  QuicFlowControllerPeer::SetSendWindowOffset(headers_stream->flow_controller(),
                                              0);
  EXPECT_TRUE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_TRUE(session_.IsStreamFlowControlBlocked());

  // Unblock the headers stream by supplying a WINDOW_UPDATE.
  QuicWindowUpdateFrame window_update_frame(headers_stream->id(),
                                            2 * kMinimumFlowControlSendWindow);
  session_.OnWindowUpdateFrame(window_update_frame);
  EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
  EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
  EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
}

TEST_P(QuicSessionTestServer, TooManyUnfinishedStreamsCauseServerRejectStream) {
  // If a buggy/malicious peer creates too many streams that are not ended
  // with a FIN or RST then we send a connection close or an RST to
  // refuse streams.
  const QuicStreamId kMaxStreams = 5;
  QuicSessionPeer::SetMaxOpenStreams(&session_, kMaxStreams);
  const QuicStreamId kFirstStreamId = kClientDataStreamId1;
  const QuicStreamId kFinalStreamId = kClientDataStreamId1 + 2 * kMaxStreams;

  // Create kMaxStreams data streams, and close them all without receiving a
  // FIN or a RST_STREAM from the client.
  for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += 2) {
    QuicStreamFrame data1(i, false, 0, StringPiece("HT"));
    session_.OnStreamFrame(data1);
    // EXPECT_EQ(1u, session_.GetNumOpenStreams());
    EXPECT_CALL(*connection_, SendRstStream(i, _, _));
    session_.CloseStream(i);
  }

  if (GetParam() <= QUIC_VERSION_27) {
    EXPECT_CALL(*connection_,
                SendConnectionCloseWithDetails(QUIC_TOO_MANY_OPEN_STREAMS, _));
    EXPECT_CALL(*connection_, SendRstStream(kFinalStreamId, _, _)).Times(0);
  } else {
    EXPECT_CALL(*connection_,
                SendRstStream(kFinalStreamId, QUIC_REFUSED_STREAM, _))
        .Times(1);
  }
  // Create one more data streams to exceed limit of open stream.
  QuicStreamFrame data1(kFinalStreamId, false, 0, StringPiece("HT"));
  session_.OnStreamFrame(data1);

  // Called after any new data is received by the session, and triggers the
  // call to close the connection.
  session_.PostProcessAfterData();
}

TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpened) {
  // Verify that a draining stream (which has received a FIN but not consumed
  // it) does not count against the open quota (because it is closed from the
  // protocol point of view).
  if (GetParam() <= QUIC_VERSION_27) {
    EXPECT_CALL(*connection_,
                SendConnectionCloseWithDetails(QUIC_TOO_MANY_OPEN_STREAMS, _))
        .Times(0);
  } else {
    EXPECT_CALL(*connection_, SendRstStream(_, QUIC_REFUSED_STREAM, _))
        .Times(0);
  }
  const QuicStreamId kMaxStreams = 5;
  QuicSessionPeer::SetMaxOpenStreams(&session_, kMaxStreams);

  // Create kMaxStreams + 1 data streams, and mark them draining.
  const QuicStreamId kFirstStreamId = kClientDataStreamId1;
  const QuicStreamId kFinalStreamId =
      kClientDataStreamId1 + 2 * kMaxStreams + 1;
  for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += 2) {
    QuicStreamFrame data1(i, true, 0, StringPiece("HT"));
    session_.OnStreamFrame(data1);
    EXPECT_EQ(1u, session_.GetNumOpenIncomingStreams());
    session_.StreamDraining(i);
    EXPECT_EQ(0u, session_.GetNumOpenIncomingStreams());
  }

  // Called after any new data is received by the session, and triggers the call
  // to close the connection.
  session_.PostProcessAfterData();
}

class QuicSessionTestClient : public QuicSessionTestBase {
 protected:
  QuicSessionTestClient() : QuicSessionTestBase(Perspective::IS_CLIENT) {}
};

INSTANTIATE_TEST_CASE_P(Tests,
                        QuicSessionTestClient,
                        ::testing::ValuesIn(QuicSupportedVersions()));

TEST_P(QuicSessionTestClient, AvailableStreamsClient) {
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(6) != nullptr);
  // Both 2 and 4 should be available.
  EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(&session_, 2));
  EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(&session_, 4));
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(2) != nullptr);
  ASSERT_TRUE(session_.GetOrCreateDynamicStream(4) != nullptr);
  // And 5 should be not available.
  EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(&session_, 5));
}

TEST_P(QuicSessionTestClient, RecordFinAfterReadSideClosed) {
  // Verify that an incoming FIN is recorded in a stream object even if the read
  // side has been closed.  This prevents an entry from being made in
  // locally_closed_streams_highest_offset_ (which will never be deleted).
  TestStream* stream = session_.CreateOutgoingDynamicStream(kDefaultPriority);
  QuicStreamId stream_id = stream->id();

  // Close the read side manually.
  ReliableQuicStreamPeer::CloseReadSide(stream);

  // Receive a stream data frame with FIN.
  QuicStreamFrame frame(stream_id, true, 0, StringPiece());
  session_.OnStreamFrame(frame);
  EXPECT_TRUE(stream->fin_received());

  // Reset stream locally.
  EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
  stream->Reset(QUIC_STREAM_CANCELLED);
  EXPECT_TRUE(ReliableQuicStreamPeer::read_side_closed(stream));

  // Allow the session to delete the stream object.
  session_.PostProcessAfterData();
  EXPECT_TRUE(connection_->connected());
  EXPECT_TRUE(QuicSessionPeer::IsStreamClosed(&session_, stream_id));
  EXPECT_EQ(nullptr, QuicSessionPeer::dynamic_streams(&session_)[stream_id]);

  // The stream is not waiting for the arrival of the peer's final offset as it
  // was received with the FIN earlier.
  EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(&session_)
                    .size());
}

}  // namespace
}  // namespace test
}  // namespace net