Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / quic / quic_session_test.cc
blob787f6242f243f9ea1937be1e56062953094f5c98
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>
8 #include <vector>
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"
31 using base::hash_map;
32 using std::set;
33 using std::vector;
34 using testing::CreateFunctor;
35 using testing::InSequence;
36 using testing::Invoke;
37 using testing::Return;
38 using testing::StrictMock;
39 using testing::_;
41 namespace net {
42 namespace test {
43 namespace {
45 const QuicPriority kHighestPriority = 0;
46 const QuicPriority kSomeMiddlePriority = 3;
48 class TestCryptoStream : public QuicCryptoStream {
49 public:
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;
59 string error_details;
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 {
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 virtual 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, NULL);
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,
126 DefaultQuicConfig()),
127 crypto_stream_(this),
128 writev_consumes_all_data_(false) {
129 InitializeSession();
132 virtual TestCryptoStream* GetCryptoStream() OVERRIDE {
133 return &crypto_stream_;
136 virtual TestStream* CreateOutgoingDataStream() OVERRIDE {
137 TestStream* stream = new TestStream(GetNextStreamId(), this);
138 ActivateStream(stream);
139 return stream;
142 virtual TestStream* CreateIncomingDataStream(QuicStreamId id) OVERRIDE {
143 return new TestStream(id, this);
146 bool IsClosedStream(QuicStreamId id) {
147 return QuicSession::IsClosedStream(id);
150 QuicDataStream* GetIncomingDataStream(QuicStreamId stream_id) {
151 return QuicSession::GetIncomingDataStream(stream_id);
154 virtual QuicConsumedData WritevData(
155 QuicStreamId id,
156 const IOVector& data,
157 QuicStreamOffset offset,
158 bool fin,
159 FecProtection fec_protection,
160 QuicAckNotifier::DelegateInterface* ack_notifier_delegate) OVERRIDE {
161 // Always consumes everything.
162 if (writev_consumes_all_data_) {
163 return QuicConsumedData(data.TotalBufferSize(), fin);
164 } else {
165 return QuicSession::WritevData(id, data, offset, fin, fec_protection,
166 ack_notifier_delegate);
170 void set_writev_consumes_all_data(bool val) {
171 writev_consumes_all_data_ = val;
174 QuicConsumedData SendStreamData(QuicStreamId id) {
175 return WritevData(id, IOVector(), 0, true, MAY_FEC_PROTECT, NULL);
178 using QuicSession::PostProcessAfterData;
180 private:
181 StrictMock<TestCryptoStream> crypto_stream_;
183 bool writev_consumes_all_data_;
186 class QuicSessionTest : public ::testing::TestWithParam<QuicVersion> {
187 protected:
188 QuicSessionTest()
189 : connection_(new MockConnection(true, SupportedVersions(GetParam()))),
190 session_(connection_) {
191 session_.config()->SetInitialFlowControlWindowToSend(
192 kInitialSessionFlowControlWindowForTest);
193 session_.config()->SetInitialStreamFlowControlWindowToSend(
194 kInitialStreamFlowControlWindowForTest);
195 session_.config()->SetInitialSessionFlowControlWindowToSend(
196 kInitialSessionFlowControlWindowForTest);
197 headers_[":host"] = "www.google.com";
198 headers_[":path"] = "/index.hml";
199 headers_[":scheme"] = "http";
200 headers_["cookie"] =
201 "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
202 "__utmc=160408618; "
203 "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX"
204 "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX"
205 "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT"
206 "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0"
207 "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh"
208 "1zFMi5vzcns38-8_Sns; "
209 "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-"
210 "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339"
211 "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c"
212 "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%"
213 "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4"
214 "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1"
215 "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP"
216 "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6"
217 "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b"
218 "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6"
219 "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG"
220 "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk"
221 "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn"
222 "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr"
223 "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo ";
226 void CheckClosedStreams() {
227 for (int i = kCryptoStreamId; i < 100; i++) {
228 if (closed_streams_.count(i) == 0) {
229 EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
230 } else {
231 EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
236 void CloseStream(QuicStreamId id) {
237 session_.CloseStream(id);
238 closed_streams_.insert(id);
241 QuicVersion version() const { return connection_->version(); }
243 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) != NULL);
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) != NULL);
276 ASSERT_TRUE(session_.GetIncomingDataStream(3) != NULL);
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, DecompressionError) {
321 QuicHeadersStream* stream = QuicSessionPeer::GetHeadersStream(&session_);
322 const unsigned char data[] = {
323 0x80, 0x03, 0x00, 0x01, // SPDY/3 SYN_STREAM frame
324 0x00, 0x00, 0x00, 0x25, // flags/length
325 0x00, 0x00, 0x00, 0x05, // stream id
326 0x00, 0x00, 0x00, 0x00, // associated stream id
327 0x00, 0x00,
328 'a', 'b', 'c', 'd' // invalid compressed data
330 EXPECT_CALL(*connection_,
331 SendConnectionCloseWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA,
332 "SPDY framing error."));
333 stream->ProcessRawData(reinterpret_cast<const char*>(data),
334 arraysize(data));
337 TEST_P(QuicSessionTest, DebugDFatalIfMarkingClosedStreamWriteBlocked) {
338 TestStream* stream2 = session_.CreateOutgoingDataStream();
339 // Close the stream.
340 stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
341 // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL.
343 QuicStreamId kClosedStreamId = stream2->id();
344 EXPECT_DEBUG_DFATAL(
345 session_.MarkWriteBlocked(kClosedStreamId, kSomeMiddlePriority),
346 "Marking unknown stream 2 blocked.");
350 TEST_P(QuicSessionTest, DebugDFatalIfMarkWriteBlockedCalledWithWrongPriority) {
351 const QuicPriority kDifferentPriority = 0;
353 TestStream* stream2 = session_.CreateOutgoingDataStream();
354 EXPECT_NE(kDifferentPriority, stream2->EffectivePriority());
355 // TODO(rtenneti): enable when chromium supports EXPECT_DEBUG_DFATAL.
357 EXPECT_DEBUG_DFATAL(
358 session_.MarkWriteBlocked(stream2->id(), kDifferentPriority),
359 "Priorities do not match. Got: 0 Expected: 3");
363 TEST_P(QuicSessionTest, OnCanWrite) {
364 TestStream* stream2 = session_.CreateOutgoingDataStream();
365 TestStream* stream4 = session_.CreateOutgoingDataStream();
366 TestStream* stream6 = session_.CreateOutgoingDataStream();
368 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
369 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
370 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
372 InSequence s;
373 StreamBlocker stream2_blocker(&session_, stream2->id());
374 // Reregister, to test the loop limit.
375 EXPECT_CALL(*stream2, OnCanWrite())
376 .WillOnce(Invoke(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
377 EXPECT_CALL(*stream6, OnCanWrite());
378 EXPECT_CALL(*stream4, OnCanWrite());
379 session_.OnCanWrite();
380 EXPECT_TRUE(session_.WillingAndAbleToWrite());
383 TEST_P(QuicSessionTest, OnCanWriteBundlesStreams) {
384 // Drive congestion control manually.
385 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
386 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
388 TestStream* stream2 = session_.CreateOutgoingDataStream();
389 TestStream* stream4 = session_.CreateOutgoingDataStream();
390 TestStream* stream6 = session_.CreateOutgoingDataStream();
392 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
393 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
394 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
396 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillRepeatedly(
397 Return(QuicTime::Delta::Zero()));
398 EXPECT_CALL(*send_algorithm, GetCongestionWindow())
399 .WillOnce(Return(kMaxPacketSize * 10));
400 EXPECT_CALL(*stream2, OnCanWrite())
401 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
402 &session_, &TestSession::SendStreamData, stream2->id()))));
403 EXPECT_CALL(*stream4, OnCanWrite())
404 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
405 &session_, &TestSession::SendStreamData, stream4->id()))));
406 EXPECT_CALL(*stream6, OnCanWrite())
407 .WillOnce(IgnoreResult(Invoke(CreateFunctor(
408 &session_, &TestSession::SendStreamData, stream6->id()))));
410 // Expect that we only send one packet, the writes from different streams
411 // should be bundled together.
412 MockPacketWriter* writer =
413 static_cast<MockPacketWriter*>(
414 QuicConnectionPeer::GetWriter(session_.connection()));
415 EXPECT_CALL(*writer, WritePacket(_, _, _, _)).WillOnce(
416 Return(WriteResult(WRITE_STATUS_OK, 0)));
417 EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _)).Times(1);
418 session_.OnCanWrite();
419 EXPECT_FALSE(session_.WillingAndAbleToWrite());
422 TEST_P(QuicSessionTest, OnCanWriteCongestionControlBlocks) {
423 InSequence s;
425 // Drive congestion control manually.
426 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
427 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
429 TestStream* stream2 = session_.CreateOutgoingDataStream();
430 TestStream* stream4 = session_.CreateOutgoingDataStream();
431 TestStream* stream6 = session_.CreateOutgoingDataStream();
433 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
434 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
435 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
437 StreamBlocker stream2_blocker(&session_, stream2->id());
438 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
439 QuicTime::Delta::Zero()));
440 EXPECT_CALL(*stream2, OnCanWrite());
441 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
442 QuicTime::Delta::Zero()));
443 EXPECT_CALL(*stream6, OnCanWrite());
444 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
445 QuicTime::Delta::Infinite()));
446 // stream4->OnCanWrite is not called.
448 session_.OnCanWrite();
449 EXPECT_TRUE(session_.WillingAndAbleToWrite());
451 // Still congestion-control blocked.
452 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
453 QuicTime::Delta::Infinite()));
454 session_.OnCanWrite();
455 EXPECT_TRUE(session_.WillingAndAbleToWrite());
457 // stream4->OnCanWrite is called once the connection stops being
458 // congestion-control blocked.
459 EXPECT_CALL(*send_algorithm, TimeUntilSend(_, _, _)).WillOnce(Return(
460 QuicTime::Delta::Zero()));
461 EXPECT_CALL(*stream4, OnCanWrite());
462 session_.OnCanWrite();
463 EXPECT_FALSE(session_.WillingAndAbleToWrite());
466 TEST_P(QuicSessionTest, BufferedHandshake) {
467 EXPECT_FALSE(session_.HasPendingHandshake()); // Default value.
469 // Test that blocking other streams does not change our status.
470 TestStream* stream2 = session_.CreateOutgoingDataStream();
471 StreamBlocker stream2_blocker(&session_, stream2->id());
472 stream2_blocker.MarkWriteBlocked();
473 EXPECT_FALSE(session_.HasPendingHandshake());
475 TestStream* stream3 = session_.CreateOutgoingDataStream();
476 StreamBlocker stream3_blocker(&session_, stream3->id());
477 stream3_blocker.MarkWriteBlocked();
478 EXPECT_FALSE(session_.HasPendingHandshake());
480 // Blocking (due to buffering of) the Crypto stream is detected.
481 session_.MarkWriteBlocked(kCryptoStreamId, kHighestPriority);
482 EXPECT_TRUE(session_.HasPendingHandshake());
484 TestStream* stream4 = session_.CreateOutgoingDataStream();
485 StreamBlocker stream4_blocker(&session_, stream4->id());
486 stream4_blocker.MarkWriteBlocked();
487 EXPECT_TRUE(session_.HasPendingHandshake());
489 InSequence s;
490 // Force most streams to re-register, which is common scenario when we block
491 // the Crypto stream, and only the crypto stream can "really" write.
493 // Due to prioritization, we *should* be asked to write the crypto stream
494 // first.
495 // Don't re-register the crypto stream (which signals complete writing).
496 TestCryptoStream* crypto_stream = session_.GetCryptoStream();
497 EXPECT_CALL(*crypto_stream, OnCanWrite());
499 // Re-register all other streams, to show they weren't able to proceed.
500 EXPECT_CALL(*stream2, OnCanWrite())
501 .WillOnce(Invoke(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
502 EXPECT_CALL(*stream3, OnCanWrite())
503 .WillOnce(Invoke(&stream3_blocker, &StreamBlocker::MarkWriteBlocked));
504 EXPECT_CALL(*stream4, OnCanWrite())
505 .WillOnce(Invoke(&stream4_blocker, &StreamBlocker::MarkWriteBlocked));
507 session_.OnCanWrite();
508 EXPECT_TRUE(session_.WillingAndAbleToWrite());
509 EXPECT_FALSE(session_.HasPendingHandshake()); // Crypto stream wrote.
512 TEST_P(QuicSessionTest, OnCanWriteWithClosedStream) {
513 TestStream* stream2 = session_.CreateOutgoingDataStream();
514 TestStream* stream4 = session_.CreateOutgoingDataStream();
515 TestStream* stream6 = session_.CreateOutgoingDataStream();
517 session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
518 session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
519 session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
520 CloseStream(stream6->id());
522 InSequence s;
523 EXPECT_CALL(*stream2, OnCanWrite());
524 EXPECT_CALL(*stream4, OnCanWrite());
525 session_.OnCanWrite();
526 EXPECT_FALSE(session_.WillingAndAbleToWrite());
529 TEST_P(QuicSessionTest, OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
530 if (version() < QUIC_VERSION_19) {
531 return;
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 // Add 1 to the connection timeout on the server side.
582 EXPECT_EQ(kDefaultInitialTimeoutSecs + 1,
583 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
584 CryptoHandshakeMessage msg;
585 session_.GetCryptoStream()->OnHandshakeMessage(msg);
586 EXPECT_EQ(kDefaultTimeoutSecs + 1,
587 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
590 TEST_P(QuicSessionTest, RstStreamBeforeHeadersDecompressed) {
591 // Send two bytes of payload.
592 QuicStreamFrame data1(kClientDataStreamId1, false, 0, MakeIOVector("HT"));
593 vector<QuicStreamFrame> frames;
594 frames.push_back(data1);
595 session_.OnStreamFrames(frames);
596 EXPECT_EQ(1u, session_.GetNumOpenStreams());
598 QuicRstStreamFrame rst1(kClientDataStreamId1, QUIC_STREAM_NO_ERROR, 0);
599 session_.OnRstStream(rst1);
600 EXPECT_EQ(0u, session_.GetNumOpenStreams());
601 // Connection should remain alive.
602 EXPECT_TRUE(connection_->connected());
605 TEST_P(QuicSessionTest, MultipleRstStreamsCauseSingleConnectionClose) {
606 // If multiple invalid reset stream frames arrive in a single packet, this
607 // should trigger a connection close. However there is no need to send
608 // multiple connection close frames.
610 // Create valid stream.
611 QuicStreamFrame data1(kClientDataStreamId1, false, 0, MakeIOVector("HT"));
612 vector<QuicStreamFrame> frames;
613 frames.push_back(data1);
614 session_.OnStreamFrames(frames);
615 EXPECT_EQ(1u, session_.GetNumOpenStreams());
617 // Process first invalid stream reset, resulting in the connection being
618 // closed.
619 EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID))
620 .Times(1);
621 QuicStreamId kLargeInvalidStreamId = 99999999;
622 QuicRstStreamFrame rst1(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
623 session_.OnRstStream(rst1);
624 QuicConnectionPeer::CloseConnection(connection_);
626 // Processing of second invalid stream reset should not result in the
627 // connection being closed for a second time.
628 QuicRstStreamFrame rst2(kLargeInvalidStreamId, QUIC_STREAM_NO_ERROR, 0);
629 session_.OnRstStream(rst2);
632 TEST_P(QuicSessionTest, HandshakeUnblocksFlowControlBlockedStream) {
633 // Test that if a stream is flow control blocked, then on receipt of the SHLO
634 // containing a suitable send window offset, the stream becomes unblocked.
635 if (version() <= QUIC_VERSION_16) {
636 return;
639 // Ensure that Writev consumes all the data it is given (simulate no socket
640 // blocking).
641 session_.set_writev_consumes_all_data(true);
643 // Create a stream, and send enough data to make it flow control blocked.
644 TestStream* stream2 = session_.CreateOutgoingDataStream();
645 string body(kDefaultFlowControlSendWindow, '.');
646 EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
647 stream2->SendBody(body, false);
648 EXPECT_TRUE(stream2->flow_controller()->IsBlocked());
650 // Now complete the crypto handshake, resulting in an increased flow control
651 // send window.
652 CryptoHandshakeMessage msg;
653 session_.GetCryptoStream()->OnHandshakeMessage(msg);
655 // Stream is now unblocked.
656 EXPECT_FALSE(stream2->flow_controller()->IsBlocked());
659 TEST_P(QuicSessionTest, InvalidFlowControlWindowInHandshake) {
660 // TODO(rjshade): Remove this test when removing QUIC_VERSION_19.
661 // Test that receipt of an invalid (< default) flow control window from
662 // the peer results in the connection being torn down.
663 if (version() <= QUIC_VERSION_16 || version() > QUIC_VERSION_19) {
664 return;
667 uint32 kInvalidWindow = kDefaultFlowControlSendWindow - 1;
668 QuicConfigPeer::SetReceivedInitialFlowControlWindow(session_.config(),
669 kInvalidWindow);
671 EXPECT_CALL(*connection_,
672 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW)).Times(2);
673 session_.OnConfigNegotiated();
676 TEST_P(QuicSessionTest, InvalidStreamFlowControlWindowInHandshake) {
677 // Test that receipt of an invalid (< default) stream flow control window from
678 // the peer results in the connection being torn down.
679 if (version() <= QUIC_VERSION_19) {
680 return;
683 uint32 kInvalidWindow = kDefaultFlowControlSendWindow - 1;
684 QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(),
685 kInvalidWindow);
687 EXPECT_CALL(*connection_,
688 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW));
689 session_.OnConfigNegotiated();
692 TEST_P(QuicSessionTest, InvalidSessionFlowControlWindowInHandshake) {
693 // Test that receipt of an invalid (< default) session flow control window
694 // from the peer results in the connection being torn down.
695 if (version() <= QUIC_VERSION_19) {
696 return;
699 uint32 kInvalidWindow = kDefaultFlowControlSendWindow - 1;
700 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(),
701 kInvalidWindow);
703 EXPECT_CALL(*connection_,
704 SendConnectionClose(QUIC_FLOW_CONTROL_INVALID_WINDOW));
705 session_.OnConfigNegotiated();
708 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingRstOutOfOrder) {
709 if (version() < QUIC_VERSION_19) {
710 return;
713 // Test that when we receive an out of order stream RST we correctly adjust
714 // our connection level flow control receive window.
715 // On close, the stream should mark as consumed all bytes between the highest
716 // byte consumed so far and the final byte offset from the RST frame.
717 TestStream* stream = session_.CreateOutgoingDataStream();
719 const QuicStreamOffset kByteOffset =
720 1 + kInitialSessionFlowControlWindowForTest / 2;
722 // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
723 EXPECT_CALL(*connection_, SendWindowUpdate(stream->id(), _)).Times(0);
724 // We do expect a connection level WINDOW_UPDATE when the stream is reset.
725 EXPECT_CALL(*connection_,
726 SendWindowUpdate(0, kInitialSessionFlowControlWindowForTest +
727 kByteOffset)).Times(1);
729 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
730 kByteOffset);
731 session_.OnRstStream(rst_frame);
732 session_.PostProcessAfterData();
733 EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
736 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingFinAndLocalReset) {
737 if (version() < QUIC_VERSION_19) {
738 return;
741 // Test the situation where we receive a FIN on a stream, and before we fully
742 // consume all the data from the sequencer buffer we locally RST the stream.
743 // The bytes between highest consumed byte, and the final byte offset that we
744 // determined when the FIN arrived, should be marked as consumed at the
745 // connection level flow controller when the stream is reset.
746 TestStream* stream = session_.CreateOutgoingDataStream();
748 const QuicStreamOffset kByteOffset =
749 1 + kInitialSessionFlowControlWindowForTest / 2;
750 QuicStreamFrame frame(stream->id(), true, kByteOffset, IOVector());
751 vector<QuicStreamFrame> frames;
752 frames.push_back(frame);
753 session_.OnStreamFrames(frames);
754 session_.PostProcessAfterData();
756 EXPECT_EQ(0u, stream->flow_controller()->bytes_consumed());
757 EXPECT_EQ(kByteOffset,
758 stream->flow_controller()->highest_received_byte_offset());
760 // We only expect to see a connection WINDOW_UPDATE when talking
761 // QUIC_VERSION_19, as in this case both stream and session flow control
762 // windows are the same size. In later versions we will not see a connection
763 // level WINDOW_UPDATE when exhausting a stream, as the stream flow control
764 // limit is much lower than the connection flow control limit.
765 if (version() == QUIC_VERSION_19) {
766 // Expect no stream WINDOW_UPDATE frames, as stream read side closed.
767 EXPECT_CALL(*connection_, SendWindowUpdate(stream->id(), _)).Times(0);
768 // We do expect a connection level WINDOW_UPDATE when the stream is reset.
769 EXPECT_CALL(*connection_,
770 SendWindowUpdate(0, kInitialSessionFlowControlWindowForTest +
771 kByteOffset)).Times(1);
774 // Reset stream locally.
775 stream->Reset(QUIC_STREAM_CANCELLED);
776 EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
779 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingFinAfterRst) {
780 // Test that when we RST the stream (and tear down stream state), and then
781 // receive a FIN from the peer, we correctly adjust our connection level flow
782 // control receive window.
783 if (version() < QUIC_VERSION_19) {
784 return;
787 // Connection starts with some non-zero highest received byte offset,
788 // due to other active streams.
789 const uint64 kInitialConnectionBytesConsumed = 567;
790 const uint64 kInitialConnectionHighestReceivedOffset = 1234;
791 EXPECT_LT(kInitialConnectionBytesConsumed,
792 kInitialConnectionHighestReceivedOffset);
793 session_.flow_controller()->UpdateHighestReceivedOffset(
794 kInitialConnectionHighestReceivedOffset);
795 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
797 // Reset our stream: this results in the stream being closed locally.
798 TestStream* stream = session_.CreateOutgoingDataStream();
799 stream->Reset(QUIC_STREAM_CANCELLED);
801 // Now receive a response from the peer with a FIN. We should handle this by
802 // adjusting the connection level flow control receive window to take into
803 // account the total number of bytes sent by the peer.
804 const QuicStreamOffset kByteOffset = 5678;
805 string body = "hello";
806 IOVector data = MakeIOVector(body);
807 QuicStreamFrame frame(stream->id(), true, kByteOffset, data);
808 vector<QuicStreamFrame> frames;
809 frames.push_back(frame);
810 session_.OnStreamFrames(frames);
812 QuicStreamOffset total_stream_bytes_sent_by_peer =
813 kByteOffset + body.length();
814 EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer,
815 session_.flow_controller()->bytes_consumed());
816 EXPECT_EQ(
817 kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer,
818 session_.flow_controller()->highest_received_byte_offset());
821 TEST_P(QuicSessionTest, ConnectionFlowControlAccountingRstAfterRst) {
822 // Test that when we RST the stream (and tear down stream state), and then
823 // receive a RST from the peer, we correctly adjust our connection level flow
824 // control receive window.
825 if (version() < QUIC_VERSION_19) {
826 return;
829 // Connection starts with some non-zero highest received byte offset,
830 // due to other active streams.
831 const uint64 kInitialConnectionBytesConsumed = 567;
832 const uint64 kInitialConnectionHighestReceivedOffset = 1234;
833 EXPECT_LT(kInitialConnectionBytesConsumed,
834 kInitialConnectionHighestReceivedOffset);
835 session_.flow_controller()->UpdateHighestReceivedOffset(
836 kInitialConnectionHighestReceivedOffset);
837 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
839 // Reset our stream: this results in the stream being closed locally.
840 TestStream* stream = session_.CreateOutgoingDataStream();
841 stream->Reset(QUIC_STREAM_CANCELLED);
843 // Now receive a RST from the peer. We should handle this by adjusting the
844 // connection level flow control receive window to take into account the total
845 // number of bytes sent by the peer.
846 const QuicStreamOffset kByteOffset = 5678;
847 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
848 kByteOffset);
849 session_.OnRstStream(rst_frame);
851 EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset,
852 session_.flow_controller()->bytes_consumed());
853 EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset,
854 session_.flow_controller()->highest_received_byte_offset());
857 TEST_P(QuicSessionTest, FlowControlWithInvalidFinalOffset) {
858 // Test that if we receive a stream RST with a highest byte offset that
859 // violates flow control, that we close the connection.
860 if (version() <= QUIC_VERSION_16) {
861 return;
864 const uint64 kLargeOffset = kInitialSessionFlowControlWindowForTest + 1;
865 EXPECT_CALL(*connection_,
866 SendConnectionClose(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA))
867 .Times(2);
869 // Check that stream frame + FIN results in connection close.
870 TestStream* stream = session_.CreateOutgoingDataStream();
871 stream->Reset(QUIC_STREAM_CANCELLED);
872 QuicStreamFrame frame(stream->id(), true, kLargeOffset, IOVector());
873 vector<QuicStreamFrame> frames;
874 frames.push_back(frame);
875 session_.OnStreamFrames(frames);
877 // Check that RST results in connection close.
878 QuicRstStreamFrame rst_frame(stream->id(), QUIC_STREAM_CANCELLED,
879 kLargeOffset);
880 session_.OnRstStream(rst_frame);
883 TEST_P(QuicSessionTest, VersionNegotiationDisablesFlowControl) {
884 if (version() < QUIC_VERSION_19) {
885 return;
888 // Test that after successful version negotiation, flow control is disabled
889 // appropriately at both the connection and stream level.
891 // Initially both stream and connection flow control are enabled.
892 TestStream* stream = session_.CreateOutgoingDataStream();
893 EXPECT_TRUE(stream->flow_controller()->IsEnabled());
894 EXPECT_TRUE(session_.flow_controller()->IsEnabled());
896 // Version 18 implies that stream flow control is enabled, but connection
897 // level is disabled.
898 session_.OnSuccessfulVersionNegotiation(QUIC_VERSION_18);
899 EXPECT_FALSE(session_.flow_controller()->IsEnabled());
900 EXPECT_TRUE(stream->flow_controller()->IsEnabled());
902 // Version 16 means all flow control is disabled.
903 session_.OnSuccessfulVersionNegotiation(QUIC_VERSION_16);
904 EXPECT_FALSE(session_.flow_controller()->IsEnabled());
905 EXPECT_FALSE(stream->flow_controller()->IsEnabled());
908 TEST_P(QuicSessionTest, TooManyUnfinishedStreamsCauseConnectionClose) {
909 if (version() < QUIC_VERSION_18) {
910 return;
912 // If a buggy/malicious peer creates too many streams that are not ended with
913 // a FIN or RST then we send a connection close.
914 ValueRestore<bool> old_flag(&FLAGS_close_quic_connection_unfinished_streams,
915 true);
917 EXPECT_CALL(*connection_,
918 SendConnectionClose(QUIC_TOO_MANY_UNFINISHED_STREAMS)).Times(1);
920 const int kMaxStreams = 5;
921 QuicSessionPeer::SetMaxOpenStreams(&session_, kMaxStreams);
923 // Create kMaxStreams + 1 data streams, and close them all without receiving a
924 // FIN or a RST from the client.
925 const int kFirstStreamId = kClientDataStreamId1;
926 const int kFinalStreamId = kClientDataStreamId1 + 2 * kMaxStreams + 1;
927 for (int i = kFirstStreamId; i < kFinalStreamId; i += 2) {
928 QuicStreamFrame data1(i, false, 0, MakeIOVector("HT"));
929 vector<QuicStreamFrame> frames;
930 frames.push_back(data1);
931 session_.OnStreamFrames(frames);
932 EXPECT_EQ(1u, session_.GetNumOpenStreams());
933 session_.CloseStream(i);
937 } // namespace
938 } // namespace test
939 } // namespace net