Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blobac8d05a17bf0f6d059bc181c86fe1804ebf055b9
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::MockQuicConnectionDebugVisitor;
59 using net::test::QuicConnectionPeer;
60 using net::test::QuicFlowControllerPeer;
61 using net::test::QuicSentPacketManagerPeer;
62 using net::test::QuicSessionPeer;
63 using net::test::QuicSpdySessionPeer;
64 using net::test::ReliableQuicStreamPeer;
65 using net::test::TestWriterFactory;
66 using net::test::ValueRestore;
67 using net::test::kClientDataStreamId1;
68 using net::test::kInitialSessionFlowControlWindowForTest;
69 using net::test::kInitialStreamFlowControlWindowForTest;
70 using net::tools::test::PacketDroppingTestWriter;
71 using net::tools::test::QuicDispatcherPeer;
72 using net::tools::test::QuicServerPeer;
73 using std::ostream;
74 using std::string;
75 using std::vector;
77 namespace net {
78 namespace tools {
79 namespace test {
80 namespace {
82 const char kFooResponseBody[] = "Artichoke hearts make me happy.";
83 const char kBarResponseBody[] = "Palm hearts are pretty delicious, also.";
85 // Run all tests with the cross products of all versions.
86 struct TestParams {
87 TestParams(const QuicVersionVector& client_supported_versions,
88 const QuicVersionVector& server_supported_versions,
89 QuicVersion negotiated_version,
90 bool use_fec,
91 QuicTag congestion_control_tag)
92 : client_supported_versions(client_supported_versions),
93 server_supported_versions(server_supported_versions),
94 negotiated_version(negotiated_version),
95 use_fec(use_fec),
96 congestion_control_tag(congestion_control_tag) {
99 friend ostream& operator<<(ostream& os, const TestParams& p) {
100 os << "{ server_supported_versions: "
101 << QuicVersionVectorToString(p.server_supported_versions);
102 os << " client_supported_versions: "
103 << QuicVersionVectorToString(p.client_supported_versions);
104 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
105 os << " use_fec: " << p.use_fec;
106 os << " congestion_control_tag: "
107 << QuicUtils::TagToString(p.congestion_control_tag) << " }";
108 return os;
111 QuicVersionVector client_supported_versions;
112 QuicVersionVector server_supported_versions;
113 QuicVersion negotiated_version;
114 bool use_fec;
115 QuicTag congestion_control_tag;
118 // Constructs various test permutations.
119 vector<TestParams> GetTestParams() {
120 // Divide the versions into buckets in which the intra-frame format
121 // is compatible. When clients encounter QUIC version negotiation
122 // they simply retransmit all packets using the new version's
123 // QUIC framing. However, they are unable to change the intra-frame
124 // layout (for example to change SPDY/4 headers to SPDY/3). So
125 // these tests need to ensure that clients are never attempting
126 // to do 0-RTT across incompatible versions. Chromium only supports
127 // a single version at a time anyway. :)
128 QuicVersionVector all_supported_versions = QuicSupportedVersions();
129 QuicVersionVector client_version_buckets[2];
130 for (const QuicVersion version : all_supported_versions) {
131 if (version <= QUIC_VERSION_24) {
132 // SPDY/4 compression but SPDY/3 headers
133 client_version_buckets[0].push_back(version);
134 } else {
135 // SPDY/4
136 client_version_buckets[1].push_back(version);
140 vector<TestParams> params;
141 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
142 // for (const QuicTag congestion_control_tag : {kRENO, kTBBR, kQBIC}) {
143 for (const QuicTag congestion_control_tag : {kRENO, kQBIC}) {
144 for (const bool use_fec : {false, true}) {
145 for (const QuicVersionVector& client_versions : client_version_buckets) {
146 CHECK(!client_versions.empty());
147 // Add an entry for server and client supporting all versions.
148 params.push_back(TestParams(client_versions, all_supported_versions,
149 client_versions.front(), use_fec != 0,
150 congestion_control_tag));
152 // Test client supporting all versions and server supporting 1
153 // version. Simulate an old server and exercise version downgrade in
154 // the client. Protocol negotiation should occur. Skip the i = 0 case
155 // because it is essentially the same as the default case.
156 for (const QuicVersion version : client_versions) {
157 QuicVersionVector server_supported_versions;
158 server_supported_versions.push_back(version);
159 params.push_back(TestParams(client_versions,
160 server_supported_versions,
161 server_supported_versions.front(),
162 use_fec != 0, congestion_control_tag));
167 return params;
170 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
171 public:
172 ServerDelegate(TestWriterFactory* writer_factory,
173 QuicDispatcher* dispatcher)
174 : writer_factory_(writer_factory),
175 dispatcher_(dispatcher) {}
176 ~ServerDelegate() override {}
177 void OnPacketSent(WriteResult result) override {
178 writer_factory_->OnPacketSent(result);
180 void OnCanWrite() override { dispatcher_->OnCanWrite(); }
182 private:
183 TestWriterFactory* writer_factory_;
184 QuicDispatcher* dispatcher_;
187 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
188 public:
189 explicit ClientDelegate(QuicClient* client) : client_(client) {}
190 ~ClientDelegate() override {}
191 void OnPacketSent(WriteResult result) override {}
192 void OnCanWrite() override {
193 EpollEvent event(EPOLLOUT, false);
194 client_->OnEvent(client_->fd(), &event);
197 private:
198 QuicClient* client_;
201 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
202 protected:
203 EndToEndTest()
204 : server_hostname_("example.com"),
205 server_started_(false),
206 strike_register_no_startup_period_(false) {
207 IPAddressNumber ip;
208 CHECK(net::ParseIPLiteralToNumber("127.0.0.1", &ip));
209 server_address_ = IPEndPoint(ip, 0);
211 client_supported_versions_ = GetParam().client_supported_versions;
212 server_supported_versions_ = GetParam().server_supported_versions;
213 negotiated_version_ = GetParam().negotiated_version;
214 FLAGS_enable_quic_fec = GetParam().use_fec;
216 VLOG(1) << "Using Configuration: " << GetParam();
218 // Use different flow control windows for client/server.
219 client_config_.SetInitialStreamFlowControlWindowToSend(
220 2 * kInitialStreamFlowControlWindowForTest);
221 client_config_.SetInitialSessionFlowControlWindowToSend(
222 2 * kInitialSessionFlowControlWindowForTest);
223 server_config_.SetInitialStreamFlowControlWindowToSend(
224 3 * kInitialStreamFlowControlWindowForTest);
225 server_config_.SetInitialSessionFlowControlWindowToSend(
226 3 * kInitialSessionFlowControlWindowForTest);
228 QuicInMemoryCachePeer::ResetForTests();
229 AddToCache("/foo", 200, "OK", kFooResponseBody);
230 AddToCache("/bar", 200, "OK", kBarResponseBody);
233 ~EndToEndTest() override {
234 // TODO(rtenneti): port RecycleUnusedPort if needed.
235 // RecycleUnusedPort(server_address_.port());
236 QuicInMemoryCachePeer::ResetForTests();
239 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
240 QuicTestClient* client = new QuicTestClient(
241 server_address_,
242 server_hostname_,
243 false, // not secure
244 client_config_,
245 client_supported_versions_);
246 client->UseWriter(writer);
247 client->Connect();
248 return client;
251 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
252 CHECK(client_.get() == nullptr);
253 DVLOG(1) << "Setting client initial stream flow control window: " << window;
254 client_config_.SetInitialStreamFlowControlWindowToSend(window);
257 void set_client_initial_session_flow_control_receive_window(uint32 window) {
258 CHECK(client_.get() == nullptr);
259 DVLOG(1) << "Setting client initial session flow control window: "
260 << window;
261 client_config_.SetInitialSessionFlowControlWindowToSend(window);
264 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
265 CHECK(server_thread_.get() == nullptr);
266 DVLOG(1) << "Setting server initial stream flow control window: "
267 << window;
268 server_config_.SetInitialStreamFlowControlWindowToSend(window);
271 void set_server_initial_session_flow_control_receive_window(uint32 window) {
272 CHECK(server_thread_.get() == nullptr);
273 DVLOG(1) << "Setting server initial session flow control window: "
274 << window;
275 server_config_.SetInitialSessionFlowControlWindowToSend(window);
278 const QuicSentPacketManager *
279 GetSentPacketManagerFromFirstServerSession() const {
280 QuicDispatcher* dispatcher =
281 QuicServerPeer::GetDispatcher(server_thread_->server());
282 QuicSession* session = dispatcher->session_map().begin()->second;
283 return &session->connection()->sent_packet_manager();
286 bool Initialize() {
287 QuicTagVector copt;
288 server_config_.SetConnectionOptionsToSend(copt);
290 // TODO(nimia): Consider setting the congestion control algorithm for the
291 // client as well according to the test parameter.
292 copt.push_back(GetParam().congestion_control_tag);
294 if (GetParam().use_fec) {
295 // Set FEC config in client's connection options and in client session.
296 copt.push_back(kFHDR);
299 client_config_.SetConnectionOptionsToSend(copt);
301 // Start the server first, because CreateQuicClient() attempts
302 // to connect to the server.
303 StartServer();
304 client_.reset(CreateQuicClient(client_writer_));
305 if (GetParam().use_fec) {
306 // Set FecPolicy to always protect data on all streams.
307 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
309 static EpollEvent event(EPOLLOUT, false);
310 client_writer_->Initialize(
311 reinterpret_cast<QuicEpollConnectionHelper*>(
312 QuicConnectionPeer::GetHelper(
313 client_->client()->session()->connection())),
314 new ClientDelegate(client_->client()));
315 return client_->client()->connected();
318 void SetUp() override {
319 // The ownership of these gets transferred to the QuicPacketWriterWrapper
320 // and TestWriterFactory when Initialize() is executed.
321 client_writer_ = new PacketDroppingTestWriter();
322 server_writer_ = new PacketDroppingTestWriter();
325 void TearDown() override { StopServer(); }
327 void StartServer() {
328 server_thread_.reset(
329 new ServerThread(
330 new QuicServer(server_config_, server_supported_versions_),
331 server_address_,
332 strike_register_no_startup_period_));
333 server_thread_->Initialize();
334 server_address_ = IPEndPoint(server_address_.address(),
335 server_thread_->GetPort());
336 QuicDispatcher* dispatcher =
337 QuicServerPeer::GetDispatcher(server_thread_->server());
338 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
339 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
340 packet_writer_factory);
341 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
342 server_writer_->Initialize(
343 QuicDispatcherPeer::GetHelper(dispatcher),
344 new ServerDelegate(packet_writer_factory, dispatcher));
345 server_thread_->Start();
346 server_started_ = true;
349 void StopServer() {
350 if (!server_started_)
351 return;
352 if (server_thread_.get()) {
353 server_thread_->Quit();
354 server_thread_->Join();
358 void AddToCache(StringPiece path,
359 int response_code,
360 StringPiece response_detail,
361 StringPiece body) {
362 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
363 "www.google.com", path, response_code, response_detail, body);
366 void SetPacketLossPercentage(int32 loss) {
367 // TODO(rtenneti): enable when we can do random packet loss tests in
368 // chrome's tree.
369 if (loss != 0 && loss != 100)
370 return;
371 client_writer_->set_fake_packet_loss_percentage(loss);
372 server_writer_->set_fake_packet_loss_percentage(loss);
375 void SetPacketSendDelay(QuicTime::Delta delay) {
376 // TODO(rtenneti): enable when we can do random packet send delay tests in
377 // chrome's tree.
378 // client_writer_->set_fake_packet_delay(delay);
379 // server_writer_->set_fake_packet_delay(delay);
382 void SetReorderPercentage(int32 reorder) {
383 // TODO(rtenneti): enable when we can do random packet reorder tests in
384 // chrome's tree.
385 // client_writer_->set_fake_reorder_percentage(reorder);
386 // server_writer_->set_fake_reorder_percentage(reorder);
389 // Verifies that the client and server connections were both free of packets
390 // being discarded, based on connection stats.
391 // Calls server_thread_ Pause() and Resume(), which may only be called once
392 // per test.
393 void VerifyCleanConnection(bool had_packet_loss) {
394 QuicConnectionStats client_stats =
395 client_->client()->session()->connection()->GetStats();
396 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
397 // if (!had_packet_loss) {
398 // EXPECT_EQ(0u, client_stats.packets_lost);
399 // }
400 EXPECT_EQ(0u, client_stats.packets_discarded);
401 EXPECT_EQ(0u, client_stats.packets_dropped);
402 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
404 server_thread_->Pause();
405 QuicDispatcher* dispatcher =
406 QuicServerPeer::GetDispatcher(server_thread_->server());
407 ASSERT_EQ(1u, dispatcher->session_map().size());
408 QuicSession* session = dispatcher->session_map().begin()->second;
409 QuicConnectionStats server_stats = session->connection()->GetStats();
410 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
411 // if (!had_packet_loss) {
412 // EXPECT_EQ(0u, server_stats.packets_lost);
413 // }
414 EXPECT_EQ(0u, server_stats.packets_discarded);
415 // TODO(ianswett): Restore the check for packets_dropped equals 0.
416 // The expect for packets received is equal to packets processed fails
417 // due to version negotiation packets.
418 server_thread_->Resume();
421 IPEndPoint server_address_;
422 string server_hostname_;
423 scoped_ptr<ServerThread> server_thread_;
424 scoped_ptr<QuicTestClient> client_;
425 PacketDroppingTestWriter* client_writer_;
426 PacketDroppingTestWriter* server_writer_;
427 bool server_started_;
428 QuicConfig client_config_;
429 QuicConfig server_config_;
430 QuicVersionVector client_supported_versions_;
431 QuicVersionVector server_supported_versions_;
432 QuicVersion negotiated_version_;
433 bool strike_register_no_startup_period_;
436 // Run all end to end tests with all supported versions.
437 INSTANTIATE_TEST_CASE_P(EndToEndTests,
438 EndToEndTest,
439 ::testing::ValuesIn(GetTestParams()));
441 TEST_P(EndToEndTest, SimpleRequestResponse) {
442 ASSERT_TRUE(Initialize());
444 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
445 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
448 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
449 // try bots) and selectively disable this test.
450 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
451 IPAddressNumber ip;
452 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
453 server_address_ = IPEndPoint(ip, server_address_.port());
454 ASSERT_TRUE(Initialize());
456 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
457 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
460 TEST_P(EndToEndTest, SeparateFinPacket) {
461 ASSERT_TRUE(Initialize());
463 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
464 request.set_has_complete_message(false);
466 // Send a request in two parts: the request and then an empty packet with FIN.
467 client_->SendMessage(request);
468 client_->SendData("", true);
469 client_->WaitForResponse();
470 EXPECT_EQ(kFooResponseBody, client_->response_body());
471 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
473 // Now do the same thing but with a content length.
474 request.AddBody("foo", true);
475 client_->SendMessage(request);
476 client_->SendData("", true);
477 client_->WaitForResponse();
478 EXPECT_EQ(kFooResponseBody, client_->response_body());
479 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
482 TEST_P(EndToEndTest, MultipleRequestResponse) {
483 ASSERT_TRUE(Initialize());
485 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
486 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
487 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
488 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
491 TEST_P(EndToEndTest, MultipleClients) {
492 ASSERT_TRUE(Initialize());
493 scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
495 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
496 request.AddHeader("content-length", "3");
497 request.set_has_complete_message(false);
499 client_->SendMessage(request);
500 client2->SendMessage(request);
502 client_->SendData("bar", true);
503 client_->WaitForResponse();
504 EXPECT_EQ(kFooResponseBody, client_->response_body());
505 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
507 client2->SendData("eep", true);
508 client2->WaitForResponse();
509 EXPECT_EQ(kFooResponseBody, client2->response_body());
510 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
513 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
514 // Send a large enough request to guarantee fragmentation.
515 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
516 AddToCache(huge_request, 200, "OK", kBarResponseBody);
518 ASSERT_TRUE(Initialize());
520 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
521 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
524 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
525 // Send a large enough request to guarantee fragmentation.
526 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
527 AddToCache(huge_request, 200, "OK", kBarResponseBody);
529 ASSERT_TRUE(Initialize());
530 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
531 SetReorderPercentage(50);
533 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
534 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
537 TEST_P(EndToEndTest, PostMissingBytes) {
538 ASSERT_TRUE(Initialize());
540 // Add a content length header with no body.
541 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
542 request.AddHeader("content-length", "3");
543 request.set_skip_message_validation(true);
545 // This should be detected as stream fin without complete request,
546 // triggering an error response.
547 client_->SendCustomSynchronousRequest(request);
548 EXPECT_EQ("bad", client_->response_body());
549 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
552 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
553 // http://crbug.com/297040.
554 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
555 ASSERT_TRUE(Initialize());
557 client_->client()->WaitForCryptoHandshakeConfirmed();
559 // 1 MB body.
560 string body;
561 GenerateBody(&body, 1024 * 1024);
563 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
564 request.AddBody(body, true);
566 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
567 VerifyCleanConnection(false);
570 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
571 ASSERT_TRUE(Initialize());
572 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
574 client_->client()->WaitForCryptoHandshakeConfirmed();
576 // 100 KB body.
577 string body;
578 GenerateBody(&body, 100 * 1024);
580 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
581 request.AddBody(body, true);
583 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
584 VerifyCleanConnection(false);
587 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
588 // Connect with lower fake packet loss than we'd like to test. Until
589 // b/10126687 is fixed, losing handshake packets is pretty brutal.
590 SetPacketLossPercentage(5);
591 ASSERT_TRUE(Initialize());
593 // Wait for the server SHLO before upping the packet loss.
594 client_->client()->WaitForCryptoHandshakeConfirmed();
595 SetPacketLossPercentage(30);
597 // 10 KB body.
598 string body;
599 GenerateBody(&body, 1024 * 10);
601 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
602 request.AddBody(body, true);
604 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
605 VerifyCleanConnection(true);
608 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
609 // Connect with lower fake packet loss than we'd like to test. Until
610 // b/10126687 is fixed, losing handshake packets is pretty brutal.
611 SetPacketLossPercentage(5);
612 ASSERT_TRUE(Initialize());
614 // Wait for the server SHLO before upping the packet loss.
615 client_->client()->WaitForCryptoHandshakeConfirmed();
616 SetPacketLossPercentage(10);
617 client_writer_->set_fake_blocked_socket_percentage(10);
619 // 10 KB body.
620 string body;
621 GenerateBody(&body, 1024 * 10);
623 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
624 request.AddBody(body, true);
626 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
629 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
630 ASSERT_TRUE(Initialize());
632 client_->client()->WaitForCryptoHandshakeConfirmed();
633 // Both of these must be called when the writer is not actively used.
634 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
635 SetReorderPercentage(30);
637 // 1 MB body.
638 string body;
639 GenerateBody(&body, 1024 * 1024);
641 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
642 request.AddBody(body, true);
644 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
647 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
648 // Have the server accept 0-RTT without waiting a startup period.
649 strike_register_no_startup_period_ = true;
651 // Send a request and then disconnect. This prepares the client to attempt
652 // a 0-RTT handshake for the next request.
653 ASSERT_TRUE(Initialize());
655 string body;
656 GenerateBody(&body, 20480);
658 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
659 request.AddBody(body, true);
661 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
662 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
664 client_->Disconnect();
666 // The 0-RTT handshake should succeed.
667 client_->Connect();
668 client_->WaitForResponseForMs(-1);
669 ASSERT_TRUE(client_->client()->connected());
670 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
671 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
673 client_->Disconnect();
675 // Restart the server so that the 0-RTT handshake will take 1 RTT.
676 StopServer();
677 server_writer_ = new PacketDroppingTestWriter();
678 StartServer();
680 client_->Connect();
681 ASSERT_TRUE(client_->client()->connected());
682 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
683 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
684 VerifyCleanConnection(false);
687 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
688 ASSERT_TRUE(Initialize());
689 client_->client()->WaitForCryptoHandshakeConfirmed();
690 server_thread_->WaitForCryptoHandshakeConfirmed();
692 FecPolicy expected_policy =
693 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
695 // Verify that server's FEC configuration is correct.
696 server_thread_->Pause();
697 QuicDispatcher* dispatcher =
698 QuicServerPeer::GetDispatcher(server_thread_->server());
699 ASSERT_EQ(1u, dispatcher->session_map().size());
700 QuicSpdySession* session = dispatcher->session_map().begin()->second;
701 EXPECT_EQ(expected_policy,
702 QuicSpdySessionPeer::GetHeadersStream(session)->fec_policy());
703 server_thread_->Resume();
705 // Verify that client's FEC configuration is correct.
706 EXPECT_EQ(expected_policy, QuicSpdySessionPeer::GetHeadersStream(
707 client_->client()->session())->fec_policy());
708 EXPECT_EQ(expected_policy,
709 client_->GetOrCreateStream()->fec_policy());
712 TEST_P(EndToEndTest, LargePostSmallBandwidthLargeBuffer) {
713 ASSERT_TRUE(Initialize());
714 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
715 // 256KB per second with a 256KB buffer from server to client. Wireless
716 // clients commonly have larger buffers, but our max CWND is 200.
717 server_writer_->set_max_bandwidth_and_buffer_size(
718 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
720 client_->client()->WaitForCryptoHandshakeConfirmed();
722 // 1 MB body.
723 string body;
724 GenerateBody(&body, 1024 * 1024);
726 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
727 request.AddBody(body, true);
729 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
730 // This connection will not drop packets, because the buffer size is larger
731 // than the default receive window.
732 VerifyCleanConnection(false);
735 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
736 // Regression test for b/14677858.
737 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
738 // if currently connection level flow control blocked. If set, this results in
739 // an infinite loop in the EpollServer, as the alarm fires and is immediately
740 // rescheduled.
741 ASSERT_TRUE(Initialize());
742 client_->client()->WaitForCryptoHandshakeConfirmed();
744 // Ensure both stream and connection level are flow control blocked by setting
745 // the send window offset to 0.
746 const uint64 flow_control_window =
747 server_config_.GetInitialStreamFlowControlWindowToSend();
748 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
749 QuicSession* session = client_->client()->session();
750 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
751 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
752 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
753 EXPECT_TRUE(session->flow_controller()->IsBlocked());
755 // Make sure that the stream has data pending so that it will be marked as
756 // write blocked when it receives a stream level WINDOW_UPDATE.
757 stream->SendBody("hello", false);
759 // The stream now attempts to write, fails because it is still connection
760 // level flow control blocked, and is added to the write blocked list.
761 QuicWindowUpdateFrame window_update(stream->id(), 2 * flow_control_window);
762 stream->OnWindowUpdateFrame(window_update);
764 // Prior to fixing b/14677858 this call would result in an infinite loop in
765 // Chromium. As a proxy for detecting this, we now check whether the
766 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
767 // connection is still flow control blocked.
768 session->connection()->OnCanWrite();
770 QuicAlarm* resume_writes_alarm =
771 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
772 EXPECT_FALSE(resume_writes_alarm->IsSet());
775 TEST_P(EndToEndTest, InvalidStream) {
776 ASSERT_TRUE(Initialize());
777 client_->client()->WaitForCryptoHandshakeConfirmed();
779 string body;
780 GenerateBody(&body, kMaxPacketSize);
782 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
783 request.AddBody(body, true);
784 // Force the client to write with a stream ID belonging to a nonexistent
785 // server-side stream.
786 QuicSessionPeer::SetNextStreamId(client_->client()->session(), 2);
788 client_->SendCustomSynchronousRequest(request);
789 // EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
790 EXPECT_EQ(QUIC_PACKET_FOR_NONEXISTENT_STREAM, client_->connection_error());
793 // TODO(rch): this test seems to cause net_unittests timeouts :|
794 TEST_P(EndToEndTest, DISABLED_MultipleTermination) {
795 ASSERT_TRUE(Initialize());
797 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
798 request.AddHeader("content-length", "3");
799 request.set_has_complete_message(false);
801 // Set the offset so we won't frame. Otherwise when we pick up termination
802 // before HTTP framing is complete, we send an error and close the stream,
803 // and the second write is picked up as writing on a closed stream.
804 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
805 ASSERT_TRUE(stream != nullptr);
806 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
808 client_->SendData("bar", true);
809 client_->WaitForWriteToFlush();
811 // By default the stream protects itself from writes after terminte is set.
812 // Override this to test the server handling buggy clients.
813 ReliableQuicStreamPeer::SetWriteSideClosed(
814 false, client_->GetOrCreateStream());
816 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
819 TEST_P(EndToEndTest, Timeout) {
820 client_config_.SetIdleConnectionStateLifetime(
821 QuicTime::Delta::FromMicroseconds(500),
822 QuicTime::Delta::FromMicroseconds(500));
823 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
824 // that's enough to validate timeout in this case.
825 Initialize();
826 while (client_->client()->connected()) {
827 client_->client()->WaitForEvents();
831 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
832 // Negotiate 1 max open stream.
833 client_config_.SetMaxStreamsPerConnection(1, 1);
834 ASSERT_TRUE(Initialize());
835 client_->client()->WaitForCryptoHandshakeConfirmed();
837 // Make the client misbehave after negotiation.
838 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
839 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(),
840 kServerMaxStreams + 1);
842 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
843 request.AddHeader("content-length", "3");
844 request.set_has_complete_message(false);
846 // The server supports a small number of additional streams beyond the
847 // negotiated limit. Open enough streams to go beyond that limit.
848 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
849 client_->SendMessage(request);
851 client_->WaitForResponse();
853 EXPECT_FALSE(client_->connected());
854 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
855 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
858 TEST_P(EndToEndTest, NegotiateCongestionControl) {
859 ValueRestore<bool> old_flag(&FLAGS_quic_allow_bbr, true);
860 ASSERT_TRUE(Initialize());
861 client_->client()->WaitForCryptoHandshakeConfirmed();
863 CongestionControlType expected_congestion_control_type = kReno;
864 switch (GetParam().congestion_control_tag) {
865 case kRENO:
866 expected_congestion_control_type = kReno;
867 break;
868 case kTBBR:
869 expected_congestion_control_type = kBBR;
870 break;
871 case kQBIC:
872 expected_congestion_control_type = kCubic;
873 break;
874 default:
875 DLOG(FATAL) << "Unexpected congestion control tag";
878 EXPECT_EQ(expected_congestion_control_type,
879 QuicSentPacketManagerPeer::GetSendAlgorithm(
880 *GetSentPacketManagerFromFirstServerSession())
881 ->GetCongestionControlType());
884 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
885 // Server limits the number of max streams to 2.
886 server_config_.SetMaxStreamsPerConnection(2, 2);
887 // Client tries to negotiate for 10.
888 client_config_.SetMaxStreamsPerConnection(10, 5);
890 ASSERT_TRUE(Initialize());
891 client_->client()->WaitForCryptoHandshakeConfirmed();
892 QuicConfig* client_negotiated_config = client_->client()->session()->config();
893 EXPECT_EQ(2u, client_negotiated_config->MaxStreamsPerConnection());
896 TEST_P(EndToEndTest, ClientSuggestsRTT) {
897 // Client suggests initial RTT, verify it is used.
898 const uint32 kInitialRTT = 20000;
899 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT);
901 ASSERT_TRUE(Initialize());
902 client_->client()->WaitForCryptoHandshakeConfirmed();
903 server_thread_->WaitForCryptoHandshakeConfirmed();
905 // Pause the server so we can access the server's internals without races.
906 server_thread_->Pause();
907 QuicDispatcher* dispatcher =
908 QuicServerPeer::GetDispatcher(server_thread_->server());
909 ASSERT_EQ(1u, dispatcher->session_map().size());
910 const QuicSentPacketManager& client_sent_packet_manager =
911 client_->client()->session()->connection()->sent_packet_manager();
912 const QuicSentPacketManager& server_sent_packet_manager =
913 *GetSentPacketManagerFromFirstServerSession();
915 EXPECT_EQ(kInitialRTT,
916 client_sent_packet_manager.GetRttStats()->initial_rtt_us());
917 EXPECT_EQ(kInitialRTT,
918 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
919 server_thread_->Resume();
922 TEST_P(EndToEndTest, MaxInitialRTT) {
923 // Client tries to suggest twice the server's max initial rtt and the server
924 // uses the max.
925 client_config_.SetInitialRoundTripTimeUsToSend(
926 2 * kMaxInitialRoundTripTimeUs);
928 ASSERT_TRUE(Initialize());
929 client_->client()->WaitForCryptoHandshakeConfirmed();
930 server_thread_->WaitForCryptoHandshakeConfirmed();
932 // Pause the server so we can access the server's internals without races.
933 server_thread_->Pause();
934 QuicDispatcher* dispatcher =
935 QuicServerPeer::GetDispatcher(server_thread_->server());
936 ASSERT_EQ(1u, dispatcher->session_map().size());
937 QuicSession* session = dispatcher->session_map().begin()->second;
938 const QuicSentPacketManager& client_sent_packet_manager =
939 client_->client()->session()->connection()->sent_packet_manager();
941 // Now that acks have been exchanged, the RTT estimate has decreased on the
942 // server and is not infinite on the client.
943 EXPECT_FALSE(
944 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
945 const RttStats& server_rtt_stats =
946 *session->connection()->sent_packet_manager().GetRttStats();
947 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
948 server_rtt_stats.initial_rtt_us());
949 EXPECT_GE(static_cast<int64>(kMaxInitialRoundTripTimeUs),
950 server_rtt_stats.smoothed_rtt().ToMicroseconds());
951 server_thread_->Resume();
954 TEST_P(EndToEndTest, MinInitialRTT) {
955 // Client tries to suggest 0 and the server uses the default.
956 client_config_.SetInitialRoundTripTimeUsToSend(0);
958 ASSERT_TRUE(Initialize());
959 client_->client()->WaitForCryptoHandshakeConfirmed();
960 server_thread_->WaitForCryptoHandshakeConfirmed();
962 // Pause the server so we can access the server's internals without races.
963 server_thread_->Pause();
964 QuicDispatcher* dispatcher =
965 QuicServerPeer::GetDispatcher(server_thread_->server());
966 ASSERT_EQ(1u, dispatcher->session_map().size());
967 QuicSession* session = dispatcher->session_map().begin()->second;
968 const QuicSentPacketManager& client_sent_packet_manager =
969 client_->client()->session()->connection()->sent_packet_manager();
970 const QuicSentPacketManager& server_sent_packet_manager =
971 session->connection()->sent_packet_manager();
973 // Now that acks have been exchanged, the RTT estimate has decreased on the
974 // server and is not infinite on the client.
975 EXPECT_FALSE(
976 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
977 // Expect the default rtt of 100ms.
978 EXPECT_EQ(static_cast<int64>(100 * kNumMicrosPerMilli),
979 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
980 // Ensure the bandwidth is valid.
981 client_sent_packet_manager.BandwidthEstimate();
982 server_sent_packet_manager.BandwidthEstimate();
983 server_thread_->Resume();
986 TEST_P(EndToEndTest, 0ByteConnectionId) {
987 client_config_.SetBytesForConnectionIdToSend(0);
988 ASSERT_TRUE(Initialize());
990 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
991 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
993 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
994 client_->client()->session()->connection());
995 EXPECT_EQ(PACKET_0BYTE_CONNECTION_ID,
996 header->public_header.connection_id_length);
999 TEST_P(EndToEndTest, 1ByteConnectionId) {
1000 client_config_.SetBytesForConnectionIdToSend(1);
1001 ASSERT_TRUE(Initialize());
1003 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1004 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1005 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1006 client_->client()->session()->connection());
1007 EXPECT_EQ(PACKET_1BYTE_CONNECTION_ID,
1008 header->public_header.connection_id_length);
1011 TEST_P(EndToEndTest, 4ByteConnectionId) {
1012 client_config_.SetBytesForConnectionIdToSend(4);
1013 ASSERT_TRUE(Initialize());
1015 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1016 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1017 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1018 client_->client()->session()->connection());
1019 EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID,
1020 header->public_header.connection_id_length);
1023 TEST_P(EndToEndTest, 8ByteConnectionId) {
1024 client_config_.SetBytesForConnectionIdToSend(8);
1025 ASSERT_TRUE(Initialize());
1027 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1028 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1029 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1030 client_->client()->session()->connection());
1031 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1032 header->public_header.connection_id_length);
1035 TEST_P(EndToEndTest, 15ByteConnectionId) {
1036 client_config_.SetBytesForConnectionIdToSend(15);
1037 ASSERT_TRUE(Initialize());
1039 // Our server is permissive and allows for out of bounds values.
1040 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1041 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1042 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1043 client_->client()->session()->connection());
1044 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1045 header->public_header.connection_id_length);
1048 TEST_P(EndToEndTest, ResetConnection) {
1049 ASSERT_TRUE(Initialize());
1050 client_->client()->WaitForCryptoHandshakeConfirmed();
1052 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1053 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1054 client_->ResetConnection();
1055 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1056 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1059 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1060 SetPacketLossPercentage(1);
1061 ASSERT_TRUE(Initialize());
1062 string large_body;
1063 GenerateBody(&large_body, 10240);
1064 int max_streams = 100;
1066 AddToCache("/large_response", 200, "OK", large_body);;
1068 client_->client()->WaitForCryptoHandshakeConfirmed();
1069 SetPacketLossPercentage(10);
1071 for (int i = 0; i < max_streams; ++i) {
1072 EXPECT_LT(0, client_->SendRequest("/large_response"));
1075 // WaitForEvents waits 50ms and returns true if there are outstanding
1076 // requests.
1077 while (client_->client()->WaitForEvents() == true) {
1081 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1082 ASSERT_TRUE(Initialize());
1083 string small_body;
1084 GenerateBody(&small_body, 256);
1086 AddToCache("/small_response", 200, "OK", small_body);
1088 client_->client()->WaitForCryptoHandshakeConfirmed();
1090 QuicSession* session = client_->client()->session();
1091 // Lose the request.
1092 SetPacketLossPercentage(100);
1093 EXPECT_LT(0, client_->SendRequest("/small_response"));
1094 client_->client()->WaitForEvents();
1095 // Transmit the cancel, and ensure the connection is torn down properly.
1096 SetPacketLossPercentage(0);
1097 QuicStreamId stream_id = kClientDataStreamId1;
1098 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1100 // WaitForEvents waits 50ms and returns true if there are outstanding
1101 // requests.
1102 while (client_->client()->WaitForEvents() == true) {
1104 // It should be completely fine to RST a stream before any data has been
1105 // received for that stream.
1106 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1109 class WrongAddressWriter : public QuicPacketWriterWrapper {
1110 public:
1111 WrongAddressWriter() {
1112 IPAddressNumber ip;
1113 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1114 self_address_ = IPEndPoint(ip, 0);
1117 WriteResult WritePacket(const char* buffer,
1118 size_t buf_len,
1119 const IPAddressNumber& real_self_address,
1120 const IPEndPoint& peer_address) override {
1121 // Use wrong address!
1122 return QuicPacketWriterWrapper::WritePacket(
1123 buffer, buf_len, self_address_.address(), peer_address);
1126 bool IsWriteBlockedDataBuffered() const override { return false; }
1128 IPEndPoint self_address_;
1131 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1132 // Allow client IP migration during an established QUIC connection.
1133 ValueRestore<bool> old_flag(&FLAGS_quic_allow_ip_migration, true);
1135 ASSERT_TRUE(Initialize());
1137 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1138 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1140 // Store the client IP address which was used to send the first request.
1141 IPAddressNumber old_host = client_->client()->client_address().address();
1143 // Migrate socket to the new IP address.
1144 IPAddressNumber new_host;
1145 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &new_host));
1146 EXPECT_NE(old_host, new_host);
1147 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
1149 // Send a request using the new socket.
1150 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1151 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1154 TEST_P(EndToEndTest, ConnectionMigrationClientIPChangedUnsupported) {
1155 // Tests that the client's IP can not change during an established QUIC
1156 // connection. If it changes, the connection is closed by the server as we
1157 // do not yet support IP migration.
1158 ValueRestore<bool> old_flag(&FLAGS_quic_allow_ip_migration, false);
1160 ASSERT_TRUE(Initialize());
1162 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1163 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1165 WrongAddressWriter* writer = new WrongAddressWriter();
1167 writer->set_writer(new QuicDefaultPacketWriter(client_->client()->fd()));
1168 QuicConnectionPeer::SetWriter(client_->client()->session()->connection(),
1169 writer, /* owns_writer= */ true);
1171 client_->SendSynchronousRequest("/bar");
1173 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1174 EXPECT_EQ(QUIC_ERROR_MIGRATING_ADDRESS, client_->connection_error());
1177 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1178 // Tests that the client's port can change during an established QUIC
1179 // connection, and that doing so does not result in the connection being
1180 // closed by the server.
1181 ASSERT_TRUE(Initialize());
1183 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1184 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1186 // Store the client address which was used to send the first request.
1187 IPEndPoint old_address = client_->client()->client_address();
1189 // Stop listening on the old FD.
1190 EpollServer* eps = client_->epoll_server();
1191 int old_fd = client_->client()->fd();
1192 eps->UnregisterFD(old_fd);
1193 // Create a new socket before closing the old one, which will result in a new
1194 // ephemeral port.
1195 QuicClientPeer::CreateUDPSocket(client_->client());
1196 close(old_fd);
1198 // The packet writer needs to be updated to use the new FD.
1199 client_->client()->CreateQuicPacketWriter();
1201 // Change the internal state of the client and connection to use the new port,
1202 // this is done because in a real NAT rebinding the client wouldn't see any
1203 // port change, and so expects no change to incoming port.
1204 // This is kind of ugly, but needed as we are simply swapping out the client
1205 // FD rather than any more complex NAT rebinding simulation.
1206 int new_port = client_->client()->client_address().port();
1207 QuicClientPeer::SetClientPort(client_->client(), new_port);
1208 QuicConnectionPeer::SetSelfAddress(
1209 client_->client()->session()->connection(),
1210 IPEndPoint(
1211 client_->client()->session()->connection()->self_address().address(),
1212 new_port));
1214 // Register the new FD for epoll events.
1215 int new_fd = client_->client()->fd();
1216 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1218 // Send a second request, using the new FD.
1219 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1220 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1222 // Verify that the client's ephemeral port is different.
1223 IPEndPoint new_address = client_->client()->client_address();
1224 EXPECT_EQ(old_address.address(), new_address.address());
1225 EXPECT_NE(old_address.port(), new_address.port());
1228 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
1229 // Client and server can set different initial flow control receive windows.
1230 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1231 // in the crypto handshake.
1232 const uint32 kClientStreamIFCW = 123456;
1233 const uint32 kClientSessionIFCW = 234567;
1234 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1235 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1237 const uint32 kServerStreamIFCW = 654321;
1238 const uint32 kServerSessionIFCW = 765432;
1239 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1240 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1242 ASSERT_TRUE(Initialize());
1244 // Values are exchanged during crypto handshake, so wait for that to finish.
1245 client_->client()->WaitForCryptoHandshakeConfirmed();
1246 server_thread_->WaitForCryptoHandshakeConfirmed();
1248 // Open a data stream to make sure the stream level flow control is updated.
1249 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1250 stream->SendBody("hello", false);
1252 // Client should have the right values for server's receive window.
1253 EXPECT_EQ(kServerStreamIFCW,
1254 client_->client()
1255 ->session()
1256 ->config()
1257 ->ReceivedInitialStreamFlowControlWindowBytes());
1258 EXPECT_EQ(kServerSessionIFCW,
1259 client_->client()
1260 ->session()
1261 ->config()
1262 ->ReceivedInitialSessionFlowControlWindowBytes());
1263 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1264 stream->flow_controller()));
1265 EXPECT_EQ(kServerSessionIFCW,
1266 QuicFlowControllerPeer::SendWindowOffset(
1267 client_->client()->session()->flow_controller()));
1269 // Server should have the right values for client's receive window.
1270 server_thread_->Pause();
1271 QuicDispatcher* dispatcher =
1272 QuicServerPeer::GetDispatcher(server_thread_->server());
1273 QuicSession* session = dispatcher->session_map().begin()->second;
1274 EXPECT_EQ(kClientStreamIFCW,
1275 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1276 EXPECT_EQ(kClientSessionIFCW,
1277 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1278 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1279 session->flow_controller()));
1280 server_thread_->Resume();
1283 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1284 // The special headers and crypto streams should be subject to per-stream flow
1285 // control limits, but should not be subject to connection level flow control.
1286 const uint32 kStreamIFCW = 123456;
1287 const uint32 kSessionIFCW = 234567;
1288 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
1289 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
1290 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
1291 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
1293 ASSERT_TRUE(Initialize());
1295 // Wait for crypto handshake to finish. This should have contributed to the
1296 // crypto stream flow control window, but not affected the session flow
1297 // control window.
1298 client_->client()->WaitForCryptoHandshakeConfirmed();
1299 server_thread_->WaitForCryptoHandshakeConfirmed();
1301 QuicCryptoStream* crypto_stream =
1302 QuicSessionPeer::GetCryptoStream(client_->client()->session());
1303 EXPECT_LT(
1304 QuicFlowControllerPeer::SendWindowSize(crypto_stream->flow_controller()),
1305 kStreamIFCW);
1306 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1307 client_->client()->session()->flow_controller()));
1309 // Send a request with no body, and verify that the connection level window
1310 // has not been affected.
1311 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1313 QuicHeadersStream* headers_stream =
1314 QuicSpdySessionPeer::GetHeadersStream(client_->client()->session());
1315 EXPECT_LT(
1316 QuicFlowControllerPeer::SendWindowSize(headers_stream->flow_controller()),
1317 kStreamIFCW);
1318 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1319 client_->client()->session()->flow_controller()));
1321 // Server should be in a similar state: connection flow control window should
1322 // not have any bytes marked as received.
1323 server_thread_->Pause();
1324 QuicDispatcher* dispatcher =
1325 QuicServerPeer::GetDispatcher(server_thread_->server());
1326 QuicSession* session = dispatcher->session_map().begin()->second;
1327 QuicFlowController* server_connection_flow_controller =
1328 session->flow_controller();
1329 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
1330 server_connection_flow_controller));
1331 server_thread_->Resume();
1334 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1335 // A stream created on receipt of a simple request with no body will never get
1336 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1337 // the locally closed streams map: it will never be removed if so.
1338 ASSERT_TRUE(Initialize());
1340 // Send a simple headers only request, and receive response.
1341 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1342 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1344 // Now verify that the server is not waiting for a final FIN or RST.
1345 server_thread_->Pause();
1346 QuicDispatcher* dispatcher =
1347 QuicServerPeer::GetDispatcher(server_thread_->server());
1348 QuicSession* session = dispatcher->session_map().begin()->second;
1349 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1350 session).size());
1351 server_thread_->Resume();
1354 // A TestAckNotifierDelegate verifies that its OnAckNotification method has been
1355 // called exactly once on destruction.
1356 class TestAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
1357 public:
1358 TestAckNotifierDelegate() {}
1360 void OnAckNotification(int /*num_retransmitted_packets*/,
1361 int /*num_retransmitted_bytes*/,
1362 QuicTime::Delta /*delta_largest_observed*/) override {
1363 ASSERT_FALSE(has_been_notified_);
1364 has_been_notified_ = true;
1367 bool has_been_notified() const { return has_been_notified_; }
1369 protected:
1370 // Object is ref counted.
1371 ~TestAckNotifierDelegate() override { EXPECT_TRUE(has_been_notified_); }
1373 private:
1374 bool has_been_notified_ = false;
1377 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
1378 // Verify that even in the presence of packet loss and occasionally blocked
1379 // socket, an AckNotifierDelegate will get informed that the data it is
1380 // interested in has been ACKed. This tests end-to-end ACK notification, and
1381 // demonstrates that retransmissions do not break this functionality.
1382 SetPacketLossPercentage(5);
1383 ASSERT_TRUE(Initialize());
1385 // Wait for the server SHLO before upping the packet loss.
1386 client_->client()->WaitForCryptoHandshakeConfirmed();
1387 SetPacketLossPercentage(30);
1388 client_writer_->set_fake_blocked_socket_percentage(10);
1390 // Create a POST request and send the headers only.
1391 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1392 request.set_has_complete_message(false);
1393 client_->SendMessage(request);
1395 // The TestAckNotifierDelegate will cause a failure if not notified.
1396 scoped_refptr<TestAckNotifierDelegate> delegate(new TestAckNotifierDelegate);
1398 // Test the AckNotifier's ability to track multiple packets by making the
1399 // request body exceed the size of a single packet.
1400 string request_string =
1401 "a request body bigger than one packet" + string(kMaxPacketSize, '.');
1403 // Send the request, and register the delegate for ACKs.
1404 client_->SendData(request_string, true, delegate.get());
1405 client_->WaitForResponse();
1406 EXPECT_EQ(kFooResponseBody, client_->response_body());
1407 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1409 // Send another request to flush out any pending ACKs on the server.
1410 client_->SendSynchronousRequest(request_string);
1412 // Pause the server to avoid races.
1413 server_thread_->Pause();
1414 // Make sure the delegate does get the notification it expects.
1415 while (!delegate->has_been_notified()) {
1416 // Waits for up to 50 ms.
1417 client_->client()->WaitForEvents();
1419 server_thread_->Resume();
1422 // Send a public reset from the server for a different connection ID.
1423 // It should be ignored.
1424 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
1425 ASSERT_TRUE(Initialize());
1427 // Send the public reset.
1428 QuicConnectionId incorrect_connection_id =
1429 client_->client()->session()->connection()->connection_id() + 1;
1430 QuicPublicResetPacket header;
1431 header.public_header.connection_id = incorrect_connection_id;
1432 header.public_header.reset_flag = true;
1433 header.public_header.version_flag = false;
1434 header.rejected_sequence_number = 10101;
1435 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1436 Perspective::IS_SERVER);
1437 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1438 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1439 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1440 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1441 .Times(1);
1442 // We must pause the server's thread in order to call WritePacket without
1443 // race conditions.
1444 server_thread_->Pause();
1445 server_writer_->WritePacket(packet->data(), packet->length(),
1446 server_address_.address(),
1447 client_->client()->client_address());
1448 server_thread_->Resume();
1450 // The connection should be unaffected.
1451 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1452 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1454 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1457 // Send a public reset from the client for a different connection ID.
1458 // It should be ignored.
1459 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
1460 ASSERT_TRUE(Initialize());
1462 // Send the public reset.
1463 QuicConnectionId incorrect_connection_id =
1464 client_->client()->session()->connection()->connection_id() + 1;
1465 QuicPublicResetPacket header;
1466 header.public_header.connection_id = incorrect_connection_id;
1467 header.public_header.reset_flag = true;
1468 header.public_header.version_flag = false;
1469 header.rejected_sequence_number = 10101;
1470 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1471 Perspective::IS_CLIENT);
1472 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1473 client_writer_->WritePacket(packet->data(), packet->length(),
1474 client_->client()->client_address().address(),
1475 server_address_);
1477 // The connection should be unaffected.
1478 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1479 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1482 // Send a version negotiation packet from the server for a different
1483 // connection ID. It should be ignored.
1484 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
1485 ASSERT_TRUE(Initialize());
1487 // Send the version negotiation packet.
1488 QuicConnectionId incorrect_connection_id =
1489 client_->client()->session()->connection()->connection_id() + 1;
1490 QuicVersionNegotiationPacket header;
1491 header.connection_id = incorrect_connection_id;
1492 header.reset_flag = true;
1493 header.version_flag = true;
1494 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1495 Perspective::IS_SERVER);
1496 scoped_ptr<QuicEncryptedPacket> packet(
1497 framer.BuildVersionNegotiationPacket(header, server_supported_versions_));
1498 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1499 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1500 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1501 .Times(1);
1502 // We must pause the server's thread in order to call WritePacket without
1503 // race conditions.
1504 server_thread_->Pause();
1505 server_writer_->WritePacket(packet->data(), packet->length(),
1506 server_address_.address(),
1507 client_->client()->client_address());
1508 server_thread_->Resume();
1510 // The connection should be unaffected.
1511 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1512 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1514 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1517 // A bad header shouldn't tear down the connection, because the receiver can't
1518 // tell the connection ID.
1519 TEST_P(EndToEndTest, BadPacketHeaderTruncated) {
1520 ASSERT_TRUE(Initialize());
1522 // Start the connection.
1523 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1524 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1526 // Packet with invalid public flags.
1527 char packet[] = {// public flags (8 byte connection_id)
1528 0x3C,
1529 // truncated connection ID
1530 0x11};
1531 client_writer_->WritePacket(&packet[0], sizeof(packet),
1532 client_->client()->client_address().address(),
1533 server_address_);
1534 // Give the server time to process the packet.
1535 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1536 // Pause the server so we can access the server's internals without races.
1537 server_thread_->Pause();
1538 QuicDispatcher* dispatcher =
1539 QuicServerPeer::GetDispatcher(server_thread_->server());
1540 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1541 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1542 server_thread_->Resume();
1544 // The connection should not be terminated.
1545 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1546 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1549 // A bad header shouldn't tear down the connection, because the receiver can't
1550 // tell the connection ID.
1551 TEST_P(EndToEndTest, BadPacketHeaderFlags) {
1552 ASSERT_TRUE(Initialize());
1554 // Start the connection.
1555 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1556 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1558 // Packet with invalid public flags.
1559 char packet[] = {
1560 // invalid public flags
1561 0xFF,
1562 // connection_id
1563 0x10,
1564 0x32,
1565 0x54,
1566 0x76,
1567 0x98,
1568 0xBA,
1569 0xDC,
1570 0xFE,
1571 // packet sequence number
1572 0xBC,
1573 0x9A,
1574 0x78,
1575 0x56,
1576 0x34,
1577 0x12,
1578 // private flags
1579 0x00,
1581 client_writer_->WritePacket(&packet[0], sizeof(packet),
1582 client_->client()->client_address().address(),
1583 server_address_);
1584 // Give the server time to process the packet.
1585 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1586 // Pause the server so we can access the server's internals without races.
1587 server_thread_->Pause();
1588 QuicDispatcher* dispatcher =
1589 QuicServerPeer::GetDispatcher(server_thread_->server());
1590 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1591 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1592 server_thread_->Resume();
1594 // The connection should not be terminated.
1595 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1596 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1599 // Send a packet from the client with bad encrypted data. The server should not
1600 // tear down the connection.
1601 TEST_P(EndToEndTest, BadEncryptedData) {
1602 ASSERT_TRUE(Initialize());
1604 // Start the connection.
1605 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1606 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1608 scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
1609 client_->client()->session()->connection()->connection_id(), false, false,
1610 1, "At least 20 characters.", PACKET_8BYTE_CONNECTION_ID,
1611 PACKET_6BYTE_SEQUENCE_NUMBER));
1612 // Damage the encrypted data.
1613 string damaged_packet(packet->data(), packet->length());
1614 damaged_packet[30] ^= 0x01;
1615 DVLOG(1) << "Sending bad packet.";
1616 client_writer_->WritePacket(damaged_packet.data(), damaged_packet.length(),
1617 client_->client()->client_address().address(),
1618 server_address_);
1619 // Give the server time to process the packet.
1620 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1621 // This error is sent to the connection's OnError (which ignores it), so the
1622 // dispatcher doesn't see it.
1623 // Pause the server so we can access the server's internals without races.
1624 server_thread_->Pause();
1625 QuicDispatcher* dispatcher =
1626 QuicServerPeer::GetDispatcher(server_thread_->server());
1627 EXPECT_EQ(QUIC_NO_ERROR,
1628 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1629 server_thread_->Resume();
1631 // The connection should not be terminated.
1632 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1633 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1636 } // namespace
1637 } // namespace test
1638 } // namespace tools
1639 } // namespace net