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/test_tools/quic_test_utils.h"
8 #include "base/stl_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "net/quic/crypto/crypto_framer.h"
11 #include "net/quic/crypto/crypto_handshake.h"
12 #include "net/quic/crypto/crypto_utils.h"
13 #include "net/quic/crypto/null_encrypter.h"
14 #include "net/quic/crypto/quic_decrypter.h"
15 #include "net/quic/crypto/quic_encrypter.h"
16 #include "net/quic/quic_framer.h"
17 #include "net/quic/quic_packet_creator.h"
18 #include "net/quic/quic_utils.h"
19 #include "net/quic/test_tools/quic_connection_peer.h"
20 #include "net/spdy/spdy_frame_builder.h"
22 using base::StringPiece
;
26 using testing::AnyNumber
;
33 // No-op alarm implementation used by MockHelper.
34 class TestAlarm
: public QuicAlarm
{
36 explicit TestAlarm(QuicAlarm::Delegate
* delegate
)
37 : QuicAlarm(delegate
) {
40 virtual void SetImpl() OVERRIDE
{}
41 virtual void CancelImpl() OVERRIDE
{}
46 QuicAckFrame
MakeAckFrame(QuicPacketSequenceNumber largest_observed
) {
48 ack
.largest_observed
= largest_observed
;
53 QuicAckFrame
MakeAckFrameWithNackRanges(
54 size_t num_nack_ranges
, QuicPacketSequenceNumber least_unacked
) {
55 QuicAckFrame ack
= MakeAckFrame(2 * num_nack_ranges
+ least_unacked
);
56 // Add enough missing packets to get num_nack_ranges nack ranges.
57 for (QuicPacketSequenceNumber i
= 1; i
< 2 * num_nack_ranges
; i
+= 2) {
58 ack
.missing_packets
.insert(least_unacked
+ i
);
63 SerializedPacket
BuildUnsizedDataPacket(QuicFramer
* framer
,
64 const QuicPacketHeader
& header
,
65 const QuicFrames
& frames
) {
66 const size_t max_plaintext_size
= framer
->GetMaxPlaintextSize(kMaxPacketSize
);
67 size_t packet_size
= GetPacketHeaderSize(header
);
68 for (size_t i
= 0; i
< frames
.size(); ++i
) {
69 DCHECK_LE(packet_size
, max_plaintext_size
);
70 bool first_frame
= i
== 0;
71 bool last_frame
= i
== frames
.size() - 1;
72 const size_t frame_size
= framer
->GetSerializedFrameLength(
73 frames
[i
], max_plaintext_size
- packet_size
, first_frame
, last_frame
,
74 header
.is_in_fec_group
,
75 header
.public_header
.sequence_number_length
);
77 packet_size
+= frame_size
;
79 return framer
->BuildDataPacket(header
, frames
, packet_size
);
82 uint64
SimpleRandom::RandUint64() {
83 unsigned char hash
[base::kSHA1Length
];
84 base::SHA1HashBytes(reinterpret_cast<unsigned char*>(&seed_
), sizeof(seed_
),
86 memcpy(&seed_
, hash
, sizeof(seed_
));
90 MockFramerVisitor::MockFramerVisitor() {
91 // By default, we want to accept packets.
92 ON_CALL(*this, OnProtocolVersionMismatch(_
))
93 .WillByDefault(testing::Return(false));
95 // By default, we want to accept packets.
96 ON_CALL(*this, OnUnauthenticatedHeader(_
))
97 .WillByDefault(testing::Return(true));
99 ON_CALL(*this, OnUnauthenticatedPublicHeader(_
))
100 .WillByDefault(testing::Return(true));
102 ON_CALL(*this, OnPacketHeader(_
))
103 .WillByDefault(testing::Return(true));
105 ON_CALL(*this, OnStreamFrame(_
))
106 .WillByDefault(testing::Return(true));
108 ON_CALL(*this, OnAckFrame(_
))
109 .WillByDefault(testing::Return(true));
111 ON_CALL(*this, OnCongestionFeedbackFrame(_
))
112 .WillByDefault(testing::Return(true));
114 ON_CALL(*this, OnStopWaitingFrame(_
))
115 .WillByDefault(testing::Return(true));
117 ON_CALL(*this, OnPingFrame(_
))
118 .WillByDefault(testing::Return(true));
120 ON_CALL(*this, OnRstStreamFrame(_
))
121 .WillByDefault(testing::Return(true));
123 ON_CALL(*this, OnConnectionCloseFrame(_
))
124 .WillByDefault(testing::Return(true));
126 ON_CALL(*this, OnGoAwayFrame(_
))
127 .WillByDefault(testing::Return(true));
130 MockFramerVisitor::~MockFramerVisitor() {
133 bool NoOpFramerVisitor::OnProtocolVersionMismatch(QuicVersion version
) {
137 bool NoOpFramerVisitor::OnUnauthenticatedPublicHeader(
138 const QuicPacketPublicHeader
& header
) {
142 bool NoOpFramerVisitor::OnUnauthenticatedHeader(
143 const QuicPacketHeader
& header
) {
147 bool NoOpFramerVisitor::OnPacketHeader(const QuicPacketHeader
& header
) {
151 bool NoOpFramerVisitor::OnStreamFrame(const QuicStreamFrame
& frame
) {
155 bool NoOpFramerVisitor::OnAckFrame(const QuicAckFrame
& frame
) {
159 bool NoOpFramerVisitor::OnCongestionFeedbackFrame(
160 const QuicCongestionFeedbackFrame
& frame
) {
164 bool NoOpFramerVisitor::OnStopWaitingFrame(
165 const QuicStopWaitingFrame
& frame
) {
169 bool NoOpFramerVisitor::OnPingFrame(const QuicPingFrame
& frame
) {
173 bool NoOpFramerVisitor::OnRstStreamFrame(
174 const QuicRstStreamFrame
& frame
) {
178 bool NoOpFramerVisitor::OnConnectionCloseFrame(
179 const QuicConnectionCloseFrame
& frame
) {
183 bool NoOpFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
187 bool NoOpFramerVisitor::OnWindowUpdateFrame(
188 const QuicWindowUpdateFrame
& frame
) {
192 bool NoOpFramerVisitor::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
196 MockConnectionVisitor::MockConnectionVisitor() {
199 MockConnectionVisitor::~MockConnectionVisitor() {
202 MockHelper::MockHelper() {
205 MockHelper::~MockHelper() {
208 const QuicClock
* MockHelper::GetClock() const {
212 QuicRandom
* MockHelper::GetRandomGenerator() {
213 return &random_generator_
;
216 QuicAlarm
* MockHelper::CreateAlarm(QuicAlarm::Delegate
* delegate
) {
217 return new TestAlarm(delegate
);
220 void MockHelper::AdvanceTime(QuicTime::Delta delta
) {
221 clock_
.AdvanceTime(delta
);
225 class NiceMockPacketWriterFactory
226 : public QuicConnection::PacketWriterFactory
{
228 NiceMockPacketWriterFactory() {}
229 virtual ~NiceMockPacketWriterFactory() {}
231 virtual QuicPacketWriter
* Create(
232 QuicConnection
* /*connection*/) const override
{
233 return new testing::NiceMock
<MockPacketWriter
>();
237 DISALLOW_COPY_AND_ASSIGN(NiceMockPacketWriterFactory
);
241 MockConnection::MockConnection(bool is_server
)
242 : QuicConnection(kTestConnectionId
,
243 IPEndPoint(TestPeerIPAddress(), kTestPort
),
244 new testing::NiceMock
<MockHelper
>(),
245 NiceMockPacketWriterFactory(),
246 /* owns_writer= */ true,
247 is_server
, QuicSupportedVersions()),
251 MockConnection::MockConnection(IPEndPoint address
,
253 : QuicConnection(kTestConnectionId
, address
,
254 new testing::NiceMock
<MockHelper
>(),
255 NiceMockPacketWriterFactory(),
256 /* owns_writer= */ true,
257 is_server
, QuicSupportedVersions()),
261 MockConnection::MockConnection(QuicConnectionId connection_id
,
263 : QuicConnection(connection_id
,
264 IPEndPoint(TestPeerIPAddress(), kTestPort
),
265 new testing::NiceMock
<MockHelper
>(),
266 NiceMockPacketWriterFactory(),
267 /* owns_writer= */ true,
268 is_server
, QuicSupportedVersions()),
272 MockConnection::MockConnection(bool is_server
,
273 const QuicVersionVector
& supported_versions
)
274 : QuicConnection(kTestConnectionId
,
275 IPEndPoint(TestPeerIPAddress(), kTestPort
),
276 new testing::NiceMock
<MockHelper
>(),
277 NiceMockPacketWriterFactory(),
278 /* owns_writer= */ true,
279 is_server
, supported_versions
),
283 MockConnection::~MockConnection() {
286 void MockConnection::AdvanceTime(QuicTime::Delta delta
) {
287 static_cast<MockHelper
*>(helper())->AdvanceTime(delta
);
290 PacketSavingConnection::PacketSavingConnection(bool is_server
)
291 : MockConnection(is_server
) {
294 PacketSavingConnection::PacketSavingConnection(
296 const QuicVersionVector
& supported_versions
)
297 : MockConnection(is_server
, supported_versions
) {
300 PacketSavingConnection::~PacketSavingConnection() {
301 STLDeleteElements(&packets_
);
302 STLDeleteElements(&encrypted_packets_
);
305 bool PacketSavingConnection::SendOrQueuePacket(
306 EncryptionLevel level
,
307 const SerializedPacket
& packet
,
308 TransmissionType transmission_type
) {
309 packets_
.push_back(packet
.packet
);
310 QuicEncryptedPacket
* encrypted
= QuicConnectionPeer::GetFramer(this)->
311 EncryptPacket(level
, packet
.sequence_number
, *packet
.packet
);
312 encrypted_packets_
.push_back(encrypted
);
316 MockSession::MockSession(QuicConnection
* connection
)
317 : QuicSession(connection
, DefaultQuicConfig()) {
319 ON_CALL(*this, WritevData(_
, _
, _
, _
, _
, _
))
320 .WillByDefault(testing::Return(QuicConsumedData(0, false)));
323 MockSession::~MockSession() {
326 TestSession::TestSession(QuicConnection
* connection
, const QuicConfig
& config
)
327 : QuicSession(connection
, config
),
328 crypto_stream_(NULL
) {
332 TestSession::~TestSession() {}
334 void TestSession::SetCryptoStream(QuicCryptoStream
* stream
) {
335 crypto_stream_
= stream
;
338 QuicCryptoStream
* TestSession::GetCryptoStream() {
339 return crypto_stream_
;
342 TestClientSession::TestClientSession(QuicConnection
* connection
,
343 const QuicConfig
& config
)
344 : QuicClientSessionBase(connection
, config
),
345 crypto_stream_(NULL
) {
346 EXPECT_CALL(*this, OnProofValid(_
)).Times(AnyNumber());
350 TestClientSession::~TestClientSession() {}
352 void TestClientSession::SetCryptoStream(QuicCryptoStream
* stream
) {
353 crypto_stream_
= stream
;
356 QuicCryptoStream
* TestClientSession::GetCryptoStream() {
357 return crypto_stream_
;
360 MockPacketWriter::MockPacketWriter() {
363 MockPacketWriter::~MockPacketWriter() {
366 MockSendAlgorithm::MockSendAlgorithm() {
369 MockSendAlgorithm::~MockSendAlgorithm() {
372 MockLossAlgorithm::MockLossAlgorithm() {
375 MockLossAlgorithm::~MockLossAlgorithm() {
378 MockAckNotifierDelegate::MockAckNotifierDelegate() {
381 MockAckNotifierDelegate::~MockAckNotifierDelegate() {
384 MockNetworkChangeVisitor::MockNetworkChangeVisitor() {
387 MockNetworkChangeVisitor::~MockNetworkChangeVisitor() {
392 string
HexDumpWithMarks(const char* data
, int length
,
393 const bool* marks
, int mark_length
) {
394 static const char kHexChars
[] = "0123456789abcdef";
395 static const int kColumns
= 4;
397 const int kSizeLimit
= 1024;
398 if (length
> kSizeLimit
|| mark_length
> kSizeLimit
) {
399 LOG(ERROR
) << "Only dumping first " << kSizeLimit
<< " bytes.";
400 length
= min(length
, kSizeLimit
);
401 mark_length
= min(mark_length
, kSizeLimit
);
405 for (const char* row
= data
; length
> 0;
406 row
+= kColumns
, length
-= kColumns
) {
407 for (const char *p
= row
; p
< row
+ 4; ++p
) {
408 if (p
< row
+ length
) {
410 (marks
&& (p
- data
) < mark_length
&& marks
[p
- data
]);
411 hex
+= mark
? '*' : ' ';
412 hex
+= kHexChars
[(*p
& 0xf0) >> 4];
413 hex
+= kHexChars
[*p
& 0x0f];
414 hex
+= mark
? '*' : ' ';
421 for (const char *p
= row
; p
< row
+ 4 && p
< row
+ length
; ++p
)
422 hex
+= (*p
>= 0x20 && *p
<= 0x7f) ? (*p
) : '.';
431 IPAddressNumber
TestPeerIPAddress() { return Loopback4(); }
433 QuicVersion
QuicVersionMax() { return QuicSupportedVersions().front(); }
435 QuicVersion
QuicVersionMin() { return QuicSupportedVersions().back(); }
437 IPAddressNumber
Loopback4() {
438 IPAddressNumber addr
;
439 CHECK(ParseIPLiteralToNumber("127.0.0.1", &addr
));
443 IPAddressNumber
Loopback6() {
444 IPAddressNumber addr
;
445 CHECK(ParseIPLiteralToNumber("::1", &addr
));
449 void GenerateBody(string
* body
, int length
) {
451 body
->reserve(length
);
452 for (int i
= 0; i
< length
; ++i
) {
453 body
->append(1, static_cast<char>(32 + i
% (126 - 32)));
457 QuicEncryptedPacket
* ConstructEncryptedPacket(
458 QuicConnectionId connection_id
,
461 QuicPacketSequenceNumber sequence_number
,
462 const string
& data
) {
463 QuicPacketHeader header
;
464 header
.public_header
.connection_id
= connection_id
;
465 header
.public_header
.connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
466 header
.public_header
.version_flag
= version_flag
;
467 header
.public_header
.reset_flag
= reset_flag
;
468 header
.public_header
.sequence_number_length
= PACKET_6BYTE_SEQUENCE_NUMBER
;
469 header
.packet_sequence_number
= sequence_number
;
470 header
.entropy_flag
= false;
471 header
.entropy_hash
= 0;
472 header
.fec_flag
= false;
473 header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
474 header
.fec_group
= 0;
475 QuicStreamFrame
stream_frame(1, false, 0, MakeIOVector(data
));
476 QuicFrame
frame(&stream_frame
);
478 frames
.push_back(frame
);
479 QuicFramer
framer(QuicSupportedVersions(), QuicTime::Zero(), false);
480 scoped_ptr
<QuicPacket
> packet(
481 BuildUnsizedDataPacket(&framer
, header
, frames
).packet
);
482 EXPECT_TRUE(packet
!= NULL
);
483 QuicEncryptedPacket
* encrypted
= framer
.EncryptPacket(ENCRYPTION_NONE
,
486 EXPECT_TRUE(encrypted
!= NULL
);
490 void CompareCharArraysWithHexError(
491 const string
& description
,
493 const int actual_len
,
494 const char* expected
,
495 const int expected_len
) {
496 EXPECT_EQ(actual_len
, expected_len
);
497 const int min_len
= min(actual_len
, expected_len
);
498 const int max_len
= max(actual_len
, expected_len
);
499 scoped_ptr
<bool[]> marks(new bool[max_len
]);
500 bool identical
= (actual_len
== expected_len
);
501 for (int i
= 0; i
< min_len
; ++i
) {
502 if (actual
[i
] != expected
[i
]) {
509 for (int i
= min_len
; i
< max_len
; ++i
) {
512 if (identical
) return;
517 << HexDumpWithMarks(expected
, expected_len
, marks
.get(), max_len
)
519 << HexDumpWithMarks(actual
, actual_len
, marks
.get(), max_len
);
522 bool DecodeHexString(const base::StringPiece
& hex
, std::string
* bytes
) {
526 std::vector
<uint8
> v
;
527 if (!base::HexStringToBytes(hex
.as_string(), &v
))
530 bytes
->assign(reinterpret_cast<const char*>(&v
[0]), v
.size());
534 static QuicPacket
* ConstructPacketFromHandshakeMessage(
535 QuicConnectionId connection_id
,
536 const CryptoHandshakeMessage
& message
,
537 bool should_include_version
) {
538 CryptoFramer crypto_framer
;
539 scoped_ptr
<QuicData
> data(crypto_framer
.ConstructHandshakeMessage(message
));
540 QuicFramer
quic_framer(QuicSupportedVersions(), QuicTime::Zero(), false);
542 QuicPacketHeader header
;
543 header
.public_header
.connection_id
= connection_id
;
544 header
.public_header
.reset_flag
= false;
545 header
.public_header
.version_flag
= should_include_version
;
546 header
.packet_sequence_number
= 1;
547 header
.entropy_flag
= false;
548 header
.entropy_hash
= 0;
549 header
.fec_flag
= false;
550 header
.fec_group
= 0;
552 QuicStreamFrame
stream_frame(kCryptoStreamId
, false, 0,
553 MakeIOVector(data
->AsStringPiece()));
555 QuicFrame
frame(&stream_frame
);
557 frames
.push_back(frame
);
558 return BuildUnsizedDataPacket(&quic_framer
, header
, frames
).packet
;
561 QuicPacket
* ConstructHandshakePacket(QuicConnectionId connection_id
,
563 CryptoHandshakeMessage message
;
564 message
.set_tag(tag
);
565 return ConstructPacketFromHandshakeMessage(connection_id
, message
, false);
568 size_t GetPacketLengthForOneStream(
570 bool include_version
,
571 QuicSequenceNumberLength sequence_number_length
,
572 InFecGroup is_in_fec_group
,
573 size_t* payload_length
) {
575 const size_t stream_length
=
576 NullEncrypter().GetCiphertextSize(*payload_length
) +
577 QuicPacketCreator::StreamFramePacketOverhead(
578 PACKET_8BYTE_CONNECTION_ID
, include_version
,
579 sequence_number_length
, 0u, is_in_fec_group
);
580 const size_t ack_length
= NullEncrypter().GetCiphertextSize(
581 QuicFramer::GetMinAckFrameSize(
582 sequence_number_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) +
583 GetPacketHeaderSize(PACKET_8BYTE_CONNECTION_ID
, include_version
,
584 sequence_number_length
, is_in_fec_group
);
585 if (stream_length
< ack_length
) {
586 *payload_length
= 1 + ack_length
- stream_length
;
589 return NullEncrypter().GetCiphertextSize(*payload_length
) +
590 QuicPacketCreator::StreamFramePacketOverhead(
591 PACKET_8BYTE_CONNECTION_ID
, include_version
,
592 sequence_number_length
, 0u, is_in_fec_group
);
595 TestEntropyCalculator::TestEntropyCalculator() {}
597 TestEntropyCalculator::~TestEntropyCalculator() {}
599 QuicPacketEntropyHash
TestEntropyCalculator::EntropyHash(
600 QuicPacketSequenceNumber sequence_number
) const {
604 MockEntropyCalculator::MockEntropyCalculator() {}
606 MockEntropyCalculator::~MockEntropyCalculator() {}
608 QuicConfig
DefaultQuicConfig() {
610 config
.SetDefaults();
611 config
.SetInitialFlowControlWindowToSend(
612 kInitialSessionFlowControlWindowForTest
);
613 config
.SetInitialStreamFlowControlWindowToSend(
614 kInitialStreamFlowControlWindowForTest
);
615 config
.SetInitialSessionFlowControlWindowToSend(
616 kInitialSessionFlowControlWindowForTest
);
620 QuicVersionVector
SupportedVersions(QuicVersion version
) {
621 QuicVersionVector versions
;
622 versions
.push_back(version
);
626 TestWriterFactory::TestWriterFactory() : current_writer_(NULL
) {}
627 TestWriterFactory::~TestWriterFactory() {}
629 QuicPacketWriter
* TestWriterFactory::Create(QuicServerPacketWriter
* writer
,
630 QuicConnection
* connection
) {
631 return new PerConnectionPacketWriter(this, writer
, connection
);
634 void TestWriterFactory::OnPacketSent(WriteResult result
) {
635 if (current_writer_
!= NULL
&& result
.status
== WRITE_STATUS_ERROR
) {
636 current_writer_
->connection()->OnWriteError(result
.error_code
);
637 current_writer_
= NULL
;
641 void TestWriterFactory::Unregister(PerConnectionPacketWriter
* writer
) {
642 if (current_writer_
== writer
) {
643 current_writer_
= NULL
;
647 TestWriterFactory::PerConnectionPacketWriter::PerConnectionPacketWriter(
648 TestWriterFactory
* factory
,
649 QuicServerPacketWriter
* writer
,
650 QuicConnection
* connection
)
651 : QuicPerConnectionPacketWriter(writer
, connection
),
655 TestWriterFactory::PerConnectionPacketWriter::~PerConnectionPacketWriter() {
656 factory_
->Unregister(this);
659 WriteResult
TestWriterFactory::PerConnectionPacketWriter::WritePacket(
662 const IPAddressNumber
& self_address
,
663 const IPEndPoint
& peer_address
) {
664 // A DCHECK(factory_current_writer_ == NULL) would be wrong here -- this class
665 // may be used in a setting where connection()->OnPacketSent() is called in a
666 // different way, so TestWriterFactory::OnPacketSent might never be called.
667 factory_
->current_writer_
= this;
668 return QuicPerConnectionPacketWriter::WritePacket(buffer
,