Clean up URLFetcher unit tests, part 8.
[chromium-blink-merge.git] / net / quic / quic_session_test.cc
blobc3f49070201b66767afee858eba5721e245d2cdf
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.
5 #include "net/quic/quic_session.h"
7 #include <set>
9 #include "base/basictypes.h"
10 #include "base/containers/hash_tables.h"
11 #include "base/rand_util.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "net/quic/crypto/crypto_protocol.h"
15 #include "net/quic/quic_crypto_stream.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_protocol.h"
18 #include "net/quic/quic_utils.h"
19 #include "net/quic/reliable_quic_stream.h"
20 #include "net/quic/test_tools/quic_config_peer.h"
21 #include "net/quic/test_tools/quic_connection_peer.h"
22 #include "net/quic/test_tools/quic_data_stream_peer.h"
23 #include "net/quic/test_tools/quic_flow_controller_peer.h"
24 #include "net/quic/test_tools/quic_session_peer.h"
25 #include "net/quic/test_tools/quic_test_utils.h"
26 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
27 #include "net/spdy/spdy_framer.h"
28 #include "net/test/gtest_util.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gmock_mutant.h"
31 #include "testing/gtest/include/gtest/gtest.h"
33 using base::hash_map;
34 using std::set;
35 using std::string;
36 using std::vector;
37 using testing::CreateFunctor;
38 using testing::InSequence;
39 using testing::Invoke;
40 using testing::Return;
41 using testing::StrictMock;
42 using testing::_;
44 namespace net {
45 namespace test {
46 namespace {
48 const QuicPriority kHighestPriority = 0;
49 const QuicPriority kSomeMiddlePriority = 3;
51 class TestCryptoStream : public QuicCryptoStream {
52 public:
53 explicit TestCryptoStream(QuicSession* session)
54 : QuicCryptoStream(session) {
57 void OnHandshakeMessage(const CryptoHandshakeMessage& message) override {
58 encryption_established_ = true;
59 handshake_confirmed_ = true;
60 CryptoHandshakeMessage msg;
61 string error_details;
62 session()->config()->SetInitialStreamFlowControlWindowToSend(
63 kInitialStreamFlowControlWindowForTest);
64 session()->config()->SetInitialSessionFlowControlWindowToSend(
65 kInitialSessionFlowControlWindowForTest);
66 session()->config()->ToHandshakeMessage(&msg);
67 const QuicErrorCode error = session()->config()->ProcessPeerHello(
68 msg, CLIENT, &error_details);
69 EXPECT_EQ(QUIC_NO_ERROR, error);
70 session()->OnConfigNegotiated();
71 session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED);
74 MOCK_METHOD0(OnCanWrite, void());
77 class TestHeadersStream : public QuicHeadersStream {
78 public:
79 explicit TestHeadersStream(QuicSession* session)
80 : QuicHeadersStream(session) {
83 MOCK_METHOD0(OnCanWrite, void());
86 class TestStream : public QuicDataStream {
87 public:
88 TestStream(QuicStreamId id, QuicSession* session)
89 : QuicDataStream(id, session) {
92 using ReliableQuicStream::CloseWriteSide;
94 uint32 ProcessData(const char* data, uint32 data_len) override {
95 return data_len;
98 void SendBody(const string& data, bool fin) {
99 WriteOrBufferData(data, fin, nullptr);
102 MOCK_METHOD0(OnCanWrite, void());
105 // Poor man's functor for use as callback in a mock.
106 class StreamBlocker {
107 public:
108 StreamBlocker(QuicSession* session, QuicStreamId stream_id)
109 : session_(session),
110 stream_id_(stream_id) {
113 void MarkWriteBlocked() {
114 session_->MarkWriteBlocked(stream_id_, kSomeMiddlePriority);
117 private:
118 QuicSession* const session_;
119 const QuicStreamId stream_id_;
122 class TestSession : public QuicSession {
123 public:
124 explicit TestSession(QuicConnection* connection)
125 : QuicSession(connection, DefaultQuicConfig()),
126 crypto_stream_(this),
127 writev_consumes_all_data_(false) {
128 InitializeSession();
131 TestCryptoStream* GetCryptoStream() override { return &crypto_stream_; }
133 TestStream* CreateOutgoingDataStream() override {
134 TestStream* stream = new TestStream(GetNextStreamId(), this);
135 ActivateStream(stream);
136 return stream;
139 TestStream* CreateIncomingDataStream(QuicStreamId id) override {
140 return new TestStream(id, this);
143 bool IsClosedStream(QuicStreamId id) {
144 return QuicSession::IsClosedStream(id);
147 QuicDataStream* GetIncomingDataStream(QuicStreamId stream_id) {
148 return QuicSession::GetIncomingDataStream(stream_id);
151 QuicConsumedData WritevData(
152 QuicStreamId id,
153 const IOVector& data,
154 QuicStreamOffset offset,
155 bool fin,
156 FecProtection fec_protection,
157 QuicAckNotifier::DelegateInterface* ack_notifier_delegate) override {
158 // Always consumes everything.
159 if (writev_consumes_all_data_) {
160 return QuicConsumedData(data.TotalBufferSize(), fin);
161 } else {
162 return QuicSession::WritevData(id, data, offset, fin, fec_protection,
163 ack_notifier_delegate);
167 void set_writev_consumes_all_data(bool val) {
168 writev_consumes_all_data_ = val;
171 QuicConsumedData SendStreamData(QuicStreamId id) {
172 return WritevData(id, MakeIOVector("not empty"), 0, true, MAY_FEC_PROTECT,
173 nullptr);
176 using QuicSession::PostProcessAfterData;
178 private:
179 StrictMock<TestCryptoStream> crypto_stream_;
181 bool writev_consumes_all_data_;
184 class QuicSessionTest : public ::testing::TestWithParam<QuicVersion> {
185 protected:
186 QuicSessionTest()
187 : connection_(
188 new StrictMock<MockConnection>(Perspective::IS_SERVER,
189 SupportedVersions(GetParam()))),
190 session_(connection_) {
191 session_.config()->SetInitialStreamFlowControlWindowToSend(
192 kInitialStreamFlowControlWindowForTest);
193 session_.config()->SetInitialSessionFlowControlWindowToSend(
194 kInitialSessionFlowControlWindowForTest);
195 headers_[":host"] = "www.google.com";
196 headers_[":path"] = "/index.hml";
197 headers_[":scheme"] = "http";
198 headers_["cookie"] =
199 "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
200 "__utmc=160408618; "
201 "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX"
202 "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX"
203 "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT"
204 "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0"
205 "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh"
206 "1zFMi5vzcns38-8_Sns; "
207 "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-"
208 "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339"
209 "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c"
210 "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%"
211 "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4"
212 "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1"
213 "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP"
214 "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6"
215 "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b"
216 "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6"
217 "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG"
218 "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk"
219 "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn"
220 "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr"
221 "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo ";
222 connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
225 void CheckClosedStreams() {
226 for (int i = kCryptoStreamId; i < 100; i++) {
227 if (!ContainsKey(closed_streams_, i)) {
228 EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
229 } else {
230 EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
235 void CloseStream(QuicStreamId id) {
236 EXPECT_CALL(*connection_, SendRstStream(id, _, _));
237 session_.CloseStream(id);
238 closed_streams_.insert(id);
241 QuicVersion version() const { return connection_->version(); }
243 StrictMock<MockConnection>* connection_;
244 TestSession session_;
245 set<QuicStreamId> closed_streams_;
246 SpdyHeaderBlock headers_;
249 INSTANTIATE_TEST_CASE_P(Tests, QuicSessionTest,
250 ::testing::ValuesIn(QuicSupportedVersions()));
252 TEST_P(QuicSessionTest, PeerAddress) {
253 EXPECT_EQ(IPEndPoint(Loopback4(), kTestPort), session_.peer_address());
256 TEST_P(QuicSessionTest, IsCryptoHandshakeConfirmed) {
257 EXPECT_FALSE(session_.IsCryptoHandshakeConfirmed());
258 CryptoHandshakeMessage message;
259 session_.GetCryptoStream()->OnHandshakeMessage(message);
260 EXPECT_TRUE(session_.IsCryptoHandshakeConfirmed());
263 TEST_P(QuicSessionTest, IsClosedStreamDefault) {
264 // Ensure that no streams are initially closed.
265 for (int i = kCryptoStreamId; i < 100; i++) {
266 EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i;
270 TEST_P(QuicSessionTest, ImplicitlyCreatedStreams) {
271 ASSERT_TRUE(session_.GetIncomingDataStream(7) != nullptr);
272 // Both 3 and 5 should be implicitly created.
273 EXPECT_FALSE(session_.IsClosedStream(3));
274 EXPECT_FALSE(session_.IsClosedStream(5));
275 ASSERT_TRUE(session_.GetIncomingDataStream(5) != nullptr);
276 ASSERT_TRUE(session_.GetIncomingDataStream(3) != nullptr);
279 TEST_P(QuicSessionTest, IsClosedStreamLocallyCreated) {
280 TestStream* stream2 = session_.CreateOutgoingDataStream();
281 EXPECT_EQ(2u, stream2->id());
282 TestStream* stream4 = session_.CreateOutgoingDataStream();
283 EXPECT_EQ(4u, stream4->id());
285 CheckClosedStreams();
286 CloseStream(4);
287 CheckClosedStreams();
288 CloseStream(2);
289 CheckClosedStreams();
292 TEST_P(QuicSessionTest, IsClosedStreamPeerCreated) {
293 QuicStreamId stream_id1 = kClientDataStreamId1;
294 QuicStreamId stream_id2 = kClientDataStreamId2;
295 QuicDataStream* stream1 = session_.GetIncomingDataStream(stream_id1);
296 QuicDataStreamPeer::SetHeadersDecompressed(stream1, true);
297 QuicDataStream* stream2 = session_.GetIncomingDataStream(stream_id2);
298 QuicDataStreamPeer::SetHeadersDecompressed(stream2, true);
300 CheckClosedStreams();
301 CloseStream(stream_id1);
302 CheckClosedStreams();
303 CloseStream(stream_id2);
304 // Create a stream explicitly, and another implicitly.
305 QuicDataStream* stream3 = session_.GetIncomingDataStream(stream_id2 + 4);
306 QuicDataStreamPeer::SetHeadersDecompressed(stream3, true);
307 CheckClosedStreams();
308 // Close one, but make sure the other is still not closed
309 CloseStream(stream3->id());
310 CheckClosedStreams();
313 TEST_P(QuicSessionTest, StreamIdTooLarge) {
314 QuicStreamId stream_id = kClientDataStreamId1;
315 session_.GetIncomingDataStream(stream_id);
316 EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID));
317 session_.GetIncomingDataStream(stream_id + kMaxStreamIdDelta + 2);
320 TEST_P(QuicSessionTest, DebugDFatalIfMarkingClosedStreamWriteBlocked) {
321 TestStream* stream2 = session_.CreateOutgoingDataStream();
322 QuicStreamId kClosedStreamId = stream2->id();
323 // Close the stream.
324 EXPECT_CALL(*connection_, SendRstStream(kClosedStreamId, _, _));
325 stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
326 EXPECT_DEBUG_DFATAL(
327 session_.MarkWriteBlocked(kClosedStreamId, kSomeMiddlePriority),
328 "Marking unknown stream 2 blocked.");
331 TEST_P(QuicSessionTest, DebugDFatalIfMarkWriteBlockedCalledWithWrongPriority) {
332 const QuicPriority kDifferentPriority = 0;
334 TestStream* stream2 = session_.CreateOutgoingDataStream();
335 EXPECT_NE(kDifferentPriority, stream2->EffectivePriority());
336 EXPECT_DEBUG_DFATAL(
337 session_.MarkWriteBlocked(stream2->id(), kDifferentPriority),
338 "Priorities do not match. Got: 0 Expected: 3");
341 TEST_P(QuicSessionTest, OnCanWrite) {
342 TestStream* stream2 = session_.CreateOutgoingDataStream();
343 TestStream* stream4 = session_.CreateOutgoingDataStream();
344 TestStream* stream6 = session_.CreateOutgoingDataStream();
346 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
347 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
348 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
350 InSequence s;
351 StreamBlocker stream2_blocker(&session_, stream2->id());
352 // Reregister, to test the loop limit.
353 EXPECT_CALL(*stream2, OnCanWrite())
354 .WillOnce(Invoke(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
355 EXPECT_CALL(*stream6, OnCanWrite());
356 EXPECT_CALL(*stream4, OnCanWrite());
357 session_.OnCanWrite();
358 EXPECT_TRUE(session_.WillingAndAbleToWrite());
361 TEST_P(QuicSessionTest, OnCanWriteBundlesStreams) {
362 // Drive congestion control manually.
363 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
364 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
366 TestStream* stream2 = session_.CreateOutgoingDataStream();
367 TestStream* stream4 = session_.CreateOutgoingDataStream();
368 TestStream* stream6 = session_.CreateOutgoingDataStream();
370 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
371 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
372 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
374 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillRepeatedly(
375 Return(QuicTime::Delta::Zero()));
376 EXPECT_CALL(*send_algorithm, GetCongestionWindow())
377 .WillRepeatedly(Return(kMaxPacketSize * 10));
378 EXPECT_CALL(*stream2, OnCanWrite())
379 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
380 &session_, &TestSession::SendStreamData, stream2->id()))));
381 EXPECT_CALL(*stream4, OnCanWrite())
382 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
383 &session_, &TestSession::SendStreamData, stream4->id()))));
384 EXPECT_CALL(*stream6, OnCanWrite())
385 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
386 &session_, &TestSession::SendStreamData, stream6->id()))));
388 // Expect that we only send one packet, the writes from different streams
389 // should be bundled together.
390 MockPacketWriter* writer =
391 static_cast<MockPacketWriter*>(
392 QuicConnectionPeer::GetWriter(session_.connection()));
393 EXPECT_CALL(*writer, WritePacket(_, _, _, _)).WillOnce(
394 Return(WriteResult(WRITE_STATUS_OK, 0)));
395 EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _)).Times(1);
396 session_.OnCanWrite();
397 EXPECT_FALSE(session_.WillingAndAbleToWrite());
400 TEST_P(QuicSessionTest, OnCanWriteCongestionControlBlocks) {
401 InSequence s;
403 // Drive congestion control manually.
404 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
405 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
407 TestStream* stream2 = session_.CreateOutgoingDataStream();
408 TestStream* stream4 = session_.CreateOutgoingDataStream();
409 TestStream* stream6 = session_.CreateOutgoingDataStream();
411 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
412 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
413 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
415 StreamBlocker stream2_blocker(&session_, stream2->id());
416 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
417 QuicTime::Delta::Zero()));
418 EXPECT_CALL(*stream2, OnCanWrite());
419 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
420 QuicTime::Delta::Zero()));
421 EXPECT_CALL(*stream6, OnCanWrite());
422 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
423 QuicTime::Delta::Infinite()));
424 // stream4->OnCanWrite is not called.
426 session_.OnCanWrite();
427 EXPECT_TRUE(session_.WillingAndAbleToWrite());
429 // Still congestion-control blocked.
430 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
431 QuicTime::Delta::Infinite()));
432 session_.OnCanWrite();
433 EXPECT_TRUE(session_.WillingAndAbleToWrite());
435 // stream4->OnCanWrite is called once the connection stops being
436 // congestion-control blocked.
437 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
438 QuicTime::Delta::Zero()));
439 EXPECT_CALL(*stream4, OnCanWrite());
440 session_.OnCanWrite();
441 EXPECT_FALSE(session_.WillingAndAbleToWrite());
444 TEST_P(QuicSessionTest, BufferedHandshake) {
445 EXPECT_FALSE(session_.HasPendingHandshake()); // Default value.
447 // Test that blocking other streams does not change our status.
448 TestStream* stream2 = session_.CreateOutgoingDataStream();
449 StreamBlocker stream2_blocker(&session_, stream2->id());
450 stream2_blocker.MarkWriteBlocked();
451 EXPECT_FALSE(session_.HasPendingHandshake());
453 TestStream* stream3 = session_.CreateOutgoingDataStream();
454 StreamBlocker stream3_blocker(&session_, stream3->id());
455 stream3_blocker.MarkWriteBlocked();
456 EXPECT_FALSE(session_.HasPendingHandshake());
458 // Blocking (due to buffering of) the Crypto stream is detected.
459 session_.MarkWriteBlocked(kCryptoStreamId, kHighestPriority);
460 EXPECT_TRUE(session_.HasPendingHandshake());
462 TestStream* stream4 = session_.CreateOutgoingDataStream();
463 StreamBlocker stream4_blocker(&session_, stream4->id());
464 stream4_blocker.MarkWriteBlocked();
465 EXPECT_TRUE(session_.HasPendingHandshake());
467 InSequence s;
468 // Force most streams to re-register, which is common scenario when we block
469 // the Crypto stream, and only the crypto stream can "really" write.
471 // Due to prioritization, we *should* be asked to write the crypto stream
472 // first.
473 // Don't re-register the crypto stream (which signals complete writing).
474 TestCryptoStream* crypto_stream = session_.GetCryptoStream();
475 EXPECT_CALL(*crypto_stream, OnCanWrite());
477 // Re-register all other streams, to show they weren't able to proceed.
478 EXPECT_CALL(*stream2, OnCanWrite())
479 .WillOnce(Invoke(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
480 EXPECT_CALL(*stream3, OnCanWrite())
481 .WillOnce(Invoke(&stream3_blocker, &StreamBlocker::MarkWriteBlocked));
482 EXPECT_CALL(*stream4, OnCanWrite())
483 .WillOnce(Invoke(&stream4_blocker, &StreamBlocker::MarkWriteBlocked));
485 session_.OnCanWrite();
486 EXPECT_TRUE(session_.WillingAndAbleToWrite());
487 EXPECT_FALSE(session_.HasPendingHandshake()); // Crypto stream wrote.
490 TEST_P(QuicSessionTest, OnCanWriteWithClosedStream) {
491 TestStream* stream2 = session_.CreateOutgoingDataStream();
492 TestStream* stream4 = session_.CreateOutgoingDataStream();
493 TestStream* stream6 = session_.CreateOutgoingDataStream();
495 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
496 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
497 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
498 CloseStream(stream6->id());
500 InSequence s;
501 EXPECT_CALL(*stream2, OnCanWrite());
502 EXPECT_CALL(*stream4, OnCanWrite());
503 session_.OnCanWrite();
504 EXPECT_FALSE(session_.WillingAndAbleToWrite());
507 TEST_P(QuicSessionTest, OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
508 // Ensure connection level flow control blockage.
509 QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(), 0);
510 EXPECT_TRUE(session_.flow_controller()->IsBlocked());
511 EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
512 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
514 // Mark the crypto and headers streams as write blocked, we expect them to be
515 // allowed to write later.
516 session_.MarkWriteBlocked(kCryptoStreamId, kHighestPriority);
517 session_.MarkWriteBlocked(kHeadersStreamId, kHighestPriority);
519 // Create a data stream, and although it is write blocked we never expect it
520 // to be allowed to write as we are connection level flow control blocked.
521 TestStream* stream = session_.CreateOutgoingDataStream();
522 session_.MarkWriteBlocked(stream->id(), kSomeMiddlePriority);
523 EXPECT_CALL(*stream, OnCanWrite()).Times(0);
525 // The crypto and headers streams should be called even though we are
526 // connection flow control blocked.
527 TestCryptoStream* crypto_stream = session_.GetCryptoStream();
528 EXPECT_CALL(*crypto_stream, OnCanWrite()).Times(1);
529 TestHeadersStream* headers_stream = new TestHeadersStream(&session_);
530 QuicSessionPeer::SetHeadersStream(&session_, headers_stream);
531 EXPECT_CALL(*headers_stream, OnCanWrite()).Times(1);
533 session_.OnCanWrite();
534 EXPECT_FALSE(session_.WillingAndAbleToWrite());
537 TEST_P(QuicSessionTest, SendGoAway) {
538 EXPECT_CALL(*connection_,
539 SendGoAway(QUIC_PEER_GOING_AWAY, 0u, "Going Away."));
540 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
541 EXPECT_TRUE(session_.goaway_sent());
543 EXPECT_CALL(*connection_,
544 SendRstStream(3u, QUIC_STREAM_PEER_GOING_AWAY, 0)).Times(0);
545 EXPECT_TRUE(session_.GetIncomingDataStream(3u));
548 TEST_P(QuicSessionTest, DoNotSendGoAwayTwice) {
549 EXPECT_CALL(*connection_,
550 SendGoAway(QUIC_PEER_GOING_AWAY, 0u, "Going Away.")).Times(1);
551 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
552 EXPECT_TRUE(session_.goaway_sent());
553 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
556 TEST_P(QuicSessionTest, IncreasedTimeoutAfterCryptoHandshake) {
557 EXPECT_EQ(kInitialIdleTimeoutSecs + 3,
558 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
559 CryptoHandshakeMessage msg;
560 session_.GetCryptoStream()->OnHandshakeMessage(msg);
561 EXPECT_EQ(kMaximumIdleTimeoutSecs + 3,
562 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
565 TEST_P(QuicSessionTest, RstStreamBeforeHeadersDecompressed) {
566 // Send two bytes of payload.
567 QuicStreamFrame data1(kClientDataStreamId1, false, 0, MakeIOVector("HT"));
568 vector<QuicStreamFrame> frames;
569 frames.push_back(data1);
570 session_.OnStreamFrames(frames);
571 EXPECT_EQ(1u, session_.GetNumOpenStreams());
573 EXPECT_CALL(*connection_, SendRstStream(kClientDataStreamId1, _, _));
574 QuicRstStreamFrame rst1(kClientDataStreamId1, QUIC_STREAM_NO_ERROR, 0);
575 session_.OnRstStream(rst1);
576 EXPECT_EQ(0u, session_.GetNumOpenStreams());
577 // Connection should remain alive.
578 EXPECT_TRUE(connection_->connected());
581 TEST_P(QuicSessionTest, MultipleRstStreamsCauseSingleConnectionClose) {
582 // If multiple invalid reset stream frames arrive in a single packet, this
583 // should trigger a connection close. However there is no need to send
584 // multiple connection close frames.
586 // Create valid stream.
587 QuicStreamFrame data1(kClientDataStreamId1, false, 0, MakeIOVector("HT"));
588 vector<QuicStreamFrame> frames;
589 frames.push_back(data1);
590 session_.OnStreamFrames(frames);
591 EXPECT_EQ(1u, session_.GetNumOpenStreams());
593 // Process first invalid stream reset, resulting in the connection being
594 // closed.
595 EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID))
596 .Times(1);
597 QuicStreamId kLargeInvalidStreamId = 99999999;
598 QuicRstStreamFrame rst1(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
599 session_.OnRstStream(rst1);
600 QuicConnectionPeer::CloseConnection(connection_);
602 // Processing of second invalid stream reset should not result in the
603 // connection being closed for a second time.
604 QuicRstStreamFrame rst2(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
605 session_.OnRstStream(rst2);
608 TEST_P(QuicSessionTest, HandshakeUnblocksFlowControlBlockedStream) {
609 // Test that if a stream is flow control blocked, then on receipt of the SHLO
610 // containing a suitable send window offset, the stream becomes unblocked.
612 // Ensure that Writev consumes all the data it is given (simulate no socket
613 // blocking).
614 session_.set_writev_consumes_all_data(true);
616 // Create a stream, and send enough data to make it flow control blocked.
617 TestStream* stream2 = session_.CreateOutgoingDataStream();
618 string body(kMinimumFlowControlSendWindow, '.');
619 EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
620 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
621 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
622 EXPECT_CALL(*connection_, SendBlocked(stream2->id()));
623 EXPECT_CALL(*connection_, SendBlocked(0));
624 stream2->SendBody(body, false);
625 EXPECT_TRUE(stream2->flow_controller()->IsBlocked());
626 EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
627 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
629 // The handshake message will call OnCanWrite, so the stream can resume
630 // writing.
631 EXPECT_CALL(*stream2, OnCanWrite());
632 // Now complete the crypto handshake, resulting in an increased flow control
633 // send window.
634 CryptoHandshakeMessage msg;
635 session_.GetCryptoStream()->OnHandshakeMessage(msg);
637 // Stream is now unblocked.
638 EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
639 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
640 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
643 TEST_P(QuicSessionTest, HandshakeUnblocksFlowControlBlockedCryptoStream) {
644 // Test that if the crypto stream is flow control blocked, then if the SHLO
645 // contains a larger send window offset, the stream becomes unblocked.
646 session_.set_writev_consumes_all_data(true);
647 TestCryptoStream* crypto_stream = session_.GetCryptoStream();
648 EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
649 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
650 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
651 QuicHeadersStream* headers_stream =
652 QuicSessionPeer::GetHeadersStream(&session_);
653 EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
654 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
655 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
656 // Write until the crypto stream is flow control blocked.
657 EXPECT_CALL(*connection_, SendBlocked(kCryptoStreamId));
658 int i = 0;
659 while (!crypto_stream->flow_controller()->IsBlocked() && i < 1000) {
660 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
661 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
662 QuicConfig config;
663 CryptoHandshakeMessage crypto_message;
664 config.ToHandshakeMessage(&crypto_message);
665 crypto_stream->SendHandshakeMessage(crypto_message);
666 ++i;
668 EXPECT_TRUE(crypto_stream->flow_controller()->IsBlocked());
669 EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
670 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
671 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
672 EXPECT_FALSE(session_.HasDataToWrite());
673 EXPECT_TRUE(crypto_stream->HasBufferedData());
675 // The handshake message will call OnCanWrite, so the stream can
676 // resume writing.
677 EXPECT_CALL(*crypto_stream, OnCanWrite());
678 // Now complete the crypto handshake, resulting in an increased flow control
679 // send window.
680 CryptoHandshakeMessage msg;
681 session_.GetCryptoStream()->OnHandshakeMessage(msg);
683 // Stream is now unblocked and will no longer have buffered data.
684 EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
685 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
686 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
689 TEST_P(QuicSessionTest, HandshakeUnblocksFlowControlBlockedHeadersStream) {
690 // Test that if the header stream is flow control blocked, then if the SHLO
691 // contains a larger send window offset, the stream becomes unblocked.
692 session_.set_writev_consumes_all_data(true);
693 TestCryptoStream* crypto_stream = session_.GetCryptoStream();
694 EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
695 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
696 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
697 QuicHeadersStream* headers_stream =
698 QuicSessionPeer::GetHeadersStream(&session_);
699 EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
700 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
701 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
702 QuicStreamId stream_id = 5;
703 // Write until the header stream is flow control blocked.
704 EXPECT_CALL(*connection_, SendBlocked(kHeadersStreamId));
705 SpdyHeaderBlock headers;
706 while (!headers_stream->flow_controller()->IsBlocked() && stream_id < 2000) {
707 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
708 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
709 headers["header"] = base::Uint64ToString(base::RandUint64()) +
710 base::Uint64ToString(base::RandUint64()) +
711 base::Uint64ToString(base::RandUint64());
712 headers_stream->WriteHeaders(stream_id, headers, true, 0, nullptr);
713 stream_id += 2;
715 // Write once more to ensure that the headers stream has buffered data. The
716 // random headers may have exactly filled the flow control window.
717 headers_stream->WriteHeaders(stream_id, headers, true, 0, nullptr);
718 EXPECT_TRUE(headers_stream->HasBufferedData());
720 EXPECT_TRUE(headers_stream->flow_controller()->IsBlocked());
721 EXPECT_FALSE(crypto_stream->flow_controller()->IsBlocked());
722 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
723 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
724 EXPECT_FALSE(session_.HasDataToWrite());
726 // Now complete the crypto handshake, resulting in an increased flow control
727 // send window.
728 CryptoHandshakeMessage msg;
729 session_.GetCryptoStream()->OnHandshakeMessage(msg);
731 // Stream is now unblocked and will no longer have buffered data.
732 EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
733 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
734 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
735 EXPECT_FALSE(headers_stream->HasBufferedData());
738 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingRstOutOfOrder) {
739 // Test that when we receive an out of order stream RST we correctly adjust
740 // our connection level flow control receive window.
741 // On close, the stream should mark as consumed all bytes between the highest
742 // byte consumed so far and the final byte offset from the RST frame.
743 TestStream* stream = session_.CreateOutgoingDataStream();
745 const QuicStreamOffset kByteOffset =
746 1 + kInitialSessionFlowControlWindowForTest / 2;
748 // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
749 EXPECT_CALL(*connection_, SendWindowUpdate(stream->id(), _)).Times(0);
750 // We do expect a connection level WINDOW_UPDATE when the stream is reset.
751 EXPECT_CALL(*connection_,
752 SendWindowUpdate(0, kInitialSessionFlowControlWindowForTest +
753 kByteOffset)).Times(1);
755 EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
756 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
757 kByteOffset);
758 session_.OnRstStream(rst_frame);
759 session_.PostProcessAfterData();
760 EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
763 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingFinAndLocalReset) {
764 // Test the situation where we receive a FIN on a stream, and before we fully
765 // consume all the data from the sequencer buffer we locally RST the stream.
766 // The bytes between highest consumed byte, and the final byte offset that we
767 // determined when the FIN arrived, should be marked as consumed at the
768 // connection level flow controller when the stream is reset.
769 TestStream* stream = session_.CreateOutgoingDataStream();
771 const QuicStreamOffset kByteOffset =
772 kInitialSessionFlowControlWindowForTest / 2;
773 QuicStreamFrame frame(stream->id(), true, kByteOffset, IOVector());
774 vector<QuicStreamFrame> frames;
775 frames.push_back(frame);
776 session_.OnStreamFrames(frames);
777 session_.PostProcessAfterData();
778 EXPECT_TRUE(connection_->connected());
780 EXPECT_EQ(0u, stream->flow_controller()->bytes_consumed());
781 EXPECT_EQ(kByteOffset,
782 stream->flow_controller()->highest_received_byte_offset());
784 // Reset stream locally.
785 EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
786 stream->Reset(QUIC_STREAM_CANCELLED);
787 EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
790 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingFinAfterRst) {
791 // Test that when we RST the stream (and tear down stream state), and then
792 // receive a FIN from the peer, we correctly adjust our connection level flow
793 // control receive window.
795 // Connection starts with some non-zero highest received byte offset,
796 // due to other active streams.
797 const uint64 kInitialConnectionBytesConsumed = 567;
798 const uint64 kInitialConnectionHighestReceivedOffset = 1234;
799 EXPECT_LT(kInitialConnectionBytesConsumed,
800 kInitialConnectionHighestReceivedOffset);
801 session_.flow_controller()->UpdateHighestReceivedOffset(
802 kInitialConnectionHighestReceivedOffset);
803 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
805 // Reset our stream: this results in the stream being closed locally.
806 TestStream* stream = session_.CreateOutgoingDataStream();
807 EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
808 stream->Reset(QUIC_STREAM_CANCELLED);
810 // Now receive a response from the peer with a FIN. We should handle this by
811 // adjusting the connection level flow control receive window to take into
812 // account the total number of bytes sent by the peer.
813 const QuicStreamOffset kByteOffset = 5678;
814 string body = "hello";
815 IOVector data = MakeIOVector(body);
816 QuicStreamFrame frame(stream->id(), true, kByteOffset, data);
817 vector<QuicStreamFrame> frames;
818 frames.push_back(frame);
819 session_.OnStreamFrames(frames);
821 QuicStreamOffset total_stream_bytes_sent_by_peer =
822 kByteOffset + body.length();
823 EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer,
824 session_.flow_controller()->bytes_consumed());
825 EXPECT_EQ(
826 kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer,
827 session_.flow_controller()->highest_received_byte_offset());
830 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingRstAfterRst) {
831 // Test that when we RST the stream (and tear down stream state), and then
832 // receive a RST from the peer, we correctly adjust our connection level flow
833 // control receive window.
835 // Connection starts with some non-zero highest received byte offset,
836 // due to other active streams.
837 const uint64 kInitialConnectionBytesConsumed = 567;
838 const uint64 kInitialConnectionHighestReceivedOffset = 1234;
839 EXPECT_LT(kInitialConnectionBytesConsumed,
840 kInitialConnectionHighestReceivedOffset);
841 session_.flow_controller()->UpdateHighestReceivedOffset(
842 kInitialConnectionHighestReceivedOffset);
843 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
845 // Reset our stream: this results in the stream being closed locally.
846 TestStream* stream = session_.CreateOutgoingDataStream();
847 EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
848 stream->Reset(QUIC_STREAM_CANCELLED);
850 // Now receive a RST from the peer. We should handle this by adjusting the
851 // connection level flow control receive window to take into account the total
852 // number of bytes sent by the peer.
853 const QuicStreamOffset kByteOffset = 5678;
854 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
855 kByteOffset);
856 session_.OnRstStream(rst_frame);
858 EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset,
859 session_.flow_controller()->bytes_consumed());
860 EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset,
861 session_.flow_controller()->highest_received_byte_offset());
864 TEST_P(QuicSessionTest, InvalidStreamFlowControlWindowInHandshake) {
865 // Test that receipt of an invalid (< default) stream flow control window from
866 // the peer results in the connection being torn down.
867 uint32 kInvalidWindow = kMinimumFlowControlSendWindow - 1;
868 QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(),
869 kInvalidWindow);
871 EXPECT_CALL(*connection_,
872 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW));
873 session_.OnConfigNegotiated();
876 TEST_P(QuicSessionTest, InvalidSessionFlowControlWindowInHandshake) {
877 // Test that receipt of an invalid (< default) session flow control window
878 // from the peer results in the connection being torn down.
879 uint32 kInvalidWindow = kMinimumFlowControlSendWindow - 1;
880 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(),
881 kInvalidWindow);
883 EXPECT_CALL(*connection_,
884 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW));
885 session_.OnConfigNegotiated();
888 TEST_P(QuicSessionTest, FlowControlWithInvalidFinalOffset) {
889 // Test that if we receive a stream RST with a highest byte offset that
890 // violates flow control, that we close the connection.
891 const uint64 kLargeOffset = kInitialSessionFlowControlWindowForTest + 1;
892 EXPECT_CALL(*connection_,
893 SendConnectionClose(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA))
894 .Times(2);
896 // Check that stream frame + FIN results in connection close.
897 TestStream* stream = session_.CreateOutgoingDataStream();
898 EXPECT_CALL(*connection_, SendRstStream(stream->id(), _, _));
899 stream->Reset(QUIC_STREAM_CANCELLED);
900 QuicStreamFrame frame(stream->id(), true, kLargeOffset, IOVector());
901 vector<QuicStreamFrame> frames;
902 frames.push_back(frame);
903 session_.OnStreamFrames(frames);
905 // Check that RST results in connection close.
906 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
907 kLargeOffset);
908 session_.OnRstStream(rst_frame);
911 TEST_P(QuicSessionTest, WindowUpdateUnblocksHeadersStream) {
912 // Test that a flow control blocked headers stream gets unblocked on recipt of
913 // a WINDOW_UPDATE frame. Regression test for b/17413860.
915 // Set the headers stream to be flow control blocked.
916 QuicHeadersStream* headers_stream =
917 QuicSessionPeer::GetHeadersStream(&session_);
918 QuicFlowControllerPeer::SetSendWindowOffset(headers_stream->flow_controller(),
920 EXPECT_TRUE(headers_stream->flow_controller()->IsBlocked());
921 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
922 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
924 // Unblock the headers stream by supplying a WINDOW_UPDATE.
925 QuicWindowUpdateFrame window_update_frame(headers_stream->id(),
926 2 * kMinimumFlowControlSendWindow);
927 vector<QuicWindowUpdateFrame> frames;
928 frames.push_back(window_update_frame);
929 session_.OnWindowUpdateFrames(frames);
930 EXPECT_FALSE(headers_stream->flow_controller()->IsBlocked());
931 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
932 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
935 TEST_P(QuicSessionTest, TooManyUnfinishedStreamsCauseConnectionClose) {
936 // If a buggy/malicious peer creates too many streams that are not ended with
937 // a FIN or RST then we send a connection close.
938 EXPECT_CALL(*connection_,
939 SendConnectionClose(QUIC_TOO_MANY_UNFINISHED_STREAMS)).Times(1);
941 const int kMaxStreams = 5;
942 QuicSessionPeer::SetMaxOpenStreams(&session_, kMaxStreams);
944 // Create kMaxStreams + 1 data streams, and close them all without receiving a
945 // FIN or a RST from the client.
946 const int kFirstStreamId = kClientDataStreamId1;
947 const int kFinalStreamId = kClientDataStreamId1 + 2 * kMaxStreams + 1;
948 for (int i = kFirstStreamId; i < kFinalStreamId; i += 2) {
949 QuicStreamFrame data1(i, false, 0, MakeIOVector("HT"));
950 vector<QuicStreamFrame> frames;
951 frames.push_back(data1);
952 session_.OnStreamFrames(frames);
953 EXPECT_EQ(1u, session_.GetNumOpenStreams());
954 EXPECT_CALL(*connection_, SendRstStream(i, _, _));
955 session_.CloseStream(i);
958 // Called after any new data is received by the session, and triggers the call
959 // to close the connection.
960 session_.PostProcessAfterData();
963 } // namespace
964 } // namespace test
965 } // namespace net