Fix crash in SpeechRecognizerImpl introduced in AudioParams refactor.
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blob944105ec165dcf9387123c71b9c21284b68db0a1
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 <stddef.h>
6 #include <string>
7 #include <sys/epoll.h>
8 #include <vector>
10 #include "base/basictypes.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/singleton.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/threading/platform_thread.h"
16 #include "base/time/time.h"
17 #include "net/base/ip_endpoint.h"
18 #include "net/quic/congestion_control/tcp_cubic_sender.h"
19 #include "net/quic/crypto/aes_128_gcm_12_encrypter.h"
20 #include "net/quic/crypto/null_encrypter.h"
21 #include "net/quic/quic_flags.h"
22 #include "net/quic/quic_framer.h"
23 #include "net/quic/quic_packet_creator.h"
24 #include "net/quic/quic_protocol.h"
25 #include "net/quic/quic_server_id.h"
26 #include "net/quic/quic_utils.h"
27 #include "net/quic/test_tools/quic_connection_peer.h"
28 #include "net/quic/test_tools/quic_flow_controller_peer.h"
29 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
30 #include "net/quic/test_tools/quic_session_peer.h"
31 #include "net/quic/test_tools/quic_spdy_session_peer.h"
32 #include "net/quic/test_tools/quic_test_utils.h"
33 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
34 #include "net/test/gtest_util.h"
35 #include "net/tools/epoll_server/epoll_server.h"
36 #include "net/tools/quic/quic_epoll_connection_helper.h"
37 #include "net/tools/quic/quic_in_memory_cache.h"
38 #include "net/tools/quic/quic_packet_writer_wrapper.h"
39 #include "net/tools/quic/quic_server.h"
40 #include "net/tools/quic/quic_socket_utils.h"
41 #include "net/tools/quic/quic_spdy_client_stream.h"
42 #include "net/tools/quic/test_tools/http_message.h"
43 #include "net/tools/quic/test_tools/packet_dropping_test_writer.h"
44 #include "net/tools/quic/test_tools/quic_client_peer.h"
45 #include "net/tools/quic/test_tools/quic_dispatcher_peer.h"
46 #include "net/tools/quic/test_tools/quic_in_memory_cache_peer.h"
47 #include "net/tools/quic/test_tools/quic_server_peer.h"
48 #include "net/tools/quic/test_tools/quic_test_client.h"
49 #include "net/tools/quic/test_tools/server_thread.h"
50 #include "testing/gtest/include/gtest/gtest.h"
52 using base::StringPiece;
53 using base::WaitableEvent;
54 using net::EpollServer;
55 using net::IPAddressNumber;
56 using net::test::ConstructEncryptedPacket;
57 using net::test::GenerateBody;
58 using net::test::Loopback4;
59 using net::test::MockQuicConnectionDebugVisitor;
60 using net::test::QuicConnectionPeer;
61 using net::test::QuicFlowControllerPeer;
62 using net::test::QuicSentPacketManagerPeer;
63 using net::test::QuicSessionPeer;
64 using net::test::QuicSpdySessionPeer;
65 using net::test::ReliableQuicStreamPeer;
66 using net::test::TestWriterFactory;
67 using net::test::ValueRestore;
68 using net::test::kClientDataStreamId1;
69 using net::test::kInitialSessionFlowControlWindowForTest;
70 using net::test::kInitialStreamFlowControlWindowForTest;
71 using net::tools::test::PacketDroppingTestWriter;
72 using net::tools::test::QuicDispatcherPeer;
73 using net::tools::test::QuicServerPeer;
74 using std::ostream;
75 using std::string;
76 using std::vector;
78 namespace net {
79 namespace tools {
80 namespace test {
81 namespace {
83 const char kFooResponseBody[] = "Artichoke hearts make me happy.";
84 const char kBarResponseBody[] = "Palm hearts are pretty delicious, also.";
86 // Run all tests with the cross products of all versions.
87 struct TestParams {
88 TestParams(const QuicVersionVector& client_supported_versions,
89 const QuicVersionVector& server_supported_versions,
90 QuicVersion negotiated_version,
91 bool use_fec,
92 bool client_supports_stateless_rejects,
93 bool server_uses_stateless_rejects_if_peer_supported,
94 QuicTag congestion_control_tag)
95 : client_supported_versions(client_supported_versions),
96 server_supported_versions(server_supported_versions),
97 negotiated_version(negotiated_version),
98 use_fec(use_fec),
99 client_supports_stateless_rejects(client_supports_stateless_rejects),
100 server_uses_stateless_rejects_if_peer_supported(
101 server_uses_stateless_rejects_if_peer_supported),
102 congestion_control_tag(congestion_control_tag) {}
104 friend ostream& operator<<(ostream& os, const TestParams& p) {
105 os << "{ server_supported_versions: "
106 << QuicVersionVectorToString(p.server_supported_versions);
107 os << " client_supported_versions: "
108 << QuicVersionVectorToString(p.client_supported_versions);
109 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
110 os << " client_supports_stateless_rejects: "
111 << p.client_supports_stateless_rejects;
112 os << " server_uses_stateless_rejects_if_peer_supported: "
113 << p.server_uses_stateless_rejects_if_peer_supported;
114 os << " use_fec: " << p.use_fec;
115 os << " congestion_control_tag: "
116 << QuicUtils::TagToString(p.congestion_control_tag) << " }";
117 return os;
120 QuicVersionVector client_supported_versions;
121 QuicVersionVector server_supported_versions;
122 QuicVersion negotiated_version;
123 bool use_fec;
124 bool client_supports_stateless_rejects;
125 bool server_uses_stateless_rejects_if_peer_supported;
126 QuicTag congestion_control_tag;
129 // Constructs various test permutations.
130 vector<TestParams> GetTestParams() {
131 // Divide the versions into buckets in which the intra-frame format
132 // is compatible. When clients encounter QUIC version negotiation
133 // they simply retransmit all packets using the new version's
134 // QUIC framing. However, they are unable to change the intra-frame
135 // layout (for example to change SPDY/4 headers to SPDY/3). So
136 // these tests need to ensure that clients are never attempting
137 // to do 0-RTT across incompatible versions. Chromium only supports
138 // a single version at a time anyway. :)
139 QuicVersionVector all_supported_versions = QuicSupportedVersions();
140 QuicVersionVector client_version_buckets[2];
141 for (const QuicVersion version : all_supported_versions) {
142 if (version <= QUIC_VERSION_24) {
143 // SPDY/4 compression but SPDY/3 headers
144 client_version_buckets[0].push_back(version);
145 } else {
146 // SPDY/4
147 client_version_buckets[1].push_back(version);
151 vector<TestParams> params;
152 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
153 // for (const QuicTag congestion_control_tag : {kRENO, kTBBR, kQBIC}) {
154 for (const QuicTag congestion_control_tag : {kRENO, kQBIC}) {
155 for (const bool use_fec : {false, true}) {
156 for (const QuicVersionVector& client_versions : client_version_buckets) {
157 for (bool client_supports_stateless_rejects : {true, false}) {
158 for (bool server_uses_stateless_rejects_if_peer_supported :
159 {true, false}) {
160 CHECK(!client_versions.empty());
161 // Add an entry for server and client supporting all versions.
162 params.push_back(
163 TestParams(client_versions, all_supported_versions,
164 client_versions.front(), use_fec,
165 client_supports_stateless_rejects,
166 server_uses_stateless_rejects_if_peer_supported,
167 congestion_control_tag));
169 // Test client supporting all versions and server supporting 1
170 // version. Simulate an old server and exercise version downgrade in
171 // the client. Protocol negotiation should occur. Skip the i = 0
172 // case because it is essentially the same as the default case.
173 for (const QuicVersion version : client_versions) {
174 QuicVersionVector server_supported_versions;
175 server_supported_versions.push_back(version);
176 params.push_back(
177 TestParams(client_versions, server_supported_versions,
178 server_supported_versions.front(), use_fec,
179 client_supports_stateless_rejects,
180 server_uses_stateless_rejects_if_peer_supported,
181 congestion_control_tag));
188 return params;
191 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
192 public:
193 ServerDelegate(TestWriterFactory* writer_factory,
194 QuicDispatcher* dispatcher)
195 : writer_factory_(writer_factory),
196 dispatcher_(dispatcher) {}
197 ~ServerDelegate() override {}
198 void OnPacketSent(WriteResult result) override {
199 writer_factory_->OnPacketSent(result);
201 void OnCanWrite() override { dispatcher_->OnCanWrite(); }
203 private:
204 TestWriterFactory* writer_factory_;
205 QuicDispatcher* dispatcher_;
208 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
209 public:
210 explicit ClientDelegate(QuicClient* client) : client_(client) {}
211 ~ClientDelegate() override {}
212 void OnPacketSent(WriteResult result) override {}
213 void OnCanWrite() override {
214 EpollEvent event(EPOLLOUT, false);
215 client_->OnEvent(client_->fd(), &event);
218 private:
219 QuicClient* client_;
222 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
223 protected:
224 EndToEndTest()
225 : initialized_(false),
226 server_address_(IPEndPoint(Loopback4(), 0)),
227 server_hostname_("example.com"),
228 server_started_(false),
229 strike_register_no_startup_period_(false) {
230 client_supported_versions_ = GetParam().client_supported_versions;
231 server_supported_versions_ = GetParam().server_supported_versions;
232 negotiated_version_ = GetParam().negotiated_version;
233 FLAGS_enable_quic_fec = GetParam().use_fec;
235 VLOG(1) << "Using Configuration: " << GetParam();
237 // Use different flow control windows for client/server.
238 client_config_.SetInitialStreamFlowControlWindowToSend(
239 2 * kInitialStreamFlowControlWindowForTest);
240 client_config_.SetInitialSessionFlowControlWindowToSend(
241 2 * kInitialSessionFlowControlWindowForTest);
242 server_config_.SetInitialStreamFlowControlWindowToSend(
243 3 * kInitialStreamFlowControlWindowForTest);
244 server_config_.SetInitialSessionFlowControlWindowToSend(
245 3 * kInitialSessionFlowControlWindowForTest);
247 QuicInMemoryCachePeer::ResetForTests();
248 AddToCache("/foo", 200, "OK", kFooResponseBody);
249 AddToCache("/bar", 200, "OK", kBarResponseBody);
252 ~EndToEndTest() override {
253 // TODO(rtenneti): port RecycleUnusedPort if needed.
254 // RecycleUnusedPort(server_address_.port());
255 QuicInMemoryCachePeer::ResetForTests();
258 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
259 QuicTestClient* client = new QuicTestClient(
260 server_address_, server_hostname_,
261 /*secure=*/true, client_config_, client_supported_versions_);
262 client->UseWriter(writer);
263 client->Connect();
264 return client;
267 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
268 CHECK(client_.get() == nullptr);
269 DVLOG(1) << "Setting client initial stream flow control window: " << window;
270 client_config_.SetInitialStreamFlowControlWindowToSend(window);
273 void set_client_initial_session_flow_control_receive_window(uint32 window) {
274 CHECK(client_.get() == nullptr);
275 DVLOG(1) << "Setting client initial session flow control window: "
276 << window;
277 client_config_.SetInitialSessionFlowControlWindowToSend(window);
280 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
281 CHECK(server_thread_.get() == nullptr);
282 DVLOG(1) << "Setting server initial stream flow control window: "
283 << window;
284 server_config_.SetInitialStreamFlowControlWindowToSend(window);
287 void set_server_initial_session_flow_control_receive_window(uint32 window) {
288 CHECK(server_thread_.get() == nullptr);
289 DVLOG(1) << "Setting server initial session flow control window: "
290 << window;
291 server_config_.SetInitialSessionFlowControlWindowToSend(window);
294 const QuicSentPacketManager *
295 GetSentPacketManagerFromFirstServerSession() const {
296 QuicDispatcher* dispatcher =
297 QuicServerPeer::GetDispatcher(server_thread_->server());
298 QuicSession* session = dispatcher->session_map().begin()->second;
299 return &session->connection()->sent_packet_manager();
302 bool Initialize() {
303 QuicTagVector copt;
304 server_config_.SetConnectionOptionsToSend(copt);
306 // TODO(nimia): Consider setting the congestion control algorithm for the
307 // client as well according to the test parameter.
308 copt.push_back(GetParam().congestion_control_tag);
310 if (GetParam().use_fec) {
311 // Set FEC config in client's connection options and in client session.
312 copt.push_back(kFHDR);
314 if (GetParam().client_supports_stateless_rejects) {
315 copt.push_back(kSREJ);
317 client_config_.SetConnectionOptionsToSend(copt);
319 // Start the server first, because CreateQuicClient() attempts
320 // to connect to the server.
321 StartServer();
322 client_.reset(CreateQuicClient(client_writer_));
323 if (GetParam().use_fec) {
324 // Set FecPolicy to always protect data on all streams.
325 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
327 static EpollEvent event(EPOLLOUT, false);
328 client_writer_->Initialize(
329 reinterpret_cast<QuicEpollConnectionHelper*>(
330 QuicConnectionPeer::GetHelper(
331 client_->client()->session()->connection())),
332 new ClientDelegate(client_->client()));
333 initialized_ = true;
334 return client_->client()->connected();
337 void SetUp() override {
338 // The ownership of these gets transferred to the QuicPacketWriterWrapper
339 // and TestWriterFactory when Initialize() is executed.
340 client_writer_ = new PacketDroppingTestWriter();
341 server_writer_ = new PacketDroppingTestWriter();
344 void TearDown() override {
345 ASSERT_TRUE(initialized_) << "You must call Initialize() in every test "
346 << "case. Otherwise, your test will leak memory.";
347 StopServer();
350 void StartServer() {
351 server_thread_.reset(new ServerThread(
352 new QuicServer(server_config_, server_supported_versions_),
353 /*is_secure=*/true, server_address_,
354 strike_register_no_startup_period_));
355 server_thread_->Initialize();
356 server_address_ = IPEndPoint(server_address_.address(),
357 server_thread_->GetPort());
358 QuicDispatcher* dispatcher =
359 QuicServerPeer::GetDispatcher(server_thread_->server());
360 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
361 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
362 packet_writer_factory);
363 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
365 if (GetParam().server_uses_stateless_rejects_if_peer_supported) {
366 // Enable stateless rejects and force the server to always send
367 // them.
368 FLAGS_enable_quic_stateless_reject_support = true;
369 FLAGS_quic_session_map_threshold_for_stateless_rejects = 0;
370 } else {
371 FLAGS_enable_quic_stateless_reject_support = false;
372 FLAGS_quic_session_map_threshold_for_stateless_rejects = -1;
375 server_writer_->Initialize(
376 QuicDispatcherPeer::GetHelper(dispatcher),
377 new ServerDelegate(packet_writer_factory, dispatcher));
378 server_thread_->Start();
379 server_started_ = true;
382 void StopServer() {
383 if (!server_started_)
384 return;
385 if (server_thread_.get()) {
386 server_thread_->Quit();
387 server_thread_->Join();
391 void AddToCache(StringPiece path,
392 int response_code,
393 StringPiece response_detail,
394 StringPiece body) {
395 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
396 "www.google.com", path, response_code, response_detail, body);
399 void SetPacketLossPercentage(int32 loss) {
400 // TODO(rtenneti): enable when we can do random packet loss tests in
401 // chrome's tree.
402 if (loss != 0 && loss != 100)
403 return;
404 client_writer_->set_fake_packet_loss_percentage(loss);
405 server_writer_->set_fake_packet_loss_percentage(loss);
408 void SetPacketSendDelay(QuicTime::Delta delay) {
409 // TODO(rtenneti): enable when we can do random packet send delay tests in
410 // chrome's tree.
411 // client_writer_->set_fake_packet_delay(delay);
412 // server_writer_->set_fake_packet_delay(delay);
415 void SetReorderPercentage(int32 reorder) {
416 // TODO(rtenneti): enable when we can do random packet reorder tests in
417 // chrome's tree.
418 // client_writer_->set_fake_reorder_percentage(reorder);
419 // server_writer_->set_fake_reorder_percentage(reorder);
422 // Verifies that the client and server connections were both free of packets
423 // being discarded, based on connection stats.
424 // Calls server_thread_ Pause() and Resume(), which may only be called once
425 // per test.
426 void VerifyCleanConnection(bool had_packet_loss) {
427 QuicConnectionStats client_stats =
428 client_->client()->session()->connection()->GetStats();
429 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
430 // if (!had_packet_loss) {
431 // EXPECT_EQ(0u, client_stats.packets_lost);
432 // }
433 EXPECT_EQ(0u, client_stats.packets_discarded);
434 EXPECT_EQ(0u, client_stats.packets_dropped);
435 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
437 const int num_expected_stateless_rejects =
438 (BothSidesSupportStatelessRejects() &&
439 client_->client()->session()->GetNumSentClientHellos() > 0)
441 : 0;
442 EXPECT_EQ(num_expected_stateless_rejects,
443 client_->client()->num_stateless_rejects_received());
445 server_thread_->Pause();
446 QuicDispatcher* dispatcher =
447 QuicServerPeer::GetDispatcher(server_thread_->server());
448 ASSERT_EQ(1u, dispatcher->session_map().size());
449 QuicSession* session = dispatcher->session_map().begin()->second;
450 QuicConnectionStats server_stats = session->connection()->GetStats();
451 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
452 // if (!had_packet_loss) {
453 // EXPECT_EQ(0u, server_stats.packets_lost);
454 // }
455 EXPECT_EQ(0u, server_stats.packets_discarded);
456 // TODO(ianswett): Restore the check for packets_dropped equals 0.
457 // The expect for packets received is equal to packets processed fails
458 // due to version negotiation packets.
459 server_thread_->Resume();
462 bool BothSidesSupportStatelessRejects() {
463 return (GetParam().server_uses_stateless_rejects_if_peer_supported &&
464 GetParam().client_supports_stateless_rejects);
467 bool initialized_;
468 IPEndPoint server_address_;
469 string server_hostname_;
470 scoped_ptr<ServerThread> server_thread_;
471 scoped_ptr<QuicTestClient> client_;
472 PacketDroppingTestWriter* client_writer_;
473 PacketDroppingTestWriter* server_writer_;
474 bool server_started_;
475 QuicConfig client_config_;
476 QuicConfig server_config_;
477 QuicVersionVector client_supported_versions_;
478 QuicVersionVector server_supported_versions_;
479 QuicVersion negotiated_version_;
480 bool strike_register_no_startup_period_;
483 // Run all end to end tests with all supported versions.
484 INSTANTIATE_TEST_CASE_P(EndToEndTests,
485 EndToEndTest,
486 ::testing::ValuesIn(GetTestParams()));
488 TEST_P(EndToEndTest, SimpleRequestResponse) {
489 ASSERT_TRUE(Initialize());
491 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
492 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
495 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
496 // try bots) and selectively disable this test.
497 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
498 IPAddressNumber ip;
499 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
500 server_address_ = IPEndPoint(ip, server_address_.port());
501 ASSERT_TRUE(Initialize());
503 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
504 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
507 TEST_P(EndToEndTest, SeparateFinPacket) {
508 ASSERT_TRUE(Initialize());
510 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
511 request.set_has_complete_message(false);
513 // Send a request in two parts: the request and then an empty packet with FIN.
514 client_->SendMessage(request);
515 client_->SendData("", true);
516 client_->WaitForResponse();
517 EXPECT_EQ(kFooResponseBody, client_->response_body());
518 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
520 // Now do the same thing but with a content length.
521 request.AddBody("foo", true);
522 client_->SendMessage(request);
523 client_->SendData("", true);
524 client_->WaitForResponse();
525 EXPECT_EQ(kFooResponseBody, client_->response_body());
526 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
529 TEST_P(EndToEndTest, MultipleRequestResponse) {
530 ASSERT_TRUE(Initialize());
532 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
533 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
534 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
535 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
538 TEST_P(EndToEndTest, MultipleClients) {
539 ASSERT_TRUE(Initialize());
540 scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
542 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
543 request.AddHeader("content-length", "3");
544 request.set_has_complete_message(false);
546 client_->SendMessage(request);
547 client2->SendMessage(request);
549 client_->SendData("bar", true);
550 client_->WaitForResponse();
551 EXPECT_EQ(kFooResponseBody, client_->response_body());
552 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
554 client2->SendData("eep", true);
555 client2->WaitForResponse();
556 EXPECT_EQ(kFooResponseBody, client2->response_body());
557 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
560 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
561 // Send a large enough request to guarantee fragmentation.
562 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
563 AddToCache(huge_request, 200, "OK", kBarResponseBody);
565 ASSERT_TRUE(Initialize());
567 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
568 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
571 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
572 // Send a large enough request to guarantee fragmentation.
573 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
574 AddToCache(huge_request, 200, "OK", kBarResponseBody);
576 ASSERT_TRUE(Initialize());
577 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
578 SetReorderPercentage(50);
580 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
581 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
584 TEST_P(EndToEndTest, PostMissingBytes) {
585 ASSERT_TRUE(Initialize());
587 // Add a content length header with no body.
588 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
589 request.AddHeader("content-length", "3");
590 request.set_skip_message_validation(true);
592 // This should be detected as stream fin without complete request,
593 // triggering an error response.
594 client_->SendCustomSynchronousRequest(request);
595 EXPECT_EQ("bad", client_->response_body());
596 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
599 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
600 // http://crbug.com/297040.
601 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
602 ASSERT_TRUE(Initialize());
604 client_->client()->WaitForCryptoHandshakeConfirmed();
606 // 1 MB body.
607 string body;
608 GenerateBody(&body, 1024 * 1024);
610 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
611 request.AddBody(body, true);
613 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
614 VerifyCleanConnection(false);
617 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
618 ASSERT_TRUE(Initialize());
619 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
621 client_->client()->WaitForCryptoHandshakeConfirmed();
623 // 100 KB body.
624 string body;
625 GenerateBody(&body, 100 * 1024);
627 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
628 request.AddBody(body, true);
630 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
631 VerifyCleanConnection(false);
634 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
635 if (!BothSidesSupportStatelessRejects()) {
636 // Connect with lower fake packet loss than we'd like to test.
637 // Until b/10126687 is fixed, losing handshake packets is pretty
638 // brutal.
639 // TODO(jokulik): Until we support redundant SREJ packets, don't
640 // drop handshake packets for stateless rejects.
641 SetPacketLossPercentage(5);
643 ASSERT_TRUE(Initialize());
645 // Wait for the server SHLO before upping the packet loss.
646 client_->client()->WaitForCryptoHandshakeConfirmed();
647 SetPacketLossPercentage(30);
649 // 10 KB body.
650 string body;
651 GenerateBody(&body, 1024 * 10);
653 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
654 request.AddBody(body, true);
656 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
657 VerifyCleanConnection(true);
660 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
661 if (!BothSidesSupportStatelessRejects()) {
662 // Connect with lower fake packet loss than we'd like to test. Until
663 // b/10126687 is fixed, losing handshake packets is pretty brutal.
664 // TODO(jokulik): Until we support redundant SREJ packets, don't
665 // drop handshake packets for stateless rejects.
666 SetPacketLossPercentage(5);
668 ASSERT_TRUE(Initialize());
670 // Wait for the server SHLO before upping the packet loss.
671 client_->client()->WaitForCryptoHandshakeConfirmed();
672 SetPacketLossPercentage(10);
673 client_writer_->set_fake_blocked_socket_percentage(10);
675 // 10 KB body.
676 string body;
677 GenerateBody(&body, 1024 * 10);
679 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
680 request.AddBody(body, true);
682 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
685 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
686 ASSERT_TRUE(Initialize());
688 client_->client()->WaitForCryptoHandshakeConfirmed();
689 // Both of these must be called when the writer is not actively used.
690 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
691 SetReorderPercentage(30);
693 // 1 MB body.
694 string body;
695 GenerateBody(&body, 1024 * 1024);
697 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
698 request.AddBody(body, true);
700 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
703 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
704 // Have the server accept 0-RTT without waiting a startup period.
705 strike_register_no_startup_period_ = true;
707 // Send a request and then disconnect. This prepares the client to attempt
708 // a 0-RTT handshake for the next request.
709 ASSERT_TRUE(Initialize());
711 string body;
712 GenerateBody(&body, 20480);
714 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
715 request.AddBody(body, true);
717 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
718 // In the non-stateless case, the same session is used for both
719 // hellos, so the number of hellos sent on that session is 2. In
720 // the stateless case, the first client session will be completely
721 // torn down after the reject. The number of hellos on the latest
722 // session is 1.
723 const int expected_num_hellos_latest_session =
724 BothSidesSupportStatelessRejects() ? 1 : 2;
725 EXPECT_EQ(expected_num_hellos_latest_session,
726 client_->client()->session()->GetNumSentClientHellos());
727 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
729 client_->Disconnect();
731 // The 0-RTT handshake should succeed.
732 client_->Connect();
733 client_->WaitForResponseForMs(-1);
734 ASSERT_TRUE(client_->client()->connected());
735 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
736 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
737 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
739 client_->Disconnect();
741 // Restart the server so that the 0-RTT handshake will take 1 RTT.
742 StopServer();
743 server_writer_ = new PacketDroppingTestWriter();
744 StartServer();
746 client_->Connect();
747 ASSERT_TRUE(client_->client()->connected());
748 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
749 // In the non-stateless case, the same session is used for both
750 // hellos, so the number of hellos sent on that session is 2. In
751 // the stateless case, the first client session will be completely
752 // torn down after the reject. The number of hellos sent on the
753 // latest session is 1.
754 EXPECT_EQ(expected_num_hellos_latest_session,
755 client_->client()->session()->GetNumSentClientHellos());
756 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
758 VerifyCleanConnection(false);
761 TEST_P(EndToEndTest, SynchronousRequestZeroRTTFailure) {
762 // Have the server accept 0-RTT without waiting a startup period.
763 strike_register_no_startup_period_ = true;
765 // Send a request and then disconnect. This prepares the client to attempt
766 // a 0-RTT handshake for the next request.
767 ASSERT_TRUE(Initialize());
769 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
770 // In the non-stateless case, the same session is used for both
771 // hellos, so the number of hellos sent on that session is 2. In
772 // the stateless case, the first client session will be completely
773 // torn down after the reject. The number of hellos on that second
774 // latest session is 1.
775 const int expected_num_hellos_latest_session =
776 BothSidesSupportStatelessRejects() ? 1 : 2;
777 EXPECT_EQ(expected_num_hellos_latest_session,
778 client_->client()->session()->GetNumSentClientHellos());
779 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
781 client_->Disconnect();
783 // The 0-RTT handshake should succeed.
784 client_->Connect();
785 client_->WaitForInitialResponse();
786 ASSERT_TRUE(client_->client()->connected());
787 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
788 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
789 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
791 client_->Disconnect();
793 // Restart the server so that the 0-RTT handshake will take 1 RTT.
794 StopServer();
795 server_writer_ = new PacketDroppingTestWriter();
796 StartServer();
798 client_->Connect();
799 ASSERT_TRUE(client_->client()->connected());
800 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
801 // In the non-stateless case, the same session is used for both
802 // hellos, so the number of hellos sent on that session is 2. In
803 // the stateless case, the first client session will be completely
804 // torn down after the reject. The number of hellos sent on the
805 // latest session is 1.
806 EXPECT_EQ(expected_num_hellos_latest_session,
807 client_->client()->session()->GetNumSentClientHellos());
808 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
810 VerifyCleanConnection(false);
813 TEST_P(EndToEndTest, LargePostSynchronousRequest) {
814 // Have the server accept 0-RTT without waiting a startup period.
815 strike_register_no_startup_period_ = true;
817 // Send a request and then disconnect. This prepares the client to attempt
818 // a 0-RTT handshake for the next request.
819 ASSERT_TRUE(Initialize());
821 string body;
822 GenerateBody(&body, 20480);
824 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
825 request.AddBody(body, true);
827 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
828 // In the non-stateless case, the same session is used for both
829 // hellos, so the number of hellos sent on that session is 2. In
830 // the stateless case, the first client session will be completely
831 // torn down after the reject. The number of hellos on the latest
832 // session is 1.
833 const int expected_num_hellos_latest_session =
834 BothSidesSupportStatelessRejects() ? 1 : 2;
835 EXPECT_EQ(expected_num_hellos_latest_session,
836 client_->client()->session()->GetNumSentClientHellos());
837 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
839 client_->Disconnect();
841 // The 0-RTT handshake should succeed.
842 client_->Connect();
843 client_->WaitForInitialResponse();
844 ASSERT_TRUE(client_->client()->connected());
845 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
846 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
847 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
849 client_->Disconnect();
851 // Restart the server so that the 0-RTT handshake will take 1 RTT.
852 StopServer();
853 server_writer_ = new PacketDroppingTestWriter();
854 StartServer();
856 client_->Connect();
857 ASSERT_TRUE(client_->client()->connected());
858 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
859 // In the non-stateless case, the same session is used for both
860 // hellos, so the number of hellos sent on that session is 2. In
861 // the stateless case, the first client session will be completely
862 // torn down after the reject. The number of hellos sent on the
863 // latest session is 1.
864 EXPECT_EQ(expected_num_hellos_latest_session,
865 client_->client()->session()->GetNumSentClientHellos());
866 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
868 VerifyCleanConnection(false);
871 TEST_P(EndToEndTest, StatelessRejectWithPacketLoss) {
872 // In this test, we intentionally drop the first packet from the
873 // server, which corresponds with the initial REJ/SREJ response from
874 // the server. The REJ case will succeed, due to redundancy in the
875 // stateful handshake. The SREJ will fail, because there is
876 // (currently) no way to recover from a loss of the first SREJ, and
877 // all remaining state for the first handshake is black-holed on the
878 // time-wait list.
879 // TODO(jokulik): Once redundant SREJ support is added, this test
880 // should succeed.
881 server_writer_->set_fake_drop_first_n_packets(1);
882 ASSERT_EQ(!BothSidesSupportStatelessRejects(), Initialize());
885 TEST_P(EndToEndTest, SetInitialReceivedConnectionOptions) {
886 QuicTagVector initial_received_options;
887 initial_received_options.push_back(kTBBR);
888 initial_received_options.push_back(kIW10);
889 initial_received_options.push_back(kPRST);
890 EXPECT_TRUE(server_config_.SetInitialReceivedConnectionOptions(
891 initial_received_options));
893 ASSERT_TRUE(Initialize());
894 client_->client()->WaitForCryptoHandshakeConfirmed();
895 server_thread_->WaitForCryptoHandshakeConfirmed();
897 EXPECT_FALSE(server_config_.SetInitialReceivedConnectionOptions(
898 initial_received_options));
900 // Verify that server's configuration is correct.
901 server_thread_->Pause();
902 EXPECT_TRUE(server_config_.HasReceivedConnectionOptions());
903 EXPECT_TRUE(
904 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kTBBR));
905 EXPECT_TRUE(
906 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kIW10));
907 EXPECT_TRUE(
908 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kPRST));
911 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
912 ASSERT_TRUE(Initialize());
913 client_->client()->WaitForCryptoHandshakeConfirmed();
914 server_thread_->WaitForCryptoHandshakeConfirmed();
916 FecPolicy expected_policy =
917 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
919 // Verify that server's FEC configuration is correct.
920 server_thread_->Pause();
921 QuicDispatcher* dispatcher =
922 QuicServerPeer::GetDispatcher(server_thread_->server());
923 ASSERT_EQ(1u, dispatcher->session_map().size());
924 QuicSpdySession* session = dispatcher->session_map().begin()->second;
925 EXPECT_EQ(expected_policy,
926 QuicSpdySessionPeer::GetHeadersStream(session)->fec_policy());
927 server_thread_->Resume();
929 // Verify that client's FEC configuration is correct.
930 EXPECT_EQ(expected_policy, QuicSpdySessionPeer::GetHeadersStream(
931 client_->client()->session())->fec_policy());
932 EXPECT_EQ(expected_policy,
933 client_->GetOrCreateStream()->fec_policy());
936 TEST_P(EndToEndTest, LargePostSmallBandwidthLargeBuffer) {
937 ASSERT_TRUE(Initialize());
938 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
939 // 256KB per second with a 256KB buffer from server to client. Wireless
940 // clients commonly have larger buffers, but our max CWND is 200.
941 server_writer_->set_max_bandwidth_and_buffer_size(
942 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
944 client_->client()->WaitForCryptoHandshakeConfirmed();
946 // 1 MB body.
947 string body;
948 GenerateBody(&body, 1024 * 1024);
950 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
951 request.AddBody(body, true);
953 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
954 // This connection will not drop packets, because the buffer size is larger
955 // than the default receive window.
956 VerifyCleanConnection(false);
959 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
960 // Regression test for b/14677858.
961 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
962 // if currently connection level flow control blocked. If set, this results in
963 // an infinite loop in the EpollServer, as the alarm fires and is immediately
964 // rescheduled.
965 ASSERT_TRUE(Initialize());
966 client_->client()->WaitForCryptoHandshakeConfirmed();
968 // Ensure both stream and connection level are flow control blocked by setting
969 // the send window offset to 0.
970 const uint64 flow_control_window =
971 server_config_.GetInitialStreamFlowControlWindowToSend();
972 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
973 QuicSession* session = client_->client()->session();
974 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
975 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
976 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
977 EXPECT_TRUE(session->flow_controller()->IsBlocked());
979 // Make sure that the stream has data pending so that it will be marked as
980 // write blocked when it receives a stream level WINDOW_UPDATE.
981 stream->SendBody("hello", false);
983 // The stream now attempts to write, fails because it is still connection
984 // level flow control blocked, and is added to the write blocked list.
985 QuicWindowUpdateFrame window_update(stream->id(), 2 * flow_control_window);
986 stream->OnWindowUpdateFrame(window_update);
988 // Prior to fixing b/14677858 this call would result in an infinite loop in
989 // Chromium. As a proxy for detecting this, we now check whether the
990 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
991 // connection is still flow control blocked.
992 session->connection()->OnCanWrite();
994 QuicAlarm* resume_writes_alarm =
995 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
996 EXPECT_FALSE(resume_writes_alarm->IsSet());
999 TEST_P(EndToEndTest, InvalidStream) {
1000 ASSERT_TRUE(Initialize());
1001 client_->client()->WaitForCryptoHandshakeConfirmed();
1003 string body;
1004 GenerateBody(&body, kMaxPacketSize);
1006 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1007 request.AddBody(body, true);
1008 // Force the client to write with a stream ID belonging to a nonexistent
1009 // server-side stream.
1010 QuicSessionPeer::SetNextStreamId(client_->client()->session(), 2);
1012 client_->SendCustomSynchronousRequest(request);
1013 // EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1014 EXPECT_EQ(QUIC_PACKET_FOR_NONEXISTENT_STREAM, client_->connection_error());
1017 // TODO(rch): this test seems to cause net_unittests timeouts :|
1018 TEST_P(EndToEndTest, DISABLED_MultipleTermination) {
1019 ASSERT_TRUE(Initialize());
1021 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1022 request.AddHeader("content-length", "3");
1023 request.set_has_complete_message(false);
1025 // Set the offset so we won't frame. Otherwise when we pick up termination
1026 // before HTTP framing is complete, we send an error and close the stream,
1027 // and the second write is picked up as writing on a closed stream.
1028 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1029 ASSERT_TRUE(stream != nullptr);
1030 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
1032 client_->SendData("bar", true);
1033 client_->WaitForWriteToFlush();
1035 // By default the stream protects itself from writes after terminte is set.
1036 // Override this to test the server handling buggy clients.
1037 ReliableQuicStreamPeer::SetWriteSideClosed(
1038 false, client_->GetOrCreateStream());
1040 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
1043 TEST_P(EndToEndTest, Timeout) {
1044 client_config_.SetIdleConnectionStateLifetime(
1045 QuicTime::Delta::FromMicroseconds(500),
1046 QuicTime::Delta::FromMicroseconds(500));
1047 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
1048 // that's enough to validate timeout in this case.
1049 Initialize();
1050 while (client_->client()->connected()) {
1051 client_->client()->WaitForEvents();
1055 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
1056 // Negotiate 1 max open stream.
1057 client_config_.SetMaxStreamsPerConnection(1, 1);
1058 ASSERT_TRUE(Initialize());
1059 client_->client()->WaitForCryptoHandshakeConfirmed();
1061 // Make the client misbehave after negotiation.
1062 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
1063 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(),
1064 kServerMaxStreams + 1);
1066 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1067 request.AddHeader("content-length", "3");
1068 request.set_has_complete_message(false);
1070 // The server supports a small number of additional streams beyond the
1071 // negotiated limit. Open enough streams to go beyond that limit.
1072 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
1073 client_->SendMessage(request);
1075 client_->WaitForResponse();
1077 EXPECT_FALSE(client_->connected());
1078 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1079 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
1082 TEST_P(EndToEndTest, NegotiateCongestionControl) {
1083 ValueRestore<bool> old_flag(&FLAGS_quic_allow_bbr, true);
1084 ASSERT_TRUE(Initialize());
1085 client_->client()->WaitForCryptoHandshakeConfirmed();
1087 CongestionControlType expected_congestion_control_type = kReno;
1088 switch (GetParam().congestion_control_tag) {
1089 case kRENO:
1090 expected_congestion_control_type = kReno;
1091 break;
1092 case kTBBR:
1093 expected_congestion_control_type = kBBR;
1094 break;
1095 case kQBIC:
1096 expected_congestion_control_type = kCubic;
1097 break;
1098 default:
1099 DLOG(FATAL) << "Unexpected congestion control tag";
1102 EXPECT_EQ(expected_congestion_control_type,
1103 QuicSentPacketManagerPeer::GetSendAlgorithm(
1104 *GetSentPacketManagerFromFirstServerSession())
1105 ->GetCongestionControlType());
1108 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
1109 // Server limits the number of max streams to 2.
1110 server_config_.SetMaxStreamsPerConnection(2, 2);
1111 // Client tries to negotiate for 10.
1112 client_config_.SetMaxStreamsPerConnection(10, 5);
1114 ASSERT_TRUE(Initialize());
1115 client_->client()->WaitForCryptoHandshakeConfirmed();
1116 QuicConfig* client_negotiated_config = client_->client()->session()->config();
1117 EXPECT_EQ(2u, client_negotiated_config->MaxStreamsPerConnection());
1120 TEST_P(EndToEndTest, ClientSuggestsRTT) {
1121 // Client suggests initial RTT, verify it is used.
1122 const uint32 kInitialRTT = 20000;
1123 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT);
1125 ASSERT_TRUE(Initialize());
1126 client_->client()->WaitForCryptoHandshakeConfirmed();
1127 server_thread_->WaitForCryptoHandshakeConfirmed();
1129 // Pause the server so we can access the server's internals without races.
1130 server_thread_->Pause();
1131 QuicDispatcher* dispatcher =
1132 QuicServerPeer::GetDispatcher(server_thread_->server());
1133 ASSERT_EQ(1u, dispatcher->session_map().size());
1134 const QuicSentPacketManager& client_sent_packet_manager =
1135 client_->client()->session()->connection()->sent_packet_manager();
1136 const QuicSentPacketManager& server_sent_packet_manager =
1137 *GetSentPacketManagerFromFirstServerSession();
1139 EXPECT_EQ(kInitialRTT,
1140 client_sent_packet_manager.GetRttStats()->initial_rtt_us());
1141 EXPECT_EQ(kInitialRTT,
1142 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1143 server_thread_->Resume();
1146 TEST_P(EndToEndTest, MaxInitialRTT) {
1147 // Client tries to suggest twice the server's max initial rtt and the server
1148 // uses the max.
1149 client_config_.SetInitialRoundTripTimeUsToSend(
1150 2 * kMaxInitialRoundTripTimeUs);
1152 ASSERT_TRUE(Initialize());
1153 client_->client()->WaitForCryptoHandshakeConfirmed();
1154 server_thread_->WaitForCryptoHandshakeConfirmed();
1156 // Pause the server so we can access the server's internals without races.
1157 server_thread_->Pause();
1158 QuicDispatcher* dispatcher =
1159 QuicServerPeer::GetDispatcher(server_thread_->server());
1160 ASSERT_EQ(1u, dispatcher->session_map().size());
1161 QuicSession* session = dispatcher->session_map().begin()->second;
1162 const QuicSentPacketManager& client_sent_packet_manager =
1163 client_->client()->session()->connection()->sent_packet_manager();
1165 // Now that acks have been exchanged, the RTT estimate has decreased on the
1166 // server and is not infinite on the client.
1167 EXPECT_FALSE(
1168 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
1169 const RttStats& server_rtt_stats =
1170 *session->connection()->sent_packet_manager().GetRttStats();
1171 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
1172 server_rtt_stats.initial_rtt_us());
1173 EXPECT_GE(static_cast<int64>(kMaxInitialRoundTripTimeUs),
1174 server_rtt_stats.smoothed_rtt().ToMicroseconds());
1175 server_thread_->Resume();
1178 TEST_P(EndToEndTest, MinInitialRTT) {
1179 // Client tries to suggest 0 and the server uses the default.
1180 client_config_.SetInitialRoundTripTimeUsToSend(0);
1182 ASSERT_TRUE(Initialize());
1183 client_->client()->WaitForCryptoHandshakeConfirmed();
1184 server_thread_->WaitForCryptoHandshakeConfirmed();
1186 // Pause the server so we can access the server's internals without races.
1187 server_thread_->Pause();
1188 QuicDispatcher* dispatcher =
1189 QuicServerPeer::GetDispatcher(server_thread_->server());
1190 ASSERT_EQ(1u, dispatcher->session_map().size());
1191 QuicSession* session = dispatcher->session_map().begin()->second;
1192 const QuicSentPacketManager& client_sent_packet_manager =
1193 client_->client()->session()->connection()->sent_packet_manager();
1194 const QuicSentPacketManager& server_sent_packet_manager =
1195 session->connection()->sent_packet_manager();
1197 // Now that acks have been exchanged, the RTT estimate has decreased on the
1198 // server and is not infinite on the client.
1199 EXPECT_FALSE(
1200 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
1201 // Expect the default rtt of 100ms.
1202 EXPECT_EQ(static_cast<int64>(100 * kNumMicrosPerMilli),
1203 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1204 // Ensure the bandwidth is valid.
1205 client_sent_packet_manager.BandwidthEstimate();
1206 server_sent_packet_manager.BandwidthEstimate();
1207 server_thread_->Resume();
1210 TEST_P(EndToEndTest, 0ByteConnectionId) {
1211 client_config_.SetBytesForConnectionIdToSend(0);
1212 ASSERT_TRUE(Initialize());
1214 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1215 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1217 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1218 client_->client()->session()->connection());
1219 EXPECT_EQ(PACKET_0BYTE_CONNECTION_ID,
1220 header->public_header.connection_id_length);
1223 TEST_P(EndToEndTest, 1ByteConnectionId) {
1224 client_config_.SetBytesForConnectionIdToSend(1);
1225 ASSERT_TRUE(Initialize());
1227 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1228 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1229 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1230 client_->client()->session()->connection());
1231 EXPECT_EQ(PACKET_1BYTE_CONNECTION_ID,
1232 header->public_header.connection_id_length);
1235 TEST_P(EndToEndTest, 4ByteConnectionId) {
1236 client_config_.SetBytesForConnectionIdToSend(4);
1237 ASSERT_TRUE(Initialize());
1239 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1240 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1241 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1242 client_->client()->session()->connection());
1243 EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID,
1244 header->public_header.connection_id_length);
1247 TEST_P(EndToEndTest, 8ByteConnectionId) {
1248 client_config_.SetBytesForConnectionIdToSend(8);
1249 ASSERT_TRUE(Initialize());
1251 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1252 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1253 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1254 client_->client()->session()->connection());
1255 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1256 header->public_header.connection_id_length);
1259 TEST_P(EndToEndTest, 15ByteConnectionId) {
1260 client_config_.SetBytesForConnectionIdToSend(15);
1261 ASSERT_TRUE(Initialize());
1263 // Our server is permissive and allows for out of bounds values.
1264 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1265 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1266 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1267 client_->client()->session()->connection());
1268 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1269 header->public_header.connection_id_length);
1272 TEST_P(EndToEndTest, ResetConnection) {
1273 ASSERT_TRUE(Initialize());
1274 client_->client()->WaitForCryptoHandshakeConfirmed();
1276 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1277 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1278 client_->ResetConnection();
1279 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1280 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1283 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1284 if (!BothSidesSupportStatelessRejects()) {
1285 // Connect with lower fake packet loss than we'd like to test. Until
1286 // b/10126687 is fixed, losing handshake packets is pretty brutal.
1287 // TODO(jokulik): Until we support redundant SREJ packets, don't
1288 // drop handshake packets for stateless rejects.
1289 SetPacketLossPercentage(1);
1291 ASSERT_TRUE(Initialize());
1292 string large_body;
1293 GenerateBody(&large_body, 10240);
1294 int max_streams = 100;
1296 AddToCache("/large_response", 200, "OK", large_body);;
1298 client_->client()->WaitForCryptoHandshakeConfirmed();
1299 SetPacketLossPercentage(10);
1301 for (int i = 0; i < max_streams; ++i) {
1302 EXPECT_LT(0, client_->SendRequest("/large_response"));
1305 // WaitForEvents waits 50ms and returns true if there are outstanding
1306 // requests.
1307 while (client_->client()->WaitForEvents() == true) {
1311 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1312 ASSERT_TRUE(Initialize());
1313 string small_body;
1314 GenerateBody(&small_body, 256);
1316 AddToCache("/small_response", 200, "OK", small_body);
1318 client_->client()->WaitForCryptoHandshakeConfirmed();
1320 QuicSession* session = client_->client()->session();
1321 // Lose the request.
1322 SetPacketLossPercentage(100);
1323 EXPECT_LT(0, client_->SendRequest("/small_response"));
1324 client_->client()->WaitForEvents();
1325 // Transmit the cancel, and ensure the connection is torn down properly.
1326 SetPacketLossPercentage(0);
1327 QuicStreamId stream_id = kClientDataStreamId1;
1328 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1330 // WaitForEvents waits 50ms and returns true if there are outstanding
1331 // requests.
1332 while (client_->client()->WaitForEvents() == true) {
1334 // It should be completely fine to RST a stream before any data has been
1335 // received for that stream.
1336 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1339 class WrongAddressWriter : public QuicPacketWriterWrapper {
1340 public:
1341 WrongAddressWriter() {
1342 IPAddressNumber ip;
1343 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1344 self_address_ = IPEndPoint(ip, 0);
1347 WriteResult WritePacket(const char* buffer,
1348 size_t buf_len,
1349 const IPAddressNumber& real_self_address,
1350 const IPEndPoint& peer_address) override {
1351 // Use wrong address!
1352 return QuicPacketWriterWrapper::WritePacket(
1353 buffer, buf_len, self_address_.address(), peer_address);
1356 bool IsWriteBlockedDataBuffered() const override { return false; }
1358 IPEndPoint self_address_;
1361 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1362 ASSERT_TRUE(Initialize());
1364 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1365 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1367 // Store the client IP address which was used to send the first request.
1368 IPAddressNumber old_host = client_->client()->client_address().address();
1370 // Migrate socket to the new IP address.
1371 IPAddressNumber new_host;
1372 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &new_host));
1373 EXPECT_NE(old_host, new_host);
1374 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
1376 // Send a request using the new socket.
1377 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1378 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1381 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1382 // Tests that the client's port can change during an established QUIC
1383 // connection, and that doing so does not result in the connection being
1384 // closed by the server.
1385 ASSERT_TRUE(Initialize());
1387 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1388 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1390 // Store the client address which was used to send the first request.
1391 IPEndPoint old_address = client_->client()->client_address();
1393 // Stop listening on the old FD.
1394 EpollServer* eps = client_->epoll_server();
1395 int old_fd = client_->client()->fd();
1396 eps->UnregisterFD(old_fd);
1397 // Create a new socket before closing the old one, which will result in a new
1398 // ephemeral port.
1399 QuicClientPeer::CreateUDPSocket(client_->client());
1400 close(old_fd);
1402 // The packet writer needs to be updated to use the new FD.
1403 client_->client()->CreateQuicPacketWriter();
1405 // Change the internal state of the client and connection to use the new port,
1406 // this is done because in a real NAT rebinding the client wouldn't see any
1407 // port change, and so expects no change to incoming port.
1408 // This is kind of ugly, but needed as we are simply swapping out the client
1409 // FD rather than any more complex NAT rebinding simulation.
1410 int new_port = client_->client()->client_address().port();
1411 QuicClientPeer::SetClientPort(client_->client(), new_port);
1412 QuicConnectionPeer::SetSelfAddress(
1413 client_->client()->session()->connection(),
1414 IPEndPoint(
1415 client_->client()->session()->connection()->self_address().address(),
1416 new_port));
1418 // Register the new FD for epoll events.
1419 int new_fd = client_->client()->fd();
1420 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1422 // Send a second request, using the new FD.
1423 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1424 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1426 // Verify that the client's ephemeral port is different.
1427 IPEndPoint new_address = client_->client()->client_address();
1428 EXPECT_EQ(old_address.address(), new_address.address());
1429 EXPECT_NE(old_address.port(), new_address.port());
1432 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
1433 // Client and server can set different initial flow control receive windows.
1434 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1435 // in the crypto handshake.
1436 const uint32 kClientStreamIFCW = 123456;
1437 const uint32 kClientSessionIFCW = 234567;
1438 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1439 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1441 const uint32 kServerStreamIFCW = 654321;
1442 const uint32 kServerSessionIFCW = 765432;
1443 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1444 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1446 ASSERT_TRUE(Initialize());
1448 // Values are exchanged during crypto handshake, so wait for that to finish.
1449 client_->client()->WaitForCryptoHandshakeConfirmed();
1450 server_thread_->WaitForCryptoHandshakeConfirmed();
1452 // Open a data stream to make sure the stream level flow control is updated.
1453 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1454 stream->SendBody("hello", false);
1456 // Client should have the right values for server's receive window.
1457 EXPECT_EQ(kServerStreamIFCW,
1458 client_->client()
1459 ->session()
1460 ->config()
1461 ->ReceivedInitialStreamFlowControlWindowBytes());
1462 EXPECT_EQ(kServerSessionIFCW,
1463 client_->client()
1464 ->session()
1465 ->config()
1466 ->ReceivedInitialSessionFlowControlWindowBytes());
1467 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1468 stream->flow_controller()));
1469 EXPECT_EQ(kServerSessionIFCW,
1470 QuicFlowControllerPeer::SendWindowOffset(
1471 client_->client()->session()->flow_controller()));
1473 // Server should have the right values for client's receive window.
1474 server_thread_->Pause();
1475 QuicDispatcher* dispatcher =
1476 QuicServerPeer::GetDispatcher(server_thread_->server());
1477 QuicSession* session = dispatcher->session_map().begin()->second;
1478 EXPECT_EQ(kClientStreamIFCW,
1479 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1480 EXPECT_EQ(kClientSessionIFCW,
1481 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1482 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1483 session->flow_controller()));
1484 server_thread_->Resume();
1487 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1488 // The special headers and crypto streams should be subject to per-stream flow
1489 // control limits, but should not be subject to connection level flow control.
1490 const uint32 kStreamIFCW = 123456;
1491 const uint32 kSessionIFCW = 234567;
1492 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
1493 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
1494 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
1495 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
1497 ASSERT_TRUE(Initialize());
1499 // Wait for crypto handshake to finish. This should have contributed to the
1500 // crypto stream flow control window, but not affected the session flow
1501 // control window.
1502 client_->client()->WaitForCryptoHandshakeConfirmed();
1503 server_thread_->WaitForCryptoHandshakeConfirmed();
1505 QuicCryptoStream* crypto_stream =
1506 QuicSessionPeer::GetCryptoStream(client_->client()->session());
1507 EXPECT_LT(
1508 QuicFlowControllerPeer::SendWindowSize(crypto_stream->flow_controller()),
1509 kStreamIFCW);
1510 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1511 client_->client()->session()->flow_controller()));
1513 // Send a request with no body, and verify that the connection level window
1514 // has not been affected.
1515 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1517 QuicHeadersStream* headers_stream =
1518 QuicSpdySessionPeer::GetHeadersStream(client_->client()->session());
1519 EXPECT_LT(
1520 QuicFlowControllerPeer::SendWindowSize(headers_stream->flow_controller()),
1521 kStreamIFCW);
1522 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1523 client_->client()->session()->flow_controller()));
1525 // Server should be in a similar state: connection flow control window should
1526 // not have any bytes marked as received.
1527 server_thread_->Pause();
1528 QuicDispatcher* dispatcher =
1529 QuicServerPeer::GetDispatcher(server_thread_->server());
1530 QuicSession* session = dispatcher->session_map().begin()->second;
1531 QuicFlowController* server_connection_flow_controller =
1532 session->flow_controller();
1533 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
1534 server_connection_flow_controller));
1535 server_thread_->Resume();
1538 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1539 // A stream created on receipt of a simple request with no body will never get
1540 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1541 // the locally closed streams map: it will never be removed if so.
1542 ASSERT_TRUE(Initialize());
1544 // Send a simple headers only request, and receive response.
1545 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1546 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1548 // Now verify that the server is not waiting for a final FIN or RST.
1549 server_thread_->Pause();
1550 QuicDispatcher* dispatcher =
1551 QuicServerPeer::GetDispatcher(server_thread_->server());
1552 QuicSession* session = dispatcher->session_map().begin()->second;
1553 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1554 session).size());
1555 server_thread_->Resume();
1558 // A TestAckNotifierDelegate verifies that its OnAckNotification method has been
1559 // called exactly once on destruction.
1560 class TestAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
1561 public:
1562 TestAckNotifierDelegate() {}
1564 void OnAckNotification(int /*num_retransmitted_packets*/,
1565 int /*num_retransmitted_bytes*/,
1566 QuicTime::Delta /*delta_largest_observed*/) override {
1567 ASSERT_FALSE(has_been_notified_);
1568 has_been_notified_ = true;
1571 bool has_been_notified() const { return has_been_notified_; }
1573 protected:
1574 // Object is ref counted.
1575 ~TestAckNotifierDelegate() override { EXPECT_TRUE(has_been_notified_); }
1577 private:
1578 bool has_been_notified_ = false;
1581 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
1582 // Verify that even in the presence of packet loss and occasionally blocked
1583 // socket, an AckNotifierDelegate will get informed that the data it is
1584 // interested in has been ACKed. This tests end-to-end ACK notification, and
1585 // demonstrates that retransmissions do not break this functionality.
1586 if (!BothSidesSupportStatelessRejects()) {
1587 // TODO(jokulik): Until we support redundant SREJ packets, don't
1588 // drop handshake packets for stateless rejects.
1589 SetPacketLossPercentage(5);
1591 ASSERT_TRUE(Initialize());
1593 // Wait for the server SHLO before upping the packet loss.
1594 client_->client()->WaitForCryptoHandshakeConfirmed();
1595 SetPacketLossPercentage(30);
1596 client_writer_->set_fake_blocked_socket_percentage(10);
1598 // Create a POST request and send the headers only.
1599 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1600 request.set_has_complete_message(false);
1601 client_->SendMessage(request);
1603 // The TestAckNotifierDelegate will cause a failure if not notified.
1604 scoped_refptr<TestAckNotifierDelegate> delegate(new TestAckNotifierDelegate);
1606 // Test the AckNotifier's ability to track multiple packets by making the
1607 // request body exceed the size of a single packet.
1608 string request_string =
1609 "a request body bigger than one packet" + string(kMaxPacketSize, '.');
1611 // Send the request, and register the delegate for ACKs.
1612 client_->SendData(request_string, true, delegate.get());
1613 client_->WaitForResponse();
1614 EXPECT_EQ(kFooResponseBody, client_->response_body());
1615 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1617 // Send another request to flush out any pending ACKs on the server.
1618 client_->SendSynchronousRequest(request_string);
1620 // Pause the server to avoid races.
1621 server_thread_->Pause();
1622 // Make sure the delegate does get the notification it expects.
1623 while (!delegate->has_been_notified()) {
1624 // Waits for up to 50 ms.
1625 client_->client()->WaitForEvents();
1627 server_thread_->Resume();
1630 // Send a public reset from the server for a different connection ID.
1631 // It should be ignored.
1632 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
1633 ASSERT_TRUE(Initialize());
1635 // Send the public reset.
1636 QuicConnectionId incorrect_connection_id =
1637 client_->client()->session()->connection()->connection_id() + 1;
1638 QuicPublicResetPacket header;
1639 header.public_header.connection_id = incorrect_connection_id;
1640 header.public_header.reset_flag = true;
1641 header.public_header.version_flag = false;
1642 header.rejected_packet_number = 10101;
1643 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1644 Perspective::IS_SERVER);
1645 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1646 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1647 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1648 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1649 .Times(1);
1650 // We must pause the server's thread in order to call WritePacket without
1651 // race conditions.
1652 server_thread_->Pause();
1653 server_writer_->WritePacket(packet->data(), packet->length(),
1654 server_address_.address(),
1655 client_->client()->client_address());
1656 server_thread_->Resume();
1658 // The connection should be unaffected.
1659 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1660 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1662 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1665 // Send a public reset from the client for a different connection ID.
1666 // It should be ignored.
1667 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
1668 ASSERT_TRUE(Initialize());
1670 // Send the public reset.
1671 QuicConnectionId incorrect_connection_id =
1672 client_->client()->session()->connection()->connection_id() + 1;
1673 QuicPublicResetPacket header;
1674 header.public_header.connection_id = incorrect_connection_id;
1675 header.public_header.reset_flag = true;
1676 header.public_header.version_flag = false;
1677 header.rejected_packet_number = 10101;
1678 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1679 Perspective::IS_CLIENT);
1680 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1681 client_writer_->WritePacket(packet->data(), packet->length(),
1682 client_->client()->client_address().address(),
1683 server_address_);
1685 // The connection should be unaffected.
1686 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1687 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1690 // Send a version negotiation packet from the server for a different
1691 // connection ID. It should be ignored.
1692 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
1693 ASSERT_TRUE(Initialize());
1695 // Send the version negotiation packet.
1696 QuicConnectionId incorrect_connection_id =
1697 client_->client()->session()->connection()->connection_id() + 1;
1698 QuicVersionNegotiationPacket header;
1699 header.connection_id = incorrect_connection_id;
1700 header.reset_flag = true;
1701 header.version_flag = true;
1702 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1703 Perspective::IS_SERVER);
1704 scoped_ptr<QuicEncryptedPacket> packet(
1705 framer.BuildVersionNegotiationPacket(header, server_supported_versions_));
1706 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1707 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1708 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1709 .Times(1);
1710 // We must pause the server's thread in order to call WritePacket without
1711 // race conditions.
1712 server_thread_->Pause();
1713 server_writer_->WritePacket(packet->data(), packet->length(),
1714 server_address_.address(),
1715 client_->client()->client_address());
1716 server_thread_->Resume();
1718 // The connection should be unaffected.
1719 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1720 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1722 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1725 // A bad header shouldn't tear down the connection, because the receiver can't
1726 // tell the connection ID.
1727 TEST_P(EndToEndTest, BadPacketHeaderTruncated) {
1728 ASSERT_TRUE(Initialize());
1730 // Start the connection.
1731 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1732 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1734 // Packet with invalid public flags.
1735 char packet[] = {// public flags (8 byte connection_id)
1736 0x3C,
1737 // truncated connection ID
1738 0x11};
1739 client_writer_->WritePacket(&packet[0], sizeof(packet),
1740 client_->client()->client_address().address(),
1741 server_address_);
1742 // Give the server time to process the packet.
1743 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1744 // Pause the server so we can access the server's internals without races.
1745 server_thread_->Pause();
1746 QuicDispatcher* dispatcher =
1747 QuicServerPeer::GetDispatcher(server_thread_->server());
1748 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1749 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1750 server_thread_->Resume();
1752 // The connection should not be terminated.
1753 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1754 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1757 // A bad header shouldn't tear down the connection, because the receiver can't
1758 // tell the connection ID.
1759 TEST_P(EndToEndTest, BadPacketHeaderFlags) {
1760 ASSERT_TRUE(Initialize());
1762 // Start the connection.
1763 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1764 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1766 // Packet with invalid public flags.
1767 char packet[] = {
1768 // invalid public flags
1769 0xFF,
1770 // connection_id
1771 0x10,
1772 0x32,
1773 0x54,
1774 0x76,
1775 0x98,
1776 0xBA,
1777 0xDC,
1778 0xFE,
1779 // packet sequence number
1780 0xBC,
1781 0x9A,
1782 0x78,
1783 0x56,
1784 0x34,
1785 0x12,
1786 // private flags
1787 0x00,
1789 client_writer_->WritePacket(&packet[0], sizeof(packet),
1790 client_->client()->client_address().address(),
1791 server_address_);
1792 // Give the server time to process the packet.
1793 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1794 // Pause the server so we can access the server's internals without races.
1795 server_thread_->Pause();
1796 QuicDispatcher* dispatcher =
1797 QuicServerPeer::GetDispatcher(server_thread_->server());
1798 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1799 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1800 server_thread_->Resume();
1802 // The connection should not be terminated.
1803 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1804 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1807 // Send a packet from the client with bad encrypted data. The server should not
1808 // tear down the connection.
1809 TEST_P(EndToEndTest, BadEncryptedData) {
1810 ASSERT_TRUE(Initialize());
1812 // Start the connection.
1813 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1814 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1816 scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
1817 client_->client()->session()->connection()->connection_id(), false, false,
1818 1, "At least 20 characters.", PACKET_8BYTE_CONNECTION_ID,
1819 PACKET_6BYTE_PACKET_NUMBER));
1820 // Damage the encrypted data.
1821 string damaged_packet(packet->data(), packet->length());
1822 damaged_packet[30] ^= 0x01;
1823 DVLOG(1) << "Sending bad packet.";
1824 client_writer_->WritePacket(damaged_packet.data(), damaged_packet.length(),
1825 client_->client()->client_address().address(),
1826 server_address_);
1827 // Give the server time to process the packet.
1828 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1829 // This error is sent to the connection's OnError (which ignores it), so the
1830 // dispatcher doesn't see it.
1831 // Pause the server so we can access the server's internals without races.
1832 server_thread_->Pause();
1833 QuicDispatcher* dispatcher =
1834 QuicServerPeer::GetDispatcher(server_thread_->server());
1835 EXPECT_EQ(QUIC_NO_ERROR,
1836 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1837 server_thread_->Resume();
1839 // The connection should not be terminated.
1840 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1841 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1844 } // namespace
1845 } // namespace test
1846 } // namespace tools
1847 } // namespace net