We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blobd38542e5e4883fb6c0b8aad69df496f2b30dcbd9
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/time/time.h"
16 #include "net/base/ip_endpoint.h"
17 #include "net/quic/congestion_control/tcp_cubic_sender.h"
18 #include "net/quic/crypto/aes_128_gcm_12_encrypter.h"
19 #include "net/quic/crypto/null_encrypter.h"
20 #include "net/quic/quic_flags.h"
21 #include "net/quic/quic_framer.h"
22 #include "net/quic/quic_packet_creator.h"
23 #include "net/quic/quic_protocol.h"
24 #include "net/quic/quic_server_id.h"
25 #include "net/quic/quic_utils.h"
26 #include "net/quic/test_tools/quic_connection_peer.h"
27 #include "net/quic/test_tools/quic_flow_controller_peer.h"
28 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
29 #include "net/quic/test_tools/quic_session_peer.h"
30 #include "net/quic/test_tools/quic_test_utils.h"
31 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
32 #include "net/test/gtest_util.h"
33 #include "net/tools/epoll_server/epoll_server.h"
34 #include "net/tools/quic/quic_epoll_connection_helper.h"
35 #include "net/tools/quic/quic_in_memory_cache.h"
36 #include "net/tools/quic/quic_packet_writer_wrapper.h"
37 #include "net/tools/quic/quic_server.h"
38 #include "net/tools/quic/quic_socket_utils.h"
39 #include "net/tools/quic/quic_spdy_client_stream.h"
40 #include "net/tools/quic/test_tools/http_message.h"
41 #include "net/tools/quic/test_tools/packet_dropping_test_writer.h"
42 #include "net/tools/quic/test_tools/quic_client_peer.h"
43 #include "net/tools/quic/test_tools/quic_dispatcher_peer.h"
44 #include "net/tools/quic/test_tools/quic_in_memory_cache_peer.h"
45 #include "net/tools/quic/test_tools/quic_server_peer.h"
46 #include "net/tools/quic/test_tools/quic_test_client.h"
47 #include "net/tools/quic/test_tools/server_thread.h"
48 #include "testing/gtest/include/gtest/gtest.h"
50 using base::StringPiece;
51 using base::WaitableEvent;
52 using net::EpollServer;
53 using net::test::GenerateBody;
54 using net::test::MockQuicConnectionDebugVisitor;
55 using net::test::QuicConnectionPeer;
56 using net::test::QuicFlowControllerPeer;
57 using net::test::QuicSentPacketManagerPeer;
58 using net::test::QuicSessionPeer;
59 using net::test::ReliableQuicStreamPeer;
60 using net::test::ValueRestore;
61 using net::test::kClientDataStreamId1;
62 using net::tools::test::PacketDroppingTestWriter;
63 using net::tools::test::QuicDispatcherPeer;
64 using net::tools::test::QuicServerPeer;
65 using std::ostream;
66 using std::string;
67 using std::vector;
69 namespace net {
70 namespace tools {
71 namespace test {
72 namespace {
74 const char kFooResponseBody[] = "Artichoke hearts make me happy.";
75 const char kBarResponseBody[] = "Palm hearts are pretty delicious, also.";
77 // Run all tests with the cross products of all versions.
78 struct TestParams {
79 TestParams(const QuicVersionVector& client_supported_versions,
80 const QuicVersionVector& server_supported_versions,
81 QuicVersion negotiated_version,
82 bool use_fec,
83 QuicTag congestion_control_tag)
84 : client_supported_versions(client_supported_versions),
85 server_supported_versions(server_supported_versions),
86 negotiated_version(negotiated_version),
87 use_fec(use_fec),
88 congestion_control_tag(congestion_control_tag) {
91 friend ostream& operator<<(ostream& os, const TestParams& p) {
92 os << "{ server_supported_versions: "
93 << QuicVersionVectorToString(p.server_supported_versions);
94 os << " client_supported_versions: "
95 << QuicVersionVectorToString(p.client_supported_versions);
96 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
97 os << " use_fec: " << p.use_fec;
98 os << " congestion_control_tag: "
99 << QuicUtils::TagToString(p.congestion_control_tag) << " }";
100 return os;
103 QuicVersionVector client_supported_versions;
104 QuicVersionVector server_supported_versions;
105 QuicVersion negotiated_version;
106 bool use_fec;
107 QuicTag congestion_control_tag;
110 // Constructs various test permutations.
111 vector<TestParams> GetTestParams() {
112 vector<TestParams> params;
113 QuicVersionVector all_supported_versions = QuicSupportedVersions();
114 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
115 // QuicTag congestion_control_tags[] = {kRENO, kTBBR, kQBIC};
116 QuicTag congestion_control_tags[] = {kRENO, kQBIC};
117 QuicVersionVector spdy3_versions;
118 QuicVersionVector spdy4_versions;
119 for (QuicVersion version : all_supported_versions) {
120 if (version > QUIC_VERSION_23) {
121 spdy4_versions.push_back(version);
122 } else {
123 spdy3_versions.push_back(version);
126 for (size_t congestion_control_index = 0;
127 congestion_control_index < arraysize(congestion_control_tags);
128 congestion_control_index++) {
129 QuicTag congestion_control_tag =
130 congestion_control_tags[congestion_control_index];
131 for (int use_fec = 0; use_fec < 2; ++use_fec) {
132 for (int spdy_version = 3; spdy_version <= 4; ++spdy_version) {
133 const QuicVersionVector* client_versions =
134 spdy_version == 3 ? &spdy3_versions : &spdy4_versions;
135 // Add an entry for server and client supporting all versions.
136 params.push_back(TestParams(*client_versions, all_supported_versions,
137 (*client_versions)[0], use_fec != 0,
138 congestion_control_tag));
140 // Test client supporting all versions and server supporting 1
141 // version. Simulate an old server and exercise version downgrade in
142 // the client. Protocol negotiation should occur. Skip the i = 0 case
143 // because it is essentially the same as the default case.
144 for (QuicVersion version : *client_versions) {
145 QuicVersionVector server_supported_versions;
146 server_supported_versions.push_back(version);
147 params.push_back(TestParams(*client_versions,
148 server_supported_versions,
149 server_supported_versions[0],
150 use_fec != 0, congestion_control_tag));
155 return params;
158 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
159 public:
160 ServerDelegate(TestWriterFactory* writer_factory,
161 QuicDispatcher* dispatcher)
162 : writer_factory_(writer_factory),
163 dispatcher_(dispatcher) {}
164 ~ServerDelegate() override {}
165 void OnPacketSent(WriteResult result) override {
166 writer_factory_->OnPacketSent(result);
168 void OnCanWrite() override { dispatcher_->OnCanWrite(); }
170 private:
171 TestWriterFactory* writer_factory_;
172 QuicDispatcher* dispatcher_;
175 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
176 public:
177 explicit ClientDelegate(QuicClient* client) : client_(client) {}
178 ~ClientDelegate() override {}
179 void OnPacketSent(WriteResult result) override {}
180 void OnCanWrite() override {
181 EpollEvent event(EPOLLOUT, false);
182 client_->OnEvent(client_->fd(), &event);
185 private:
186 QuicClient* client_;
189 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
190 protected:
191 EndToEndTest()
192 : server_hostname_("example.com"),
193 server_started_(false),
194 strike_register_no_startup_period_(false) {
195 net::IPAddressNumber ip;
196 CHECK(net::ParseIPLiteralToNumber("127.0.0.1", &ip));
197 server_address_ = IPEndPoint(ip, 0);
199 client_supported_versions_ = GetParam().client_supported_versions;
200 server_supported_versions_ = GetParam().server_supported_versions;
201 negotiated_version_ = GetParam().negotiated_version;
202 FLAGS_enable_quic_fec = GetParam().use_fec;
204 VLOG(1) << "Using Configuration: " << GetParam();
206 // Use different flow control windows for client/server.
207 client_config_.SetInitialStreamFlowControlWindowToSend(
208 2 * kInitialStreamFlowControlWindowForTest);
209 client_config_.SetInitialSessionFlowControlWindowToSend(
210 2 * kInitialSessionFlowControlWindowForTest);
211 server_config_.SetInitialStreamFlowControlWindowToSend(
212 3 * kInitialStreamFlowControlWindowForTest);
213 server_config_.SetInitialSessionFlowControlWindowToSend(
214 3 * kInitialSessionFlowControlWindowForTest);
216 QuicInMemoryCachePeer::ResetForTests();
217 AddToCache("/foo", 200, "OK", kFooResponseBody);
218 AddToCache("/bar", 200, "OK", kBarResponseBody);
221 ~EndToEndTest() override {
222 // TODO(rtenneti): port RecycleUnusedPort if needed.
223 // RecycleUnusedPort(server_address_.port());
224 QuicInMemoryCachePeer::ResetForTests();
227 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
228 QuicTestClient* client = new QuicTestClient(
229 server_address_,
230 server_hostname_,
231 false, // not secure
232 client_config_,
233 client_supported_versions_);
234 client->UseWriter(writer);
235 client->Connect();
236 return client;
239 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
240 CHECK(client_.get() == nullptr);
241 DVLOG(1) << "Setting client initial stream flow control window: " << window;
242 client_config_.SetInitialStreamFlowControlWindowToSend(window);
245 void set_client_initial_session_flow_control_receive_window(uint32 window) {
246 CHECK(client_.get() == nullptr);
247 DVLOG(1) << "Setting client initial session flow control window: "
248 << window;
249 client_config_.SetInitialSessionFlowControlWindowToSend(window);
252 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
253 CHECK(server_thread_.get() == nullptr);
254 DVLOG(1) << "Setting server initial stream flow control window: "
255 << window;
256 server_config_.SetInitialStreamFlowControlWindowToSend(window);
259 void set_server_initial_session_flow_control_receive_window(uint32 window) {
260 CHECK(server_thread_.get() == nullptr);
261 DVLOG(1) << "Setting server initial session flow control window: "
262 << window;
263 server_config_.SetInitialSessionFlowControlWindowToSend(window);
266 const QuicSentPacketManager *
267 GetSentPacketManagerFromFirstServerSession() const {
268 QuicDispatcher* dispatcher =
269 QuicServerPeer::GetDispatcher(server_thread_->server());
270 QuicSession* session = dispatcher->session_map().begin()->second;
271 return &session->connection()->sent_packet_manager();
274 bool Initialize() {
275 QuicTagVector copt;
276 server_config_.SetConnectionOptionsToSend(copt);
278 // TODO(nimia): Consider setting the congestion control algorithm for the
279 // client as well according to the test parameter.
280 copt.push_back(GetParam().congestion_control_tag);
282 if (GetParam().use_fec) {
283 // Set FEC config in client's connection options and in client session.
284 copt.push_back(kFHDR);
287 client_config_.SetConnectionOptionsToSend(copt);
289 // Start the server first, because CreateQuicClient() attempts
290 // to connect to the server.
291 StartServer();
292 client_.reset(CreateQuicClient(client_writer_));
293 if (GetParam().use_fec) {
294 // Set FecPolicy to always protect data on all streams.
295 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
297 static EpollEvent event(EPOLLOUT, false);
298 client_writer_->Initialize(
299 reinterpret_cast<QuicEpollConnectionHelper*>(
300 QuicConnectionPeer::GetHelper(
301 client_->client()->session()->connection())),
302 new ClientDelegate(client_->client()));
303 return client_->client()->connected();
306 void SetUp() override {
307 // The ownership of these gets transferred to the QuicPacketWriterWrapper
308 // and TestWriterFactory when Initialize() is executed.
309 client_writer_ = new PacketDroppingTestWriter();
310 server_writer_ = new PacketDroppingTestWriter();
313 void TearDown() override { StopServer(); }
315 void StartServer() {
316 server_thread_.reset(
317 new ServerThread(
318 new QuicServer(server_config_, server_supported_versions_),
319 server_address_,
320 strike_register_no_startup_period_));
321 server_thread_->Initialize();
322 server_address_ = IPEndPoint(server_address_.address(),
323 server_thread_->GetPort());
324 QuicDispatcher* dispatcher =
325 QuicServerPeer::GetDispatcher(server_thread_->server());
326 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
327 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
328 packet_writer_factory);
329 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
330 server_writer_->Initialize(
331 QuicDispatcherPeer::GetHelper(dispatcher),
332 new ServerDelegate(packet_writer_factory, dispatcher));
333 server_thread_->Start();
334 server_started_ = true;
337 void StopServer() {
338 if (!server_started_)
339 return;
340 if (server_thread_.get()) {
341 server_thread_->Quit();
342 server_thread_->Join();
346 void AddToCache(StringPiece path,
347 int response_code,
348 StringPiece response_detail,
349 StringPiece body) {
350 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
351 "www.google.com", path, response_code, response_detail, body);
354 void SetPacketLossPercentage(int32 loss) {
355 // TODO(rtenneti): enable when we can do random packet loss tests in
356 // chrome's tree.
357 if (loss != 0 && loss != 100)
358 return;
359 client_writer_->set_fake_packet_loss_percentage(loss);
360 server_writer_->set_fake_packet_loss_percentage(loss);
363 void SetPacketSendDelay(QuicTime::Delta delay) {
364 // TODO(rtenneti): enable when we can do random packet send delay tests in
365 // chrome's tree.
366 // client_writer_->set_fake_packet_delay(delay);
367 // server_writer_->set_fake_packet_delay(delay);
370 void SetReorderPercentage(int32 reorder) {
371 // TODO(rtenneti): enable when we can do random packet reorder tests in
372 // chrome's tree.
373 // client_writer_->set_fake_reorder_percentage(reorder);
374 // server_writer_->set_fake_reorder_percentage(reorder);
377 // Verifies that the client and server connections were both free of packets
378 // being discarded, based on connection stats.
379 // Calls server_thread_ Pause() and Resume(), which may only be called once
380 // per test.
381 void VerifyCleanConnection(bool had_packet_loss) {
382 QuicConnectionStats client_stats =
383 client_->client()->session()->connection()->GetStats();
384 if (!had_packet_loss) {
385 EXPECT_EQ(0u, client_stats.packets_lost);
387 EXPECT_EQ(0u, client_stats.packets_discarded);
388 EXPECT_EQ(0u, client_stats.packets_dropped);
389 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
391 server_thread_->Pause();
392 QuicDispatcher* dispatcher =
393 QuicServerPeer::GetDispatcher(server_thread_->server());
394 ASSERT_EQ(1u, dispatcher->session_map().size());
395 QuicSession* session = dispatcher->session_map().begin()->second;
396 QuicConnectionStats server_stats = session->connection()->GetStats();
397 if (!had_packet_loss) {
398 EXPECT_EQ(0u, server_stats.packets_lost);
400 EXPECT_EQ(0u, server_stats.packets_discarded);
401 // TODO(ianswett): Restore the check for packets_dropped equals 0.
402 // The expect for packets received is equal to packets processed fails
403 // due to version negotiation packets.
404 server_thread_->Resume();
407 IPEndPoint server_address_;
408 string server_hostname_;
409 scoped_ptr<ServerThread> server_thread_;
410 scoped_ptr<QuicTestClient> client_;
411 PacketDroppingTestWriter* client_writer_;
412 PacketDroppingTestWriter* server_writer_;
413 bool server_started_;
414 QuicConfig client_config_;
415 QuicConfig server_config_;
416 QuicVersionVector client_supported_versions_;
417 QuicVersionVector server_supported_versions_;
418 QuicVersion negotiated_version_;
419 bool strike_register_no_startup_period_;
422 // Run all end to end tests with all supported versions.
423 INSTANTIATE_TEST_CASE_P(EndToEndTests,
424 EndToEndTest,
425 ::testing::ValuesIn(GetTestParams()));
427 TEST_P(EndToEndTest, SimpleRequestResponse) {
428 ASSERT_TRUE(Initialize());
430 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
431 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
434 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
435 // try bots) and selectively disable this test.
436 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
437 IPAddressNumber ip;
438 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
439 server_address_ = IPEndPoint(ip, server_address_.port());
440 ASSERT_TRUE(Initialize());
442 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
443 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
446 TEST_P(EndToEndTest, SeparateFinPacket) {
447 ASSERT_TRUE(Initialize());
449 HTTPMessage request(HttpConstants::HTTP_1_1,
450 HttpConstants::POST, "/foo");
451 request.set_has_complete_message(false);
453 // Send a request in two parts: the request and then an empty packet with FIN.
454 client_->SendMessage(request);
455 client_->SendData("", true);
456 client_->WaitForResponse();
457 EXPECT_EQ(kFooResponseBody, client_->response_body());
458 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
460 // Now do the same thing but with a content length.
461 request.AddBody("foo", true);
462 client_->SendMessage(request);
463 client_->SendData("", true);
464 client_->WaitForResponse();
465 EXPECT_EQ(kFooResponseBody, client_->response_body());
466 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
469 TEST_P(EndToEndTest, MultipleRequestResponse) {
470 ASSERT_TRUE(Initialize());
472 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
473 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
474 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
475 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
478 TEST_P(EndToEndTest, MultipleClients) {
479 ASSERT_TRUE(Initialize());
480 scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
482 HTTPMessage request(HttpConstants::HTTP_1_1,
483 HttpConstants::POST, "/foo");
484 request.AddHeader("content-length", "3");
485 request.set_has_complete_message(false);
487 client_->SendMessage(request);
488 client2->SendMessage(request);
490 client_->SendData("bar", true);
491 client_->WaitForResponse();
492 EXPECT_EQ(kFooResponseBody, client_->response_body());
493 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
495 client2->SendData("eep", true);
496 client2->WaitForResponse();
497 EXPECT_EQ(kFooResponseBody, client2->response_body());
498 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
501 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
502 // Send a large enough request to guarantee fragmentation.
503 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
504 AddToCache(huge_request, 200, "OK", kBarResponseBody);
506 ASSERT_TRUE(Initialize());
508 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
509 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
512 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
513 // Send a large enough request to guarantee fragmentation.
514 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
515 AddToCache(huge_request, 200, "OK", kBarResponseBody);
517 ASSERT_TRUE(Initialize());
518 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
519 SetReorderPercentage(50);
521 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
522 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
525 TEST_P(EndToEndTest, PostMissingBytes) {
526 ASSERT_TRUE(Initialize());
528 // Add a content length header with no body.
529 HTTPMessage request(HttpConstants::HTTP_1_1,
530 HttpConstants::POST, "/foo");
531 request.AddHeader("content-length", "3");
532 request.set_skip_message_validation(true);
534 // This should be detected as stream fin without complete request,
535 // triggering an error response.
536 client_->SendCustomSynchronousRequest(request);
537 EXPECT_EQ("bad", client_->response_body());
538 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
541 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
542 // http://crbug.com/297040.
543 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
544 ASSERT_TRUE(Initialize());
546 client_->client()->WaitForCryptoHandshakeConfirmed();
548 // 1 MB body.
549 string body;
550 GenerateBody(&body, 1024 * 1024);
552 HTTPMessage request(HttpConstants::HTTP_1_1,
553 HttpConstants::POST, "/foo");
554 request.AddBody(body, true);
556 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
557 VerifyCleanConnection(false);
560 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
561 ASSERT_TRUE(Initialize());
562 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
564 client_->client()->WaitForCryptoHandshakeConfirmed();
566 // 100 KB body.
567 string body;
568 GenerateBody(&body, 100 * 1024);
570 HTTPMessage request(HttpConstants::HTTP_1_1,
571 HttpConstants::POST, "/foo");
572 request.AddBody(body, true);
574 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
575 VerifyCleanConnection(false);
578 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
579 // Connect with lower fake packet loss than we'd like to test. Until
580 // b/10126687 is fixed, losing handshake packets is pretty brutal.
581 SetPacketLossPercentage(5);
582 ASSERT_TRUE(Initialize());
584 // Wait for the server SHLO before upping the packet loss.
585 client_->client()->WaitForCryptoHandshakeConfirmed();
586 SetPacketLossPercentage(30);
588 // 10 KB body.
589 string body;
590 GenerateBody(&body, 1024 * 10);
592 HTTPMessage request(HttpConstants::HTTP_1_1,
593 HttpConstants::POST, "/foo");
594 request.AddBody(body, true);
596 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
597 VerifyCleanConnection(true);
600 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
601 // Connect with lower fake packet loss than we'd like to test. Until
602 // b/10126687 is fixed, losing handshake packets is pretty brutal.
603 SetPacketLossPercentage(5);
604 ASSERT_TRUE(Initialize());
606 // Wait for the server SHLO before upping the packet loss.
607 client_->client()->WaitForCryptoHandshakeConfirmed();
608 SetPacketLossPercentage(10);
609 client_writer_->set_fake_blocked_socket_percentage(10);
611 // 10 KB body.
612 string body;
613 GenerateBody(&body, 1024 * 10);
615 HTTPMessage request(HttpConstants::HTTP_1_1,
616 HttpConstants::POST, "/foo");
617 request.AddBody(body, true);
619 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
622 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
623 ASSERT_TRUE(Initialize());
625 client_->client()->WaitForCryptoHandshakeConfirmed();
626 // Both of these must be called when the writer is not actively used.
627 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
628 SetReorderPercentage(30);
630 // 1 MB body.
631 string body;
632 GenerateBody(&body, 1024 * 1024);
634 HTTPMessage request(HttpConstants::HTTP_1_1,
635 HttpConstants::POST, "/foo");
636 request.AddBody(body, true);
638 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
641 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
642 // Have the server accept 0-RTT without waiting a startup period.
643 strike_register_no_startup_period_ = true;
645 // Send a request and then disconnect. This prepares the client to attempt
646 // a 0-RTT handshake for the next request.
647 ASSERT_TRUE(Initialize());
649 string body;
650 GenerateBody(&body, 20480);
652 HTTPMessage request(HttpConstants::HTTP_1_1,
653 HttpConstants::POST, "/foo");
654 request.AddBody(body, true);
656 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
657 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
659 client_->Disconnect();
661 // The 0-RTT handshake should succeed.
662 client_->Connect();
663 client_->WaitForResponseForMs(-1);
664 ASSERT_TRUE(client_->client()->connected());
665 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
666 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
668 client_->Disconnect();
670 // Restart the server so that the 0-RTT handshake will take 1 RTT.
671 StopServer();
672 server_writer_ = new PacketDroppingTestWriter();
673 StartServer();
675 client_->Connect();
676 ASSERT_TRUE(client_->client()->connected());
677 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
678 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
679 VerifyCleanConnection(false);
682 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
683 ASSERT_TRUE(Initialize());
684 client_->client()->WaitForCryptoHandshakeConfirmed();
685 server_thread_->WaitForCryptoHandshakeConfirmed();
687 FecPolicy expected_policy =
688 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
690 // Verify that server's FEC configuration is correct.
691 server_thread_->Pause();
692 QuicDispatcher* dispatcher =
693 QuicServerPeer::GetDispatcher(server_thread_->server());
694 ASSERT_EQ(1u, dispatcher->session_map().size());
695 QuicSession* session = dispatcher->session_map().begin()->second;
696 EXPECT_EQ(expected_policy,
697 QuicSessionPeer::GetHeadersStream(session)->fec_policy());
698 server_thread_->Resume();
700 // Verify that client's FEC configuration is correct.
701 EXPECT_EQ(expected_policy,
702 QuicSessionPeer::GetHeadersStream(
703 client_->client()->session())->fec_policy());
704 EXPECT_EQ(expected_policy,
705 client_->GetOrCreateStream()->fec_policy());
708 // TODO(shess): This is flaky on ChromiumOS bots.
709 // http://crbug.com/374871
710 TEST_P(EndToEndTest, DISABLED_LargePostSmallBandwidthLargeBuffer) {
711 ASSERT_TRUE(Initialize());
712 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
713 // 256KB per second with a 256KB buffer from server to client. Wireless
714 // clients commonly have larger buffers, but our max CWND is 200.
715 server_writer_->set_max_bandwidth_and_buffer_size(
716 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
718 client_->client()->WaitForCryptoHandshakeConfirmed();
720 // 1 MB body.
721 string body;
722 GenerateBody(&body, 1024 * 1024);
724 HTTPMessage request(HttpConstants::HTTP_1_1,
725 HttpConstants::POST, "/foo");
726 request.AddBody(body, true);
728 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
729 // This connection will not drop packets, because the buffer size is larger
730 // than the default receive window.
731 VerifyCleanConnection(false);
734 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
735 // Regression test for b/14677858.
736 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
737 // if currently connection level flow control blocked. If set, this results in
738 // an infinite loop in the EpollServer, as the alarm fires and is immediately
739 // rescheduled.
740 ASSERT_TRUE(Initialize());
741 client_->client()->WaitForCryptoHandshakeConfirmed();
743 // Ensure both stream and connection level are flow control blocked by setting
744 // the send window offset to 0.
745 const uint64 flow_control_window =
746 server_config_.GetInitialStreamFlowControlWindowToSend();
747 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
748 QuicSession* session = client_->client()->session();
749 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
750 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
751 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
752 EXPECT_TRUE(session->flow_controller()->IsBlocked());
754 // Make sure that the stream has data pending so that it will be marked as
755 // write blocked when it receives a stream level WINDOW_UPDATE.
756 stream->SendBody("hello", false);
758 // The stream now attempts to write, fails because it is still connection
759 // level flow control blocked, and is added to the write blocked list.
760 QuicWindowUpdateFrame window_update(stream->id(), 2 * flow_control_window);
761 stream->OnWindowUpdateFrame(window_update);
763 // Prior to fixing b/14677858 this call would result in an infinite loop in
764 // Chromium. As a proxy for detecting this, we now check whether the
765 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
766 // connection is still flow control blocked.
767 session->connection()->OnCanWrite();
769 QuicAlarm* resume_writes_alarm =
770 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
771 EXPECT_FALSE(resume_writes_alarm->IsSet());
774 TEST_P(EndToEndTest, InvalidStream) {
775 ASSERT_TRUE(Initialize());
776 client_->client()->WaitForCryptoHandshakeConfirmed();
778 string body;
779 GenerateBody(&body, kMaxPacketSize);
781 HTTPMessage request(HttpConstants::HTTP_1_1,
782 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,
798 HttpConstants::POST, "/foo");
799 request.AddHeader("content-length", "3");
800 request.set_has_complete_message(false);
802 // Set the offset so we won't frame. Otherwise when we pick up termination
803 // before HTTP framing is complete, we send an error and close the stream,
804 // and the second write is picked up as writing on a closed stream.
805 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
806 ASSERT_TRUE(stream != nullptr);
807 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
809 client_->SendData("bar", true);
810 client_->WaitForWriteToFlush();
812 // By default the stream protects itself from writes after terminte is set.
813 // Override this to test the server handling buggy clients.
814 ReliableQuicStreamPeer::SetWriteSideClosed(
815 false, client_->GetOrCreateStream());
817 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
820 TEST_P(EndToEndTest, Timeout) {
821 client_config_.SetIdleConnectionStateLifetime(
822 QuicTime::Delta::FromMicroseconds(500),
823 QuicTime::Delta::FromMicroseconds(500));
824 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
825 // that's enough to validate timeout in this case.
826 Initialize();
827 while (client_->client()->connected()) {
828 client_->client()->WaitForEvents();
832 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
833 // Negotiate 1 max open stream.
834 client_config_.SetMaxStreamsPerConnection(1, 1);
835 ASSERT_TRUE(Initialize());
836 client_->client()->WaitForCryptoHandshakeConfirmed();
838 // Make the client misbehave after negotiation.
839 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
840 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(),
841 kServerMaxStreams + 1);
843 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
844 request.AddHeader("content-length", "3");
845 request.set_has_complete_message(false);
847 // The server supports a small number of additional streams beyond the
848 // negotiated limit. Open enough streams to go beyond that limit.
849 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
850 client_->SendMessage(request);
852 client_->WaitForResponse();
854 EXPECT_FALSE(client_->connected());
855 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
856 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
859 TEST_P(EndToEndTest, NegotiateCongestionControl) {
860 ValueRestore<bool> old_flag(&FLAGS_quic_allow_bbr, true);
861 ASSERT_TRUE(Initialize());
862 client_->client()->WaitForCryptoHandshakeConfirmed();
864 CongestionControlType expected_congestion_control_type = kReno;
865 switch (GetParam().congestion_control_tag) {
866 case kRENO:
867 expected_congestion_control_type = kReno;
868 break;
869 case kTBBR:
870 expected_congestion_control_type = kBBR;
871 break;
872 case kQBIC:
873 expected_congestion_control_type = kCubic;
874 break;
875 default:
876 DLOG(FATAL) << "Unexpected congestion control tag";
879 EXPECT_EQ(expected_congestion_control_type,
880 QuicSentPacketManagerPeer::GetSendAlgorithm(
881 *GetSentPacketManagerFromFirstServerSession())
882 ->GetCongestionControlType());
885 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
886 // Server limits the number of max streams to 2.
887 server_config_.SetMaxStreamsPerConnection(2, 2);
888 // Client tries to negotiate for 10.
889 client_config_.SetMaxStreamsPerConnection(10, 5);
891 ASSERT_TRUE(Initialize());
892 client_->client()->WaitForCryptoHandshakeConfirmed();
893 QuicConfig* client_negotiated_config = client_->client()->session()->config();
894 EXPECT_EQ(2u, client_negotiated_config->MaxStreamsPerConnection());
897 TEST_P(EndToEndTest, ClientSuggestsRTT) {
898 // Client suggests initial RTT, verify it is used.
899 const uint32 kInitialRTT = 20000;
900 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT);
902 ASSERT_TRUE(Initialize());
903 client_->client()->WaitForCryptoHandshakeConfirmed();
904 server_thread_->WaitForCryptoHandshakeConfirmed();
906 // Pause the server so we can access the server's internals without races.
907 server_thread_->Pause();
908 QuicDispatcher* dispatcher =
909 QuicServerPeer::GetDispatcher(server_thread_->server());
910 ASSERT_EQ(1u, dispatcher->session_map().size());
911 const QuicSentPacketManager& client_sent_packet_manager =
912 client_->client()->session()->connection()->sent_packet_manager();
913 const QuicSentPacketManager& server_sent_packet_manager =
914 *GetSentPacketManagerFromFirstServerSession();
916 EXPECT_EQ(kInitialRTT,
917 client_sent_packet_manager.GetRttStats()->initial_rtt_us());
918 EXPECT_EQ(kInitialRTT,
919 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
920 server_thread_->Resume();
923 TEST_P(EndToEndTest, MaxInitialRTT) {
924 // Client tries to suggest twice the server's max initial rtt and the server
925 // uses the max.
926 client_config_.SetInitialRoundTripTimeUsToSend(
927 2 * kMaxInitialRoundTripTimeUs);
929 ASSERT_TRUE(Initialize());
930 client_->client()->WaitForCryptoHandshakeConfirmed();
931 server_thread_->WaitForCryptoHandshakeConfirmed();
933 // Pause the server so we can access the server's internals without races.
934 server_thread_->Pause();
935 QuicDispatcher* dispatcher =
936 QuicServerPeer::GetDispatcher(server_thread_->server());
937 ASSERT_EQ(1u, dispatcher->session_map().size());
938 QuicSession* session = dispatcher->session_map().begin()->second;
939 const QuicSentPacketManager& client_sent_packet_manager =
940 client_->client()->session()->connection()->sent_packet_manager();
942 // Now that acks have been exchanged, the RTT estimate has decreased on the
943 // server and is not infinite on the client.
944 EXPECT_FALSE(
945 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
946 const RttStats& server_rtt_stats =
947 *session->connection()->sent_packet_manager().GetRttStats();
948 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
949 server_rtt_stats.initial_rtt_us());
950 EXPECT_GE(static_cast<int64>(kMaxInitialRoundTripTimeUs),
951 server_rtt_stats.smoothed_rtt().ToMicroseconds());
952 server_thread_->Resume();
955 TEST_P(EndToEndTest, MinInitialRTT) {
956 // Client tries to suggest 0 and the server uses the default.
957 client_config_.SetInitialRoundTripTimeUsToSend(0);
959 ASSERT_TRUE(Initialize());
960 client_->client()->WaitForCryptoHandshakeConfirmed();
961 server_thread_->WaitForCryptoHandshakeConfirmed();
963 // Pause the server so we can access the server's internals without races.
964 server_thread_->Pause();
965 QuicDispatcher* dispatcher =
966 QuicServerPeer::GetDispatcher(server_thread_->server());
967 ASSERT_EQ(1u, dispatcher->session_map().size());
968 QuicSession* session = dispatcher->session_map().begin()->second;
969 const QuicSentPacketManager& client_sent_packet_manager =
970 client_->client()->session()->connection()->sent_packet_manager();
971 const QuicSentPacketManager& server_sent_packet_manager =
972 session->connection()->sent_packet_manager();
974 // Now that acks have been exchanged, the RTT estimate has decreased on the
975 // server and is not infinite on the client.
976 EXPECT_FALSE(
977 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
978 // Expect the default rtt of 100ms.
979 EXPECT_EQ(static_cast<int64>(100 * kNumMicrosPerMilli),
980 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
981 // Ensure the bandwidth is valid.
982 client_sent_packet_manager.BandwidthEstimate();
983 server_sent_packet_manager.BandwidthEstimate();
984 server_thread_->Resume();
987 TEST_P(EndToEndTest, 0ByteConnectionId) {
988 client_config_.SetBytesForConnectionIdToSend(0);
989 ASSERT_TRUE(Initialize());
991 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
992 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
994 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
995 client_->client()->session()->connection());
996 EXPECT_EQ(PACKET_0BYTE_CONNECTION_ID,
997 header->public_header.connection_id_length);
1000 TEST_P(EndToEndTest, 1ByteConnectionId) {
1001 client_config_.SetBytesForConnectionIdToSend(1);
1002 ASSERT_TRUE(Initialize());
1004 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1005 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1006 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1007 client_->client()->session()->connection());
1008 EXPECT_EQ(PACKET_1BYTE_CONNECTION_ID,
1009 header->public_header.connection_id_length);
1012 TEST_P(EndToEndTest, 4ByteConnectionId) {
1013 client_config_.SetBytesForConnectionIdToSend(4);
1014 ASSERT_TRUE(Initialize());
1016 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1017 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1018 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1019 client_->client()->session()->connection());
1020 EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID,
1021 header->public_header.connection_id_length);
1024 TEST_P(EndToEndTest, 8ByteConnectionId) {
1025 client_config_.SetBytesForConnectionIdToSend(8);
1026 ASSERT_TRUE(Initialize());
1028 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1029 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1030 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1031 client_->client()->session()->connection());
1032 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1033 header->public_header.connection_id_length);
1036 TEST_P(EndToEndTest, 15ByteConnectionId) {
1037 client_config_.SetBytesForConnectionIdToSend(15);
1038 ASSERT_TRUE(Initialize());
1040 // Our server is permissive and allows for out of bounds values.
1041 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1042 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1043 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1044 client_->client()->session()->connection());
1045 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1046 header->public_header.connection_id_length);
1049 TEST_P(EndToEndTest, ResetConnection) {
1050 ASSERT_TRUE(Initialize());
1051 client_->client()->WaitForCryptoHandshakeConfirmed();
1053 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1054 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1055 client_->ResetConnection();
1056 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1057 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1060 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1061 SetPacketLossPercentage(1);
1062 ASSERT_TRUE(Initialize());
1063 string large_body;
1064 GenerateBody(&large_body, 10240);
1065 int max_streams = 100;
1067 AddToCache("/large_response", 200, "OK", large_body);;
1069 client_->client()->WaitForCryptoHandshakeConfirmed();
1070 SetPacketLossPercentage(10);
1072 for (int i = 0; i < max_streams; ++i) {
1073 EXPECT_LT(0, client_->SendRequest("/large_response"));
1076 // WaitForEvents waits 50ms and returns true if there are outstanding
1077 // requests.
1078 while (client_->client()->WaitForEvents() == true) {
1082 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1083 ASSERT_TRUE(Initialize());
1084 string small_body;
1085 GenerateBody(&small_body, 256);
1087 AddToCache("/small_response", 200, "OK", small_body);
1089 client_->client()->WaitForCryptoHandshakeConfirmed();
1091 QuicSession* session = client_->client()->session();
1092 // Lose the request.
1093 SetPacketLossPercentage(100);
1094 EXPECT_LT(0, client_->SendRequest("/small_response"));
1095 client_->client()->WaitForEvents();
1096 // Transmit the cancel, and ensure the connection is torn down properly.
1097 SetPacketLossPercentage(0);
1098 QuicStreamId stream_id = kClientDataStreamId1;
1099 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1101 // WaitForEvents waits 50ms and returns true if there are outstanding
1102 // requests.
1103 while (client_->client()->WaitForEvents() == true) {
1105 // It should be completely fine to RST a stream before any data has been
1106 // received for that stream.
1107 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1110 class WrongAddressWriter : public QuicPacketWriterWrapper {
1111 public:
1112 WrongAddressWriter() {
1113 IPAddressNumber ip;
1114 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1115 self_address_ = IPEndPoint(ip, 0);
1118 WriteResult WritePacket(const char* buffer,
1119 size_t buf_len,
1120 const IPAddressNumber& real_self_address,
1121 const IPEndPoint& peer_address) override {
1122 // Use wrong address!
1123 return QuicPacketWriterWrapper::WritePacket(
1124 buffer, buf_len, self_address_.address(), peer_address);
1127 bool IsWriteBlockedDataBuffered() const override { return false; }
1129 IPEndPoint self_address_;
1132 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1133 // Tests that the client's IP can not change during an established QUIC
1134 // connection. If it changes, the connection is closed by the server as we do
1135 // not yet support IP migration.
1136 ASSERT_TRUE(Initialize());
1138 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1139 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1141 WrongAddressWriter* writer = new WrongAddressWriter();
1143 writer->set_writer(new QuicDefaultPacketWriter(client_->client()->fd()));
1144 QuicConnectionPeer::SetWriter(client_->client()->session()->connection(),
1145 writer,
1146 /* owns_writer= */ true);
1148 client_->SendSynchronousRequest("/bar");
1150 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1151 EXPECT_EQ(QUIC_ERROR_MIGRATING_ADDRESS, client_->connection_error());
1154 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1155 // Tests that the client's port can change during an established QUIC
1156 // connection, and that doing so does not result in the connection being
1157 // closed by the server.
1158 ASSERT_TRUE(Initialize());
1160 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1161 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1163 // Store the client address which was used to send the first request.
1164 IPEndPoint old_address = client_->client()->client_address();
1166 // Stop listening on the old FD.
1167 EpollServer* eps = client_->epoll_server();
1168 int old_fd = client_->client()->fd();
1169 eps->UnregisterFD(old_fd);
1170 // Create a new socket before closing the old one, which will result in a new
1171 // ephemeral port.
1172 QuicClientPeer::CreateUDPSocket(client_->client());
1173 close(old_fd);
1175 // The packet writer needs to be updated to use the new FD.
1176 client_->client()->CreateQuicPacketWriter();
1178 // Change the internal state of the client and connection to use the new port,
1179 // this is done because in a real NAT rebinding the client wouldn't see any
1180 // port change, and so expects no change to incoming port.
1181 // This is kind of ugly, but needed as we are simply swapping out the client
1182 // FD rather than any more complex NAT rebinding simulation.
1183 int new_port = client_->client()->client_address().port();
1184 QuicClientPeer::SetClientPort(client_->client(), new_port);
1185 QuicConnectionPeer::SetSelfAddress(
1186 client_->client()->session()->connection(),
1187 IPEndPoint(
1188 client_->client()->session()->connection()->self_address().address(),
1189 new_port));
1191 // Register the new FD for epoll events.
1192 int new_fd = client_->client()->fd();
1193 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1195 // Send a second request, using the new FD.
1196 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1197 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1199 // Verify that the client's ephemeral port is different.
1200 IPEndPoint new_address = client_->client()->client_address();
1201 EXPECT_EQ(old_address.address(), new_address.address());
1202 EXPECT_NE(old_address.port(), new_address.port());
1205 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
1206 // Client and server can set different initial flow control receive windows.
1207 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1208 // in the crypto handshake.
1209 const uint32 kClientStreamIFCW = 123456;
1210 const uint32 kClientSessionIFCW = 234567;
1211 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1212 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1214 const uint32 kServerStreamIFCW = 654321;
1215 const uint32 kServerSessionIFCW = 765432;
1216 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1217 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1219 ASSERT_TRUE(Initialize());
1221 // Values are exchanged during crypto handshake, so wait for that to finish.
1222 client_->client()->WaitForCryptoHandshakeConfirmed();
1223 server_thread_->WaitForCryptoHandshakeConfirmed();
1225 // Open a data stream to make sure the stream level flow control is updated.
1226 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1227 stream->SendBody("hello", false);
1229 // Client should have the right values for server's receive window.
1230 EXPECT_EQ(kServerStreamIFCW,
1231 client_->client()
1232 ->session()
1233 ->config()
1234 ->ReceivedInitialStreamFlowControlWindowBytes());
1235 EXPECT_EQ(kServerSessionIFCW,
1236 client_->client()
1237 ->session()
1238 ->config()
1239 ->ReceivedInitialSessionFlowControlWindowBytes());
1240 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1241 stream->flow_controller()));
1242 EXPECT_EQ(kServerSessionIFCW,
1243 QuicFlowControllerPeer::SendWindowOffset(
1244 client_->client()->session()->flow_controller()));
1246 // Server should have the right values for client's receive window.
1247 server_thread_->Pause();
1248 QuicDispatcher* dispatcher =
1249 QuicServerPeer::GetDispatcher(server_thread_->server());
1250 QuicSession* session = dispatcher->session_map().begin()->second;
1251 EXPECT_EQ(kClientStreamIFCW,
1252 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1253 EXPECT_EQ(kClientSessionIFCW,
1254 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1255 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1256 session->flow_controller()));
1257 server_thread_->Resume();
1260 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1261 // The special headers and crypto streams should be subject to per-stream flow
1262 // control limits, but should not be subject to connection level flow control.
1263 const uint32 kStreamIFCW = 123456;
1264 const uint32 kSessionIFCW = 234567;
1265 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
1266 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
1267 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
1268 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
1270 ASSERT_TRUE(Initialize());
1272 // Wait for crypto handshake to finish. This should have contributed to the
1273 // crypto stream flow control window, but not affected the session flow
1274 // control window.
1275 client_->client()->WaitForCryptoHandshakeConfirmed();
1276 server_thread_->WaitForCryptoHandshakeConfirmed();
1278 QuicCryptoStream* crypto_stream =
1279 QuicSessionPeer::GetCryptoStream(client_->client()->session());
1280 EXPECT_LT(
1281 QuicFlowControllerPeer::SendWindowSize(crypto_stream->flow_controller()),
1282 kStreamIFCW);
1283 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1284 client_->client()->session()->flow_controller()));
1286 // Send a request with no body, and verify that the connection level window
1287 // has not been affected.
1288 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1290 QuicHeadersStream* headers_stream =
1291 QuicSessionPeer::GetHeadersStream(client_->client()->session());
1292 EXPECT_LT(
1293 QuicFlowControllerPeer::SendWindowSize(headers_stream->flow_controller()),
1294 kStreamIFCW);
1295 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1296 client_->client()->session()->flow_controller()));
1298 // Server should be in a similar state: connection flow control window should
1299 // not have any bytes marked as received.
1300 server_thread_->Pause();
1301 QuicDispatcher* dispatcher =
1302 QuicServerPeer::GetDispatcher(server_thread_->server());
1303 QuicSession* session = dispatcher->session_map().begin()->second;
1304 QuicFlowController* server_connection_flow_controller =
1305 session->flow_controller();
1306 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
1307 server_connection_flow_controller));
1308 server_thread_->Resume();
1311 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1312 // Regression test for b/16010251.
1313 // A stream created on receipt of a simple request with no body will never get
1314 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1315 // the locally closed streams map: it will never be removed if so.
1316 ASSERT_TRUE(Initialize());
1318 // Send a simple headers only request, and receive response.
1319 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1320 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1322 // Now verify that the server is not waiting for a final FIN or RST.
1323 server_thread_->Pause();
1324 QuicDispatcher* dispatcher =
1325 QuicServerPeer::GetDispatcher(server_thread_->server());
1326 QuicSession* session = dispatcher->session_map().begin()->second;
1327 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1328 session).size());
1329 server_thread_->Resume();
1332 // A TestAckNotifierDelegate verifies that its OnAckNotification method has been
1333 // called exactly once on destruction.
1334 class TestAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
1335 public:
1336 TestAckNotifierDelegate() {}
1338 void OnAckNotification(int /*num_retransmitted_packets*/,
1339 int /*num_retransmitted_bytes*/,
1340 QuicTime::Delta /*delta_largest_observed*/) override {
1341 ASSERT_FALSE(has_been_notified_);
1342 has_been_notified_ = true;
1345 bool has_been_notified() const { return has_been_notified_; }
1347 protected:
1348 // Object is ref counted.
1349 ~TestAckNotifierDelegate() override { EXPECT_TRUE(has_been_notified_); }
1351 private:
1352 bool has_been_notified_ = false;
1355 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
1356 // Verify that even in the presence of packet loss and occasionally blocked
1357 // socket, an AckNotifierDelegate will get informed that the data it is
1358 // interested in has been ACKed. This tests end-to-end ACK notification, and
1359 // demonstrates that retransmissions do not break this functionality.
1360 SetPacketLossPercentage(5);
1361 ASSERT_TRUE(Initialize());
1363 // Wait for the server SHLO before upping the packet loss.
1364 client_->client()->WaitForCryptoHandshakeConfirmed();
1365 SetPacketLossPercentage(30);
1366 client_writer_->set_fake_blocked_socket_percentage(10);
1368 // Create a POST request and send the headers only.
1369 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1370 request.set_has_complete_message(false);
1371 client_->SendMessage(request);
1373 // The TestAckNotifierDelegate will cause a failure if not notified.
1374 scoped_refptr<TestAckNotifierDelegate> delegate(new TestAckNotifierDelegate);
1376 // Test the AckNotifier's ability to track multiple packets by making the
1377 // request body exceed the size of a single packet.
1378 string request_string =
1379 "a request body bigger than one packet" + string(kMaxPacketSize, '.');
1381 // Send the request, and register the delegate for ACKs.
1382 client_->SendData(request_string, true, delegate.get());
1383 client_->WaitForResponse();
1384 EXPECT_EQ(kFooResponseBody, client_->response_body());
1385 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1387 // Send another request to flush out any pending ACKs on the server.
1388 client_->SendSynchronousRequest(request_string);
1390 // Pause the server to avoid races.
1391 server_thread_->Pause();
1392 // Make sure the delegate does get the notification it expects.
1393 while (!delegate->has_been_notified()) {
1394 // Waits for up to 50 ms.
1395 client_->client()->WaitForEvents();
1397 server_thread_->Resume();
1400 // Send a public reset from the server for a different connection ID.
1401 // It should be ignored.
1402 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
1403 ASSERT_TRUE(Initialize());
1405 // Send the public reset.
1406 QuicConnectionId incorrect_connection_id =
1407 client_->client()->session()->connection()->connection_id() + 1;
1408 QuicPublicResetPacket header;
1409 header.public_header.connection_id = incorrect_connection_id;
1410 header.public_header.reset_flag = true;
1411 header.public_header.version_flag = false;
1412 header.rejected_sequence_number = 10101;
1413 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1414 Perspective::IS_SERVER);
1415 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1416 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1417 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1418 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1419 .Times(1);
1420 // We must pause the server's thread in order to call WritePacket without
1421 // race conditions.
1422 server_thread_->Pause();
1423 server_writer_->WritePacket(packet->data(), packet->length(),
1424 server_address_.address(),
1425 client_->client()->client_address());
1426 server_thread_->Resume();
1428 // The connection should be unaffected.
1429 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1430 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1432 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1435 // Send a public reset from the client for a different connection ID.
1436 // It should be ignored.
1437 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
1438 ASSERT_TRUE(Initialize());
1440 // Send the public reset.
1441 QuicConnectionId incorrect_connection_id =
1442 client_->client()->session()->connection()->connection_id() + 1;
1443 QuicPublicResetPacket header;
1444 header.public_header.connection_id = incorrect_connection_id;
1445 header.public_header.reset_flag = true;
1446 header.public_header.version_flag = false;
1447 header.rejected_sequence_number = 10101;
1448 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1449 Perspective::IS_CLIENT);
1450 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1451 client_writer_->WritePacket(packet->data(), packet->length(),
1452 client_->client()->client_address().address(),
1453 server_address_);
1455 // The connection should be unaffected.
1456 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1457 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1460 // Send a version negotiation packet from the server for a different
1461 // connection ID. It should be ignored.
1462 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
1463 ASSERT_TRUE(Initialize());
1465 // Send the version negotiation packet.
1466 QuicConnectionId incorrect_connection_id =
1467 client_->client()->session()->connection()->connection_id() + 1;
1468 QuicVersionNegotiationPacket header;
1469 header.connection_id = incorrect_connection_id;
1470 header.reset_flag = true;
1471 header.version_flag = true;
1472 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1473 Perspective::IS_SERVER);
1474 scoped_ptr<QuicEncryptedPacket> packet(
1475 framer.BuildVersionNegotiationPacket(header, server_supported_versions_));
1476 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1477 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1478 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1479 .Times(1);
1480 // We must pause the server's thread in order to call WritePacket without
1481 // race conditions.
1482 server_thread_->Pause();
1483 server_writer_->WritePacket(packet->data(), packet->length(),
1484 server_address_.address(),
1485 client_->client()->client_address());
1486 server_thread_->Resume();
1488 // The connection should be unaffected.
1489 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1490 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1492 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1495 } // namespace
1496 } // namespace test
1497 } // namespace tools
1498 } // namespace net