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"
10 #include "base/basictypes.h"
11 #include "base/containers/hash_tables.h"
12 #include "net/quic/crypto/crypto_protocol.h"
13 #include "net/quic/quic_crypto_stream.h"
14 #include "net/quic/quic_flags.h"
15 #include "net/quic/quic_protocol.h"
16 #include "net/quic/quic_utils.h"
17 #include "net/quic/reliable_quic_stream.h"
18 #include "net/quic/test_tools/quic_config_peer.h"
19 #include "net/quic/test_tools/quic_connection_peer.h"
20 #include "net/quic/test_tools/quic_data_stream_peer.h"
21 #include "net/quic/test_tools/quic_flow_controller_peer.h"
22 #include "net/quic/test_tools/quic_session_peer.h"
23 #include "net/quic/test_tools/quic_test_utils.h"
24 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
25 #include "net/spdy/spdy_framer.h"
26 #include "net/test/gtest_util.h"
27 #include "testing/gmock/include/gmock/gmock.h"
28 #include "testing/gmock_mutant.h"
29 #include "testing/gtest/include/gtest/gtest.h"
34 using testing::CreateFunctor
;
35 using testing::InSequence
;
36 using testing::Invoke
;
37 using testing::Return
;
38 using testing::StrictMock
;
45 const QuicPriority kHighestPriority
= 0;
46 const QuicPriority kSomeMiddlePriority
= 3;
48 class TestCryptoStream
: public QuicCryptoStream
{
50 explicit TestCryptoStream(QuicSession
* session
)
51 : QuicCryptoStream(session
) {
54 virtual void OnHandshakeMessage(
55 const CryptoHandshakeMessage
& message
) OVERRIDE
{
56 encryption_established_
= true;
57 handshake_confirmed_
= true;
58 CryptoHandshakeMessage msg
;
60 session()->config()->SetInitialFlowControlWindowToSend(
61 kInitialSessionFlowControlWindowForTest
);
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
{
79 explicit TestHeadersStream(QuicSession
* session
)
80 : QuicHeadersStream(session
) {
83 MOCK_METHOD0(OnCanWrite
, void());
86 class TestStream
: public QuicDataStream
{
88 TestStream(QuicStreamId id
, QuicSession
* session
)
89 : QuicDataStream(id
, session
) {
92 using ReliableQuicStream::CloseWriteSide
;
94 virtual uint32
ProcessData(const char* data
, uint32 data_len
) OVERRIDE
{
98 void SendBody(const string
& data
, bool fin
) {
99 WriteOrBufferData(data
, fin
, NULL
);
102 MOCK_METHOD0(OnCanWrite
, void());
105 // Poor man's functor for use as callback in a mock.
106 class StreamBlocker
{
108 StreamBlocker(QuicSession
* session
, QuicStreamId stream_id
)
110 stream_id_(stream_id
) {
113 void MarkWriteBlocked() {
114 session_
->MarkWriteBlocked(stream_id_
, kSomeMiddlePriority
);
118 QuicSession
* const session_
;
119 const QuicStreamId stream_id_
;
122 class TestSession
: public QuicSession
{
124 explicit TestSession(QuicConnection
* connection
)
125 : QuicSession(connection
,
126 DefaultQuicConfig()),
127 crypto_stream_(this),
128 writev_consumes_all_data_(false) {}
130 virtual TestCryptoStream
* GetCryptoStream() OVERRIDE
{
131 return &crypto_stream_
;
134 virtual TestStream
* CreateOutgoingDataStream() OVERRIDE
{
135 TestStream
* stream
= new TestStream(GetNextStreamId(), this);
136 ActivateStream(stream
);
140 virtual TestStream
* CreateIncomingDataStream(QuicStreamId id
) OVERRIDE
{
141 return new TestStream(id
, this);
144 bool IsClosedStream(QuicStreamId id
) {
145 return QuicSession::IsClosedStream(id
);
148 QuicDataStream
* GetIncomingDataStream(QuicStreamId stream_id
) {
149 return QuicSession::GetIncomingDataStream(stream_id
);
152 virtual QuicConsumedData
WritevData(
154 const IOVector
& data
,
155 QuicStreamOffset offset
,
157 FecProtection fec_protection
,
158 QuicAckNotifier::DelegateInterface
* ack_notifier_delegate
) OVERRIDE
{
159 // Always consumes everything.
160 if (writev_consumes_all_data_
) {
161 return QuicConsumedData(data
.TotalBufferSize(), fin
);
163 return QuicSession::WritevData(id
, data
, offset
, fin
, fec_protection
,
164 ack_notifier_delegate
);
168 void set_writev_consumes_all_data(bool val
) {
169 writev_consumes_all_data_
= val
;
172 QuicConsumedData
SendStreamData(QuicStreamId id
) {
173 return WritevData(id
, IOVector(), 0, true, MAY_FEC_PROTECT
, NULL
);
176 using QuicSession::PostProcessAfterData
;
179 StrictMock
<TestCryptoStream
> crypto_stream_
;
181 bool writev_consumes_all_data_
;
184 class QuicSessionTest
: public ::testing::TestWithParam
<QuicVersion
> {
187 : connection_(new MockConnection(true, SupportedVersions(GetParam()))),
188 session_(connection_
) {
189 session_
.config()->SetInitialFlowControlWindowToSend(
190 kInitialSessionFlowControlWindowForTest
);
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";
199 "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
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 ";
224 void CheckClosedStreams() {
225 for (int i
= kCryptoStreamId
; i
< 100; i
++) {
226 if (closed_streams_
.count(i
) == 0) {
227 EXPECT_FALSE(session_
.IsClosedStream(i
)) << " stream id: " << i
;
229 EXPECT_TRUE(session_
.IsClosedStream(i
)) << " stream id: " << i
;
234 void CloseStream(QuicStreamId id
) {
235 session_
.CloseStream(id
);
236 closed_streams_
.insert(id
);
239 QuicVersion
version() const { return connection_
->version(); }
241 MockConnection
* connection_
;
242 TestSession session_
;
243 set
<QuicStreamId
> closed_streams_
;
244 SpdyHeaderBlock headers_
;
247 INSTANTIATE_TEST_CASE_P(Tests
, QuicSessionTest
,
248 ::testing::ValuesIn(QuicSupportedVersions()));
250 TEST_P(QuicSessionTest
, PeerAddress
) {
251 EXPECT_EQ(IPEndPoint(Loopback4(), kTestPort
), session_
.peer_address());
254 TEST_P(QuicSessionTest
, IsCryptoHandshakeConfirmed
) {
255 EXPECT_FALSE(session_
.IsCryptoHandshakeConfirmed());
256 CryptoHandshakeMessage message
;
257 session_
.GetCryptoStream()->OnHandshakeMessage(message
);
258 EXPECT_TRUE(session_
.IsCryptoHandshakeConfirmed());
261 TEST_P(QuicSessionTest
, IsClosedStreamDefault
) {
262 // Ensure that no streams are initially closed.
263 for (int i
= kCryptoStreamId
; i
< 100; i
++) {
264 EXPECT_FALSE(session_
.IsClosedStream(i
)) << "stream id: " << i
;
268 TEST_P(QuicSessionTest
, ImplicitlyCreatedStreams
) {
269 ASSERT_TRUE(session_
.GetIncomingDataStream(7) != NULL
);
270 // Both 3 and 5 should be implicitly created.
271 EXPECT_FALSE(session_
.IsClosedStream(3));
272 EXPECT_FALSE(session_
.IsClosedStream(5));
273 ASSERT_TRUE(session_
.GetIncomingDataStream(5) != NULL
);
274 ASSERT_TRUE(session_
.GetIncomingDataStream(3) != NULL
);
277 TEST_P(QuicSessionTest
, IsClosedStreamLocallyCreated
) {
278 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
279 EXPECT_EQ(2u, stream2
->id());
280 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
281 EXPECT_EQ(4u, stream4
->id());
283 CheckClosedStreams();
285 CheckClosedStreams();
287 CheckClosedStreams();
290 TEST_P(QuicSessionTest
, IsClosedStreamPeerCreated
) {
291 QuicStreamId stream_id1
= kClientDataStreamId1
;
292 QuicStreamId stream_id2
= kClientDataStreamId2
;
293 QuicDataStream
* stream1
= session_
.GetIncomingDataStream(stream_id1
);
294 QuicDataStreamPeer::SetHeadersDecompressed(stream1
, true);
295 QuicDataStream
* stream2
= session_
.GetIncomingDataStream(stream_id2
);
296 QuicDataStreamPeer::SetHeadersDecompressed(stream2
, true);
298 CheckClosedStreams();
299 CloseStream(stream_id1
);
300 CheckClosedStreams();
301 CloseStream(stream_id2
);
302 // Create a stream explicitly, and another implicitly.
303 QuicDataStream
* stream3
= session_
.GetIncomingDataStream(stream_id2
+ 4);
304 QuicDataStreamPeer::SetHeadersDecompressed(stream3
, true);
305 CheckClosedStreams();
306 // Close one, but make sure the other is still not closed
307 CloseStream(stream3
->id());
308 CheckClosedStreams();
311 TEST_P(QuicSessionTest
, StreamIdTooLarge
) {
312 QuicStreamId stream_id
= kClientDataStreamId1
;
313 session_
.GetIncomingDataStream(stream_id
);
314 EXPECT_CALL(*connection_
, SendConnectionClose(QUIC_INVALID_STREAM_ID
));
315 session_
.GetIncomingDataStream(stream_id
+ kMaxStreamIdDelta
+ 2);
318 TEST_P(QuicSessionTest
, DecompressionError
) {
319 QuicHeadersStream
* stream
= QuicSessionPeer::GetHeadersStream(&session_
);
320 const unsigned char data
[] = {
321 0x80, 0x03, 0x00, 0x01, // SPDY/3 SYN_STREAM frame
322 0x00, 0x00, 0x00, 0x25, // flags/length
323 0x00, 0x00, 0x00, 0x05, // stream id
324 0x00, 0x00, 0x00, 0x00, // associated stream id
326 'a', 'b', 'c', 'd' // invalid compressed data
328 EXPECT_CALL(*connection_
,
329 SendConnectionCloseWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA
,
330 "SPDY framing error."));
331 stream
->ProcessRawData(reinterpret_cast<const char*>(data
),
335 TEST_P(QuicSessionTest
, DebugDFatalIfMarkingClosedStreamWriteBlocked
) {
336 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
338 stream2
->Reset(QUIC_BAD_APPLICATION_PAYLOAD
);
339 // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL.
341 QuicStreamId kClosedStreamId = stream2->id();
343 session_.MarkWriteBlocked(kClosedStreamId, kSomeMiddlePriority),
344 "Marking unknown stream 2 blocked.");
348 TEST_P(QuicSessionTest
, DebugDFatalIfMarkWriteBlockedCalledWithWrongPriority
) {
349 const QuicPriority kDifferentPriority
= 0;
351 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
352 EXPECT_NE(kDifferentPriority
, stream2
->EffectivePriority());
353 // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL.
356 session_.MarkWriteBlocked(stream2->id(), kDifferentPriority),
357 "Priorities do not match. Got: 0 Expected: 3");
361 TEST_P(QuicSessionTest
, OnCanWrite
) {
362 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
363 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
364 TestStream
* stream6
= session_
.CreateOutgoingDataStream();
366 session_
.MarkWriteBlocked(stream2
->id(), kSomeMiddlePriority
);
367 session_
.MarkWriteBlocked(stream6
->id(), kSomeMiddlePriority
);
368 session_
.MarkWriteBlocked(stream4
->id(), kSomeMiddlePriority
);
371 StreamBlocker
stream2_blocker(&session_
, stream2
->id());
372 // Reregister, to test the loop limit.
373 EXPECT_CALL(*stream2
, OnCanWrite())
374 .WillOnce(Invoke(&stream2_blocker
, &StreamBlocker::MarkWriteBlocked
));
375 EXPECT_CALL(*stream6
, OnCanWrite());
376 EXPECT_CALL(*stream4
, OnCanWrite());
377 session_
.OnCanWrite();
378 EXPECT_TRUE(session_
.WillingAndAbleToWrite());
381 TEST_P(QuicSessionTest
, OnCanWriteBundlesStreams
) {
382 // Drive congestion control manually.
383 MockSendAlgorithm
* send_algorithm
= new StrictMock
<MockSendAlgorithm
>;
384 QuicConnectionPeer::SetSendAlgorithm(session_
.connection(), send_algorithm
);
386 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
387 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
388 TestStream
* stream6
= session_
.CreateOutgoingDataStream();
390 session_
.MarkWriteBlocked(stream2
->id(), kSomeMiddlePriority
);
391 session_
.MarkWriteBlocked(stream6
->id(), kSomeMiddlePriority
);
392 session_
.MarkWriteBlocked(stream4
->id(), kSomeMiddlePriority
);
394 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillRepeatedly(
395 Return(QuicTime::Delta::Zero()));
396 EXPECT_CALL(*send_algorithm
, GetCongestionWindow())
397 .WillOnce(Return(kMaxPacketSize
* 10));
398 EXPECT_CALL(*stream2
, OnCanWrite())
399 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
400 &session_
, &TestSession::SendStreamData
, stream2
->id()))));
401 EXPECT_CALL(*stream4
, OnCanWrite())
402 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
403 &session_
, &TestSession::SendStreamData
, stream4
->id()))));
404 EXPECT_CALL(*stream6
, OnCanWrite())
405 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
406 &session_
, &TestSession::SendStreamData
, stream6
->id()))));
408 // Expect that we only send one packet, the writes from different streams
409 // should be bundled together.
410 MockPacketWriter
* writer
=
411 static_cast<MockPacketWriter
*>(
412 QuicConnectionPeer::GetWriter(session_
.connection()));
413 EXPECT_CALL(*writer
, WritePacket(_
, _
, _
, _
)).WillOnce(
414 Return(WriteResult(WRITE_STATUS_OK
, 0)));
415 EXPECT_CALL(*send_algorithm
, OnPacketSent(_
, _
, _
, _
, _
)).Times(1);
416 session_
.OnCanWrite();
417 EXPECT_FALSE(session_
.WillingAndAbleToWrite());
420 TEST_P(QuicSessionTest
, OnCanWriteCongestionControlBlocks
) {
423 // Drive congestion control manually.
424 MockSendAlgorithm
* send_algorithm
= new StrictMock
<MockSendAlgorithm
>;
425 QuicConnectionPeer::SetSendAlgorithm(session_
.connection(), send_algorithm
);
427 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
428 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
429 TestStream
* stream6
= session_
.CreateOutgoingDataStream();
431 session_
.MarkWriteBlocked(stream2
->id(), kSomeMiddlePriority
);
432 session_
.MarkWriteBlocked(stream6
->id(), kSomeMiddlePriority
);
433 session_
.MarkWriteBlocked(stream4
->id(), kSomeMiddlePriority
);
435 StreamBlocker
stream2_blocker(&session_
, stream2
->id());
436 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillOnce(Return(
437 QuicTime::Delta::Zero()));
438 EXPECT_CALL(*stream2
, OnCanWrite());
439 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillOnce(Return(
440 QuicTime::Delta::Zero()));
441 EXPECT_CALL(*stream6
, OnCanWrite());
442 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillOnce(Return(
443 QuicTime::Delta::Infinite()));
444 // stream4->OnCanWrite is not called.
446 session_
.OnCanWrite();
447 EXPECT_TRUE(session_
.WillingAndAbleToWrite());
449 // Still congestion-control blocked.
450 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillOnce(Return(
451 QuicTime::Delta::Infinite()));
452 session_
.OnCanWrite();
453 EXPECT_TRUE(session_
.WillingAndAbleToWrite());
455 // stream4->OnCanWrite is called once the connection stops being
456 // congestion-control blocked.
457 EXPECT_CALL(*send_algorithm
, TimeUntilSend(_
, _
, _
)).WillOnce(Return(
458 QuicTime::Delta::Zero()));
459 EXPECT_CALL(*stream4
, OnCanWrite());
460 session_
.OnCanWrite();
461 EXPECT_FALSE(session_
.WillingAndAbleToWrite());
464 TEST_P(QuicSessionTest
, BufferedHandshake
) {
465 EXPECT_FALSE(session_
.HasPendingHandshake()); // Default value.
467 // Test that blocking other streams does not change our status.
468 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
469 StreamBlocker
stream2_blocker(&session_
, stream2
->id());
470 stream2_blocker
.MarkWriteBlocked();
471 EXPECT_FALSE(session_
.HasPendingHandshake());
473 TestStream
* stream3
= session_
.CreateOutgoingDataStream();
474 StreamBlocker
stream3_blocker(&session_
, stream3
->id());
475 stream3_blocker
.MarkWriteBlocked();
476 EXPECT_FALSE(session_
.HasPendingHandshake());
478 // Blocking (due to buffering of) the Crypto stream is detected.
479 session_
.MarkWriteBlocked(kCryptoStreamId
, kHighestPriority
);
480 EXPECT_TRUE(session_
.HasPendingHandshake());
482 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
483 StreamBlocker
stream4_blocker(&session_
, stream4
->id());
484 stream4_blocker
.MarkWriteBlocked();
485 EXPECT_TRUE(session_
.HasPendingHandshake());
488 // Force most streams to re-register, which is common scenario when we block
489 // the Crypto stream, and only the crypto stream can "really" write.
491 // Due to prioritization, we *should* be asked to write the crypto stream
493 // Don't re-register the crypto stream (which signals complete writing).
494 TestCryptoStream
* crypto_stream
= session_
.GetCryptoStream();
495 EXPECT_CALL(*crypto_stream
, OnCanWrite());
497 // Re-register all other streams, to show they weren't able to proceed.
498 EXPECT_CALL(*stream2
, OnCanWrite())
499 .WillOnce(Invoke(&stream2_blocker
, &StreamBlocker::MarkWriteBlocked
));
500 EXPECT_CALL(*stream3
, OnCanWrite())
501 .WillOnce(Invoke(&stream3_blocker
, &StreamBlocker::MarkWriteBlocked
));
502 EXPECT_CALL(*stream4
, OnCanWrite())
503 .WillOnce(Invoke(&stream4_blocker
, &StreamBlocker::MarkWriteBlocked
));
505 session_
.OnCanWrite();
506 EXPECT_TRUE(session_
.WillingAndAbleToWrite());
507 EXPECT_FALSE(session_
.HasPendingHandshake()); // Crypto stream wrote.
510 TEST_P(QuicSessionTest
, OnCanWriteWithClosedStream
) {
511 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
512 TestStream
* stream4
= session_
.CreateOutgoingDataStream();
513 TestStream
* stream6
= session_
.CreateOutgoingDataStream();
515 session_
.MarkWriteBlocked(stream2
->id(), kSomeMiddlePriority
);
516 session_
.MarkWriteBlocked(stream6
->id(), kSomeMiddlePriority
);
517 session_
.MarkWriteBlocked(stream4
->id(), kSomeMiddlePriority
);
518 CloseStream(stream6
->id());
521 EXPECT_CALL(*stream2
, OnCanWrite());
522 EXPECT_CALL(*stream4
, OnCanWrite());
523 session_
.OnCanWrite();
524 EXPECT_FALSE(session_
.WillingAndAbleToWrite());
527 TEST_P(QuicSessionTest
, OnCanWriteLimitsNumWritesIfFlowControlBlocked
) {
528 if (version() < QUIC_VERSION_19
) {
532 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
534 // Ensure connection level flow control blockage.
535 QuicFlowControllerPeer::SetSendWindowOffset(session_
.flow_controller(), 0);
536 EXPECT_TRUE(session_
.flow_controller()->IsBlocked());
538 // Mark the crypto and headers streams as write blocked, we expect them to be
539 // allowed to write later.
540 session_
.MarkWriteBlocked(kCryptoStreamId
, kHighestPriority
);
541 session_
.MarkWriteBlocked(kHeadersStreamId
, kHighestPriority
);
543 // Create a data stream, and although it is write blocked we never expect it
544 // to be allowed to write as we are connection level flow control blocked.
545 TestStream
* stream
= session_
.CreateOutgoingDataStream();
546 session_
.MarkWriteBlocked(stream
->id(), kSomeMiddlePriority
);
547 EXPECT_CALL(*stream
, OnCanWrite()).Times(0);
549 // The crypto and headers streams should be called even though we are
550 // connection flow control blocked.
551 TestCryptoStream
* crypto_stream
= session_
.GetCryptoStream();
552 EXPECT_CALL(*crypto_stream
, OnCanWrite()).Times(1);
553 TestHeadersStream
* headers_stream
= new TestHeadersStream(&session_
);
554 QuicSessionPeer::SetHeadersStream(&session_
, headers_stream
);
555 EXPECT_CALL(*headers_stream
, OnCanWrite()).Times(1);
557 session_
.OnCanWrite();
558 EXPECT_FALSE(session_
.WillingAndAbleToWrite());
561 TEST_P(QuicSessionTest
, SendGoAway
) {
562 EXPECT_CALL(*connection_
,
563 SendGoAway(QUIC_PEER_GOING_AWAY
, 0u, "Going Away."));
564 session_
.SendGoAway(QUIC_PEER_GOING_AWAY
, "Going Away.");
565 EXPECT_TRUE(session_
.goaway_sent());
567 EXPECT_CALL(*connection_
,
568 SendRstStream(3u, QUIC_STREAM_PEER_GOING_AWAY
, 0)).Times(0);
569 EXPECT_TRUE(session_
.GetIncomingDataStream(3u));
572 TEST_P(QuicSessionTest
, DoNotSendGoAwayTwice
) {
573 EXPECT_CALL(*connection_
,
574 SendGoAway(QUIC_PEER_GOING_AWAY
, 0u, "Going Away.")).Times(1);
575 session_
.SendGoAway(QUIC_PEER_GOING_AWAY
, "Going Away.");
576 EXPECT_TRUE(session_
.goaway_sent());
577 session_
.SendGoAway(QUIC_PEER_GOING_AWAY
, "Going Away.");
580 TEST_P(QuicSessionTest
, IncreasedTimeoutAfterCryptoHandshake
) {
581 EXPECT_EQ(kDefaultInitialTimeoutSecs
,
582 QuicConnectionPeer::GetNetworkTimeout(connection_
).ToSeconds());
583 CryptoHandshakeMessage msg
;
584 session_
.GetCryptoStream()->OnHandshakeMessage(msg
);
585 EXPECT_EQ(kDefaultTimeoutSecs
,
586 QuicConnectionPeer::GetNetworkTimeout(connection_
).ToSeconds());
589 TEST_P(QuicSessionTest
, RstStreamBeforeHeadersDecompressed
) {
590 // Send two bytes of payload.
591 QuicStreamFrame
data1(kClientDataStreamId1
, false, 0, MakeIOVector("HT"));
592 vector
<QuicStreamFrame
> frames
;
593 frames
.push_back(data1
);
594 session_
.OnStreamFrames(frames
);
595 EXPECT_EQ(1u, session_
.GetNumOpenStreams());
597 QuicRstStreamFrame
rst1(kClientDataStreamId1
, QUIC_STREAM_NO_ERROR
, 0);
598 session_
.OnRstStream(rst1
);
599 EXPECT_EQ(0u, session_
.GetNumOpenStreams());
600 // Connection should remain alive.
601 EXPECT_TRUE(connection_
->connected());
604 TEST_P(QuicSessionTest
, MultipleRstStreamsCauseSingleConnectionClose
) {
605 // If multiple invalid reset stream frames arrive in a single packet, this
606 // should trigger a connection close. However there is no need to send
607 // multiple connection close frames.
609 // Create valid stream.
610 QuicStreamFrame
data1(kClientDataStreamId1
, false, 0, MakeIOVector("HT"));
611 vector
<QuicStreamFrame
> frames
;
612 frames
.push_back(data1
);
613 session_
.OnStreamFrames(frames
);
614 EXPECT_EQ(1u, session_
.GetNumOpenStreams());
616 // Process first invalid stream reset, resulting in the connection being
618 EXPECT_CALL(*connection_
, SendConnectionClose(QUIC_INVALID_STREAM_ID
))
620 QuicStreamId kLargeInvalidStreamId
= 99999999;
621 QuicRstStreamFrame
rst1(kLargeInvalidStreamId
, QUIC_STREAM_NO_ERROR
, 0);
622 session_
.OnRstStream(rst1
);
623 QuicConnectionPeer::CloseConnection(connection_
);
625 // Processing of second invalid stream reset should not result in the
626 // connection being closed for a second time.
627 QuicRstStreamFrame
rst2(kLargeInvalidStreamId
, QUIC_STREAM_NO_ERROR
, 0);
628 session_
.OnRstStream(rst2
);
631 TEST_P(QuicSessionTest
, HandshakeUnblocksFlowControlBlockedStream
) {
632 // Test that if a stream is flow control blocked, then on receipt of the SHLO
633 // containing a suitable send window offset, the stream becomes unblocked.
634 if (version() <= QUIC_VERSION_16
) {
638 // Ensure that Writev consumes all the data it is given (simulate no socket
640 session_
.set_writev_consumes_all_data(true);
642 // Create a stream, and send enough data to make it flow control blocked.
643 TestStream
* stream2
= session_
.CreateOutgoingDataStream();
644 string
body(kDefaultFlowControlSendWindow
, '.');
645 EXPECT_FALSE(stream2
->flow_controller()->IsBlocked());
646 stream2
->SendBody(body
, false);
647 EXPECT_TRUE(stream2
->flow_controller()->IsBlocked());
649 // Now complete the crypto handshake, resulting in an increased flow control
651 CryptoHandshakeMessage msg
;
652 session_
.GetCryptoStream()->OnHandshakeMessage(msg
);
654 // Stream is now unblocked.
655 EXPECT_FALSE(stream2
->flow_controller()->IsBlocked());
658 TEST_P(QuicSessionTest
, InvalidFlowControlWindowInHandshake
) {
659 // TODO(rjshade): Remove this test when removing QUIC_VERSION_19.
660 // Test that receipt of an invalid (< default) flow control window from
661 // the peer results in the connection being torn down.
662 if (version() <= QUIC_VERSION_16
|| version() > QUIC_VERSION_19
) {
666 uint32 kInvalidWindow
= kDefaultFlowControlSendWindow
- 1;
667 QuicConfigPeer::SetReceivedInitialFlowControlWindow(session_
.config(),
670 EXPECT_CALL(*connection_
,
671 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW
)).Times(2);
672 session_
.OnConfigNegotiated();
675 TEST_P(QuicSessionTest
, InvalidStreamFlowControlWindowInHandshake
) {
676 // Test that receipt of an invalid (< default) stream flow control window from
677 // the peer results in the connection being torn down.
678 if (version() <= QUIC_VERSION_19
) {
682 uint32 kInvalidWindow
= kDefaultFlowControlSendWindow
- 1;
683 QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_
.config(),
686 EXPECT_CALL(*connection_
,
687 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW
));
688 session_
.OnConfigNegotiated();
691 TEST_P(QuicSessionTest
, InvalidSessionFlowControlWindowInHandshake
) {
692 // Test that receipt of an invalid (< default) session flow control window
693 // from the peer results in the connection being torn down.
694 if (version() <= QUIC_VERSION_19
) {
698 uint32 kInvalidWindow
= kDefaultFlowControlSendWindow
- 1;
699 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_
.config(),
702 EXPECT_CALL(*connection_
,
703 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW
));
704 session_
.OnConfigNegotiated();
707 TEST_P(QuicSessionTest
, ConnectionFlowControlAccountingRstOutOfOrder
) {
708 if (version() < QUIC_VERSION_19
) {
712 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
714 // Test that when we receive an out of order stream RST we correctly adjust
715 // our connection level flow control receive window.
716 // On close, the stream should mark as consumed all bytes between the highest
717 // byte consumed so far and the final byte offset from the RST frame.
718 TestStream
* stream
= session_
.CreateOutgoingDataStream();
720 const QuicStreamOffset kByteOffset
=
721 1 + kInitialSessionFlowControlWindowForTest
/ 2;
723 // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
724 EXPECT_CALL(*connection_
, SendWindowUpdate(stream
->id(), _
)).Times(0);
725 // We do expect a connection level WINDOW_UPDATE when the stream is reset.
726 EXPECT_CALL(*connection_
,
727 SendWindowUpdate(0, kInitialSessionFlowControlWindowForTest
+
728 kByteOffset
)).Times(1);
730 QuicRstStreamFrame
rst_frame(stream
->id(), QUIC_STREAM_CANCELLED
,
732 session_
.OnRstStream(rst_frame
);
733 session_
.PostProcessAfterData();
734 EXPECT_EQ(kByteOffset
, session_
.flow_controller()->bytes_consumed());
737 TEST_P(QuicSessionTest
, ConnectionFlowControlAccountingFinAndLocalReset
) {
738 if (version() < QUIC_VERSION_19
) {
742 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
744 // Test the situation where we receive a FIN on a stream, and before we fully
745 // consume all the data from the sequencer buffer we locally RST the stream.
746 // The bytes between highest consumed byte, and the final byte offset that we
747 // determined when the FIN arrived, should be marked as consumed at the
748 // connection level flow controller when the stream is reset.
749 TestStream
* stream
= session_
.CreateOutgoingDataStream();
751 const QuicStreamOffset kByteOffset
=
752 1 + kInitialSessionFlowControlWindowForTest
/ 2;
753 QuicStreamFrame
frame(stream
->id(), true, kByteOffset
, IOVector());
754 vector
<QuicStreamFrame
> frames
;
755 frames
.push_back(frame
);
756 session_
.OnStreamFrames(frames
);
757 session_
.PostProcessAfterData();
759 EXPECT_EQ(0u, stream
->flow_controller()->bytes_consumed());
760 EXPECT_EQ(kByteOffset
,
761 stream
->flow_controller()->highest_received_byte_offset());
763 // We only expect to see a connection WINDOW_UPDATE when talking
764 // QUIC_VERSION_19, as in this case both stream and session flow control
765 // windows are the same size. In later versions we will not see a connection
766 // level WINDOW_UPDATE when exhausting a stream, as the stream flow control
767 // limit is much lower than the connection flow control limit.
768 if (version() == QUIC_VERSION_19
) {
769 // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
770 EXPECT_CALL(*connection_
, SendWindowUpdate(stream
->id(), _
)).Times(0);
771 // We do expect a connection level WINDOW_UPDATE when the stream is reset.
772 EXPECT_CALL(*connection_
,
773 SendWindowUpdate(0, kInitialSessionFlowControlWindowForTest
+
774 kByteOffset
)).Times(1);
777 // Reset stream locally.
778 stream
->Reset(QUIC_STREAM_CANCELLED
);
779 EXPECT_EQ(kByteOffset
, session_
.flow_controller()->bytes_consumed());
782 TEST_P(QuicSessionTest
, ConnectionFlowControlAccountingFinAfterRst
) {
783 // Test that when we RST the stream (and tear down stream state), and then
784 // receive a FIN from the peer, we correctly adjust our connection level flow
785 // control receive window.
786 if (version() < QUIC_VERSION_19
) {
790 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
792 // Connection starts with some non-zero highest received byte offset,
793 // due to other active streams.
794 const uint64 kInitialConnectionBytesConsumed
= 567;
795 const uint64 kInitialConnectionHighestReceivedOffset
= 1234;
796 EXPECT_LT(kInitialConnectionBytesConsumed
,
797 kInitialConnectionHighestReceivedOffset
);
798 session_
.flow_controller()->UpdateHighestReceivedOffset(
799 kInitialConnectionHighestReceivedOffset
);
800 session_
.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed
);
802 // Reset our stream: this results in the stream being closed locally.
803 TestStream
* stream
= session_
.CreateOutgoingDataStream();
804 stream
->Reset(QUIC_STREAM_CANCELLED
);
806 // Now receive a response from the peer with a FIN. We should handle this by
807 // adjusting the connection level flow control receive window to take into
808 // account the total number of bytes sent by the peer.
809 const QuicStreamOffset kByteOffset
= 5678;
810 string body
= "hello";
811 IOVector data
= MakeIOVector(body
);
812 QuicStreamFrame
frame(stream
->id(), true, kByteOffset
, data
);
813 vector
<QuicStreamFrame
> frames
;
814 frames
.push_back(frame
);
815 session_
.OnStreamFrames(frames
);
817 QuicStreamOffset total_stream_bytes_sent_by_peer
=
818 kByteOffset
+ body
.length();
819 EXPECT_EQ(kInitialConnectionBytesConsumed
+ total_stream_bytes_sent_by_peer
,
820 session_
.flow_controller()->bytes_consumed());
822 kInitialConnectionHighestReceivedOffset
+ total_stream_bytes_sent_by_peer
,
823 session_
.flow_controller()->highest_received_byte_offset());
826 TEST_P(QuicSessionTest
, ConnectionFlowControlAccountingRstAfterRst
) {
827 // Test that when we RST the stream (and tear down stream state), and then
828 // receive a RST from the peer, we correctly adjust our connection level flow
829 // control receive window.
830 if (version() < QUIC_VERSION_19
) {
834 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
836 // Connection starts with some non-zero highest received byte offset,
837 // due to other active streams.
838 const uint64 kInitialConnectionBytesConsumed
= 567;
839 const uint64 kInitialConnectionHighestReceivedOffset
= 1234;
840 EXPECT_LT(kInitialConnectionBytesConsumed
,
841 kInitialConnectionHighestReceivedOffset
);
842 session_
.flow_controller()->UpdateHighestReceivedOffset(
843 kInitialConnectionHighestReceivedOffset
);
844 session_
.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed
);
846 // Reset our stream: this results in the stream being closed locally.
847 TestStream
* stream
= session_
.CreateOutgoingDataStream();
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
,
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
, FlowControlWithInvalidFinalOffset
) {
865 // Test that if we receive a stream RST with a highest byte offset that
866 // violates flow control, that we close the connection.
867 if (version() <= QUIC_VERSION_16
) {
870 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
873 const uint64 kLargeOffset
= kInitialSessionFlowControlWindowForTest
+ 1;
874 EXPECT_CALL(*connection_
,
875 SendConnectionClose(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA
))
878 // Check that stream frame + FIN results in connection close.
879 TestStream
* stream
= session_
.CreateOutgoingDataStream();
880 stream
->Reset(QUIC_STREAM_CANCELLED
);
881 QuicStreamFrame
frame(stream
->id(), true, kLargeOffset
, IOVector());
882 vector
<QuicStreamFrame
> frames
;
883 frames
.push_back(frame
);
884 session_
.OnStreamFrames(frames
);
886 // Check that RST results in connection close.
887 QuicRstStreamFrame
rst_frame(stream
->id(), QUIC_STREAM_CANCELLED
,
889 session_
.OnRstStream(rst_frame
);
892 TEST_P(QuicSessionTest
, VersionNegotiationDisablesFlowControl
) {
893 if (version() < QUIC_VERSION_19
) {
897 ValueRestore
<bool> old_flag(&FLAGS_enable_quic_connection_flow_control_2
,
899 // Test that after successful version negotiation, flow control is disabled
900 // appropriately at both the connection and stream level.
902 // Initially both stream and connection flow control are enabled.
903 TestStream
* stream
= session_
.CreateOutgoingDataStream();
904 EXPECT_TRUE(stream
->flow_controller()->IsEnabled());
905 EXPECT_TRUE(session_
.flow_controller()->IsEnabled());
907 // Version 18 implies that stream flow control is enabled, but connection
908 // level is disabled.
909 session_
.OnSuccessfulVersionNegotiation(QUIC_VERSION_18
);
910 EXPECT_FALSE(session_
.flow_controller()->IsEnabled());
911 EXPECT_TRUE(stream
->flow_controller()->IsEnabled());
913 // Version 16 means all flow control is disabled.
914 session_
.OnSuccessfulVersionNegotiation(QUIC_VERSION_16
);
915 EXPECT_FALSE(session_
.flow_controller()->IsEnabled());
916 EXPECT_FALSE(stream
->flow_controller()->IsEnabled());