- add sources.
[platform/framework/web/crosswalk.git] / src / net / quic / quic_session_test.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/quic/quic_session.h"
6
7 #include <set>
8 #include <vector>
9
10 #include "base/containers/hash_tables.h"
11 #include "net/quic/crypto/crypto_handshake.h"
12 #include "net/quic/quic_connection.h"
13 #include "net/quic/quic_protocol.h"
14 #include "net/quic/test_tools/quic_connection_peer.h"
15 #include "net/quic/test_tools/quic_test_utils.h"
16 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
17 #include "net/spdy/spdy_framer.h"
18 #include "testing/gmock/include/gmock/gmock.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20
21 using base::hash_map;
22 using std::set;
23 using std::vector;
24 using testing::_;
25 using testing::InSequence;
26 using testing::InvokeWithoutArgs;
27 using testing::StrictMock;
28
29 namespace net {
30 namespace test {
31 namespace {
32
33 const QuicPriority kSomeMiddlePriority = 2;
34
35 class TestCryptoStream : public QuicCryptoStream {
36  public:
37   explicit TestCryptoStream(QuicSession* session)
38       : QuicCryptoStream(session) {
39   }
40
41   virtual void OnHandshakeMessage(
42       const CryptoHandshakeMessage& message) OVERRIDE {
43     encryption_established_ = true;
44     handshake_confirmed_ = true;
45     CryptoHandshakeMessage msg;
46     string error_details;
47     session()->config()->ToHandshakeMessage(&msg);
48     const QuicErrorCode error = session()->config()->ProcessClientHello(
49         msg, &error_details);
50     EXPECT_EQ(QUIC_NO_ERROR, error);
51     session()->OnConfigNegotiated();
52     session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED);
53   }
54
55   MOCK_METHOD0(OnCanWrite, void());
56 };
57
58 class TestStream : public ReliableQuicStream {
59  public:
60   TestStream(QuicStreamId id, QuicSession* session)
61       : ReliableQuicStream(id, session) {
62   }
63
64   using ReliableQuicStream::CloseWriteSide;
65
66   virtual uint32 ProcessData(const char* data, uint32 data_len) {
67     return data_len;
68   }
69
70   MOCK_METHOD0(OnCanWrite, void());
71 };
72
73 // Poor man's functor for use as callback in a mock.
74 class StreamBlocker {
75  public:
76   StreamBlocker(QuicSession* session, QuicStreamId stream_id)
77       : session_(session),
78         stream_id_(stream_id) {
79   }
80
81   void MarkWriteBlocked() {
82     session_->MarkWriteBlocked(stream_id_, kSomeMiddlePriority);
83   }
84
85  private:
86   QuicSession* const session_;
87   const QuicStreamId stream_id_;
88 };
89
90 class TestSession : public QuicSession {
91  public:
92   TestSession(QuicConnection* connection, bool is_server)
93       : QuicSession(connection, DefaultQuicConfig(), is_server),
94         crypto_stream_(this) {
95   }
96
97   virtual TestCryptoStream* GetCryptoStream() OVERRIDE {
98     return &crypto_stream_;
99   }
100
101   virtual TestStream* CreateOutgoingReliableStream() OVERRIDE {
102     TestStream* stream = new TestStream(GetNextStreamId(), this);
103     ActivateStream(stream);
104     return stream;
105   }
106
107   virtual TestStream* CreateIncomingReliableStream(QuicStreamId id) OVERRIDE {
108     return new TestStream(id, this);
109   }
110
111   bool IsClosedStream(QuicStreamId id) {
112     return QuicSession::IsClosedStream(id);
113   }
114
115   ReliableQuicStream* GetIncomingReliableStream(QuicStreamId stream_id) {
116     return QuicSession::GetIncomingReliableStream(stream_id);
117   }
118
119   TestCryptoStream crypto_stream_;
120 };
121
122 class QuicSessionTest : public ::testing::Test {
123  protected:
124   QuicSessionTest()
125       : guid_(1),
126         connection_(new MockConnection(guid_, IPEndPoint(), false)),
127         session_(connection_, true) {
128     headers_[":host"] = "www.google.com";
129     headers_[":path"] = "/index.hml";
130     headers_[":scheme"] = "http";
131     headers_["cookie"] =
132         "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
133         "__utmc=160408618; "
134         "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX"
135         "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX"
136         "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT"
137         "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0"
138         "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh"
139         "1zFMi5vzcns38-8_Sns; "
140         "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-"
141         "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339"
142         "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c"
143         "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%"
144         "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4"
145         "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1"
146         "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP"
147         "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6"
148         "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b"
149         "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6"
150         "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG"
151         "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk"
152         "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn"
153         "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr"
154         "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo ";
155   }
156
157   void CheckClosedStreams() {
158     for (int i = kCryptoStreamId; i < 100; i++) {
159       if (closed_streams_.count(i) == 0) {
160         EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
161       } else {
162         EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
163       }
164     }
165   }
166
167   void CloseStream(QuicStreamId id) {
168     session_.CloseStream(id);
169     closed_streams_.insert(id);
170   }
171
172   QuicGuid guid_;
173   MockConnection* connection_;
174   TestSession session_;
175   set<QuicStreamId> closed_streams_;
176   SpdyHeaderBlock headers_;
177 };
178
179 TEST_F(QuicSessionTest, PeerAddress) {
180   EXPECT_EQ(IPEndPoint(), session_.peer_address());
181 }
182
183 TEST_F(QuicSessionTest, IsCryptoHandshakeConfirmed) {
184   EXPECT_FALSE(session_.IsCryptoHandshakeConfirmed());
185   CryptoHandshakeMessage message;
186   session_.crypto_stream_.OnHandshakeMessage(message);
187   EXPECT_TRUE(session_.IsCryptoHandshakeConfirmed());
188 }
189
190 TEST_F(QuicSessionTest, IsClosedStreamDefault) {
191   // Ensure that no streams are initially closed.
192   for (int i = kCryptoStreamId; i < 100; i++) {
193     EXPECT_FALSE(session_.IsClosedStream(i));
194   }
195 }
196
197 TEST_F(QuicSessionTest, ImplicitlyCreatedStreams) {
198   ASSERT_TRUE(session_.GetIncomingReliableStream(7) != NULL);
199   // Both 3 and 5 should be implicitly created.
200   EXPECT_FALSE(session_.IsClosedStream(3));
201   EXPECT_FALSE(session_.IsClosedStream(5));
202   ASSERT_TRUE(session_.GetIncomingReliableStream(5) != NULL);
203   ASSERT_TRUE(session_.GetIncomingReliableStream(3) != NULL);
204 }
205
206 TEST_F(QuicSessionTest, IsClosedStreamLocallyCreated) {
207   TestStream* stream2 = session_.CreateOutgoingReliableStream();
208   EXPECT_EQ(2u, stream2->id());
209   ReliableQuicStreamPeer::SetHeadersDecompressed(stream2, true);
210   TestStream* stream4 = session_.CreateOutgoingReliableStream();
211   EXPECT_EQ(4u, stream4->id());
212   ReliableQuicStreamPeer::SetHeadersDecompressed(stream4, true);
213
214   CheckClosedStreams();
215   CloseStream(4);
216   CheckClosedStreams();
217   CloseStream(2);
218   CheckClosedStreams();
219 }
220
221 TEST_F(QuicSessionTest, IsClosedStreamPeerCreated) {
222   ReliableQuicStream* stream3 = session_.GetIncomingReliableStream(3);
223   ReliableQuicStreamPeer::SetHeadersDecompressed(stream3, true);
224   ReliableQuicStream* stream5 = session_.GetIncomingReliableStream(5);
225   ReliableQuicStreamPeer::SetHeadersDecompressed(stream5, true);
226
227   CheckClosedStreams();
228   CloseStream(3);
229   CheckClosedStreams();
230   CloseStream(5);
231   // Create stream id 9, and implicitly 7
232   ReliableQuicStream* stream9 = session_.GetIncomingReliableStream(9);
233   ReliableQuicStreamPeer::SetHeadersDecompressed(stream9, true);
234   CheckClosedStreams();
235   // Close 9, but make sure 7 is still not closed
236   CloseStream(9);
237   CheckClosedStreams();
238 }
239
240 TEST_F(QuicSessionTest, StreamIdTooLarge) {
241   session_.GetIncomingReliableStream(3);
242   EXPECT_CALL(*connection_, SendConnectionClose(QUIC_INVALID_STREAM_ID));
243   session_.GetIncomingReliableStream(105);
244 }
245
246 TEST_F(QuicSessionTest, DecompressionError) {
247   ReliableQuicStream* stream = session_.GetIncomingReliableStream(3);
248   EXPECT_CALL(*connection_, SendConnectionClose(QUIC_DECOMPRESSION_FAILURE));
249   const char data[] =
250       "\1\0\0\0"   // headers id
251       "\0\0\0\4"   // length
252       "abcd";      // invalid compressed data
253   stream->ProcessRawData(data, arraysize(data));
254 }
255
256 TEST_F(QuicSessionTest, OnCanWrite) {
257   TestStream* stream2 = session_.CreateOutgoingReliableStream();
258   TestStream* stream4 = session_.CreateOutgoingReliableStream();
259   TestStream* stream6 = session_.CreateOutgoingReliableStream();
260
261   session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
262   session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
263   session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
264
265   InSequence s;
266   StreamBlocker stream2_blocker(&session_, stream2->id());
267   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(
268       // Reregister, to test the loop limit.
269       InvokeWithoutArgs(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
270   EXPECT_CALL(*stream6, OnCanWrite());
271   EXPECT_CALL(*stream4, OnCanWrite());
272
273   EXPECT_FALSE(session_.OnCanWrite());
274 }
275
276 TEST_F(QuicSessionTest, BufferedHandshake) {
277   EXPECT_FALSE(session_.HasPendingHandshake());  // Default value.
278
279   // Test that blocking other streams does not change our status.
280   TestStream* stream2 = session_.CreateOutgoingReliableStream();
281   StreamBlocker stream2_blocker(&session_, stream2->id());
282   stream2_blocker.MarkWriteBlocked();
283   EXPECT_FALSE(session_.HasPendingHandshake());
284
285   TestStream* stream3 = session_.CreateOutgoingReliableStream();
286   StreamBlocker stream3_blocker(&session_, stream3->id());
287   stream3_blocker.MarkWriteBlocked();
288   EXPECT_FALSE(session_.HasPendingHandshake());
289
290   // Blocking (due to buffering of) the Crypto stream is detected.
291   session_.MarkWriteBlocked(kCryptoStreamId, kSomeMiddlePriority);
292   EXPECT_TRUE(session_.HasPendingHandshake());
293
294   TestStream* stream4 = session_.CreateOutgoingReliableStream();
295   StreamBlocker stream4_blocker(&session_, stream4->id());
296   stream4_blocker.MarkWriteBlocked();
297   EXPECT_TRUE(session_.HasPendingHandshake());
298
299   InSequence s;
300   // Force most streams to re-register, which is common scenario when we block
301   // the Crypto stream, and only the crypto stream can "really" write.
302
303   // Due to prioritization, we *should* be asked to write the crypto stream
304   // first.
305   // Don't re-register the crypto stream (which signals complete writing).
306   TestCryptoStream* crypto_stream = session_.GetCryptoStream();
307   EXPECT_CALL(*crypto_stream, OnCanWrite());
308
309   // Re-register all other streams, to show they weren't able to proceed.
310   EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(
311       InvokeWithoutArgs(&stream2_blocker, &StreamBlocker::MarkWriteBlocked));
312
313   EXPECT_CALL(*stream3, OnCanWrite()).WillOnce(
314       InvokeWithoutArgs(&stream3_blocker, &StreamBlocker::MarkWriteBlocked));
315
316   EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(
317       InvokeWithoutArgs(&stream4_blocker, &StreamBlocker::MarkWriteBlocked));
318
319   EXPECT_FALSE(session_.OnCanWrite());
320   EXPECT_FALSE(session_.HasPendingHandshake());  // Crypto stream wrote.
321 }
322
323 TEST_F(QuicSessionTest, OnCanWriteWithClosedStream) {
324   TestStream* stream2 = session_.CreateOutgoingReliableStream();
325   TestStream* stream4 = session_.CreateOutgoingReliableStream();
326   TestStream* stream6 = session_.CreateOutgoingReliableStream();
327
328   session_.MarkWriteBlocked(stream2->id(), kSomeMiddlePriority);
329   session_.MarkWriteBlocked(stream6->id(), kSomeMiddlePriority);
330   session_.MarkWriteBlocked(stream4->id(), kSomeMiddlePriority);
331   CloseStream(stream6->id());
332
333   InSequence s;
334   EXPECT_CALL(*stream2, OnCanWrite());
335   EXPECT_CALL(*stream4, OnCanWrite());
336   EXPECT_TRUE(session_.OnCanWrite());
337 }
338
339 // Regression test for http://crbug.com/248737
340 TEST_F(QuicSessionTest, OutOfOrderHeaders) {
341   QuicSpdyCompressor compressor;
342   vector<QuicStreamFrame> frames;
343   QuicPacketHeader header;
344   header.public_header.guid = session_.guid();
345
346   TestStream* stream2 = session_.CreateOutgoingReliableStream();
347   TestStream* stream4 = session_.CreateOutgoingReliableStream();
348   stream2->CloseWriteSide();
349   stream4->CloseWriteSide();
350
351   // Create frame with headers for stream2.
352   string compressed_headers1 = compressor.CompressHeaders(headers_);
353   QuicStreamFrame frame1(stream2->id(), false, 0, compressed_headers1);
354
355   // Create frame with headers for stream4.
356   string compressed_headers2 = compressor.CompressHeaders(headers_);
357   QuicStreamFrame frame2(stream4->id(), true, 0, compressed_headers2);
358
359   // Process the second frame first.  This will cause the headers to
360   // be queued up and processed after the first frame is processed.
361   frames.push_back(frame2);
362   session_.OnStreamFrames(frames);
363
364   // Process the first frame, and un-cork the buffered headers.
365   frames[0] = frame1;
366   session_.OnStreamFrames(frames);
367
368   // Ensure that the streams actually close and we don't DCHECK.
369   connection_->CloseConnection(QUIC_CONNECTION_TIMED_OUT, true);
370 }
371
372 TEST_F(QuicSessionTest, SendGoAway) {
373   // After sending a GoAway, ensure new incoming streams cannot be created and
374   // result in a RST being sent.
375   EXPECT_CALL(*connection_,
376               SendGoAway(QUIC_PEER_GOING_AWAY, 0u, "Going Away."));
377   session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
378   EXPECT_TRUE(session_.goaway_sent());
379
380   EXPECT_CALL(*connection_, SendRstStream(3u, QUIC_STREAM_PEER_GOING_AWAY));
381   EXPECT_FALSE(session_.GetIncomingReliableStream(3u));
382 }
383
384 TEST_F(QuicSessionTest, IncreasedTimeoutAfterCryptoHandshake) {
385   EXPECT_EQ(kDefaultInitialTimeoutSecs,
386             QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
387   CryptoHandshakeMessage msg;
388   session_.crypto_stream_.OnHandshakeMessage(msg);
389   EXPECT_EQ(kDefaultTimeoutSecs,
390             QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
391 }
392
393 TEST_F(QuicSessionTest, ZombieStream) {
394   StrictMock<MockConnection>* connection =
395       new StrictMock<MockConnection>(guid_, IPEndPoint(), false);
396   TestSession session(connection, /*is_server=*/ false);
397
398   TestStream* stream3 = session.CreateOutgoingReliableStream();
399   EXPECT_EQ(3u, stream3->id());
400   TestStream* stream5 = session.CreateOutgoingReliableStream();
401   EXPECT_EQ(5u, stream5->id());
402   EXPECT_EQ(2u, session.GetNumOpenStreams());
403
404   // Reset the stream, but since the headers have not been decompressed
405   // it will become a zombie and will continue to process data
406   // until the headers are decompressed.
407   EXPECT_CALL(*connection, SendRstStream(3, QUIC_STREAM_CANCELLED));
408   session.SendRstStream(3, QUIC_STREAM_CANCELLED);
409
410   EXPECT_EQ(1u, session.GetNumOpenStreams());
411
412   vector<QuicStreamFrame> frames;
413   QuicPacketHeader header;
414   header.public_header.guid = session_.guid();
415
416   // Create frame with headers for stream2.
417   QuicSpdyCompressor compressor;
418   string compressed_headers1 = compressor.CompressHeaders(headers_);
419   QuicStreamFrame frame1(stream3->id(), false, 0, compressed_headers1);
420
421   // Process the second frame first.  This will cause the headers to
422   // be queued up and processed after the first frame is processed.
423   frames.push_back(frame1);
424   EXPECT_FALSE(stream3->headers_decompressed());
425
426   session.OnStreamFrames(frames);
427   EXPECT_EQ(1u, session.GetNumOpenStreams());
428
429   EXPECT_TRUE(connection->connected());
430 }
431
432 TEST_F(QuicSessionTest, ZombieStreamConnectionClose) {
433   StrictMock<MockConnection>* connection =
434       new StrictMock<MockConnection>(guid_, IPEndPoint(), false);
435   TestSession session(connection, /*is_server=*/ false);
436
437   TestStream* stream3 = session.CreateOutgoingReliableStream();
438   EXPECT_EQ(3u, stream3->id());
439   TestStream* stream5 = session.CreateOutgoingReliableStream();
440   EXPECT_EQ(5u, stream5->id());
441   EXPECT_EQ(2u, session.GetNumOpenStreams());
442
443   stream3->CloseWriteSide();
444   // Reset the stream, but since the headers have not been decompressed
445   // it will become a zombie and will continue to process data
446   // until the headers are decompressed.
447   EXPECT_CALL(*connection, SendRstStream(3, QUIC_STREAM_CANCELLED));
448   session.SendRstStream(3, QUIC_STREAM_CANCELLED);
449
450   EXPECT_EQ(1u, session.GetNumOpenStreams());
451
452   connection->CloseConnection(QUIC_CONNECTION_TIMED_OUT, false);
453
454   EXPECT_EQ(0u, session.GetNumOpenStreams());
455 }
456
457 }  // namespace
458 }  // namespace test
459 }  // namespace net