Fix "#if defined(DEBUG)" statements
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blobedcd0ce416ffb1bf25610183172e98160489339a
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::QuicConnectionPeer;
55 using net::test::QuicFlowControllerPeer;
56 using net::test::QuicSentPacketManagerPeer;
57 using net::test::QuicSessionPeer;
58 using net::test::ReliableQuicStreamPeer;
59 using net::test::ValueRestore;
60 using net::test::kClientDataStreamId1;
61 using net::tools::test::PacketDroppingTestWriter;
62 using net::tools::test::QuicDispatcherPeer;
63 using net::tools::test::QuicServerPeer;
64 using std::ostream;
65 using std::string;
66 using std::vector;
68 namespace net {
69 namespace tools {
70 namespace test {
71 namespace {
73 const char* kFooResponseBody = "Artichoke hearts make me happy.";
74 const char* kBarResponseBody = "Palm hearts are pretty delicious, also.";
76 // Run all tests with the cross products of all versions.
77 struct TestParams {
78 TestParams(const QuicVersionVector& client_supported_versions,
79 const QuicVersionVector& server_supported_versions,
80 QuicVersion negotiated_version,
81 bool use_pacing,
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_pacing(use_pacing),
88 use_fec(use_fec),
89 congestion_control_tag(congestion_control_tag) {
92 friend ostream& operator<<(ostream& os, const TestParams& p) {
93 os << "{ server_supported_versions: "
94 << QuicVersionVectorToString(p.server_supported_versions);
95 os << " client_supported_versions: "
96 << QuicVersionVectorToString(p.client_supported_versions);
97 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
98 os << " use_pacing: " << p.use_pacing;
99 os << " use_fec: " << p.use_fec;
100 os << " congestion_control_tag: "
101 << QuicUtils::TagToString(p.congestion_control_tag) << " }";
102 return os;
105 QuicVersionVector client_supported_versions;
106 QuicVersionVector server_supported_versions;
107 QuicVersion negotiated_version;
108 bool use_pacing;
109 bool use_fec;
110 QuicTag congestion_control_tag;
113 // Constructs various test permutations.
114 vector<TestParams> GetTestParams() {
115 vector<TestParams> params;
116 QuicVersionVector all_supported_versions = QuicSupportedVersions();
117 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
118 // QuicTag congestion_control_tags[] = {kRENO, kTBBR, kQBIC};
119 QuicTag congestion_control_tags[] = {kRENO, kQBIC};
120 for (size_t congestion_control_index = 0;
121 congestion_control_index < arraysize(congestion_control_tags);
122 congestion_control_index++) {
123 QuicTag congestion_control_tag =
124 congestion_control_tags[congestion_control_index];
125 for (int use_fec = 0; use_fec < 2; ++use_fec) {
126 for (int use_pacing = 0; use_pacing < 2; ++use_pacing) {
127 // Add an entry for server and client supporting all versions.
128 params.push_back(TestParams(all_supported_versions,
129 all_supported_versions,
130 all_supported_versions[0],
131 use_pacing != 0,
132 use_fec != 0,
133 congestion_control_tag));
135 // Test client supporting all versions and server supporting 1 version.
136 // Simulate an old server and exercise version downgrade in the client.
137 // Protocol negotiation should occur. Skip the i = 0 case because it is
138 // essentially the same as the default case.
139 for (size_t i = 1; i < all_supported_versions.size(); ++i) {
140 QuicVersionVector server_supported_versions;
141 server_supported_versions.push_back(all_supported_versions[i]);
142 params.push_back(TestParams(all_supported_versions,
143 server_supported_versions,
144 server_supported_versions[0],
145 use_pacing != 0,
146 use_fec != 0,
147 congestion_control_tag));
152 return params;
155 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
156 public:
157 ServerDelegate(TestWriterFactory* writer_factory,
158 QuicDispatcher* dispatcher)
159 : writer_factory_(writer_factory),
160 dispatcher_(dispatcher) {}
161 virtual ~ServerDelegate() {}
162 virtual void OnPacketSent(WriteResult result) override {
163 writer_factory_->OnPacketSent(result);
165 virtual void OnCanWrite() override { dispatcher_->OnCanWrite(); }
166 private:
167 TestWriterFactory* writer_factory_;
168 QuicDispatcher* dispatcher_;
171 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
172 public:
173 explicit ClientDelegate(QuicClient* client) : client_(client) {}
174 virtual ~ClientDelegate() {}
175 virtual void OnPacketSent(WriteResult result) override {}
176 virtual void OnCanWrite() override {
177 EpollEvent event(EPOLLOUT, false);
178 client_->OnEvent(client_->fd(), &event);
180 private:
181 QuicClient* client_;
184 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
185 protected:
186 EndToEndTest()
187 : server_hostname_("example.com"),
188 server_started_(false),
189 strike_register_no_startup_period_(false) {
190 net::IPAddressNumber ip;
191 CHECK(net::ParseIPLiteralToNumber("127.0.0.1", &ip));
192 server_address_ = IPEndPoint(ip, 0);
194 client_supported_versions_ = GetParam().client_supported_versions;
195 server_supported_versions_ = GetParam().server_supported_versions;
196 negotiated_version_ = GetParam().negotiated_version;
197 FLAGS_enable_quic_fec = GetParam().use_fec;
199 VLOG(1) << "Using Configuration: " << GetParam();
201 // Use different flow control windows for client/server.
202 client_config_.SetInitialFlowControlWindowToSend(
203 2 * kInitialSessionFlowControlWindowForTest);
204 client_config_.SetInitialStreamFlowControlWindowToSend(
205 2 * kInitialStreamFlowControlWindowForTest);
206 client_config_.SetInitialSessionFlowControlWindowToSend(
207 2 * kInitialSessionFlowControlWindowForTest);
208 server_config_.SetInitialFlowControlWindowToSend(
209 3 * kInitialSessionFlowControlWindowForTest);
210 server_config_.SetInitialStreamFlowControlWindowToSend(
211 3 * kInitialStreamFlowControlWindowForTest);
212 server_config_.SetInitialSessionFlowControlWindowToSend(
213 3 * kInitialSessionFlowControlWindowForTest);
215 QuicInMemoryCachePeer::ResetForTests();
216 AddToCache("GET", "https://www.google.com/foo",
217 "HTTP/1.1", "200", "OK", kFooResponseBody);
218 AddToCache("GET", "https://www.google.com/bar",
219 "HTTP/1.1", "200", "OK", kBarResponseBody);
222 virtual ~EndToEndTest() {
223 // TODO(rtenneti): port RecycleUnusedPort if needed.
224 // RecycleUnusedPort(server_address_.port());
225 QuicInMemoryCachePeer::ResetForTests();
228 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
229 QuicTestClient* client = new QuicTestClient(
230 server_address_,
231 server_hostname_,
232 false, // not secure
233 client_config_,
234 client_supported_versions_);
235 client->UseWriter(writer);
236 client->Connect();
237 return client;
240 void set_client_initial_flow_control_receive_window(uint32 window) {
241 CHECK(client_.get() == nullptr);
242 DVLOG(1) << "Setting client initial flow control window: " << window;
243 client_config_.SetInitialFlowControlWindowToSend(window);
246 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
247 CHECK(client_.get() == nullptr);
248 DVLOG(1) << "Setting client initial stream flow control window: " << window;
249 client_config_.SetInitialStreamFlowControlWindowToSend(window);
252 void set_client_initial_session_flow_control_receive_window(uint32 window) {
253 CHECK(client_.get() == nullptr);
254 DVLOG(1) << "Setting client initial session flow control window: "
255 << window;
256 client_config_.SetInitialSessionFlowControlWindowToSend(window);
259 void set_server_initial_flow_control_receive_window(uint32 window) {
260 CHECK(server_thread_.get() == nullptr);
261 DVLOG(1) << "Setting server initial flow control window: " << window;
262 server_config_.SetInitialFlowControlWindowToSend(window);
265 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
266 CHECK(server_thread_.get() == nullptr);
267 DVLOG(1) << "Setting server initial stream flow control window: "
268 << window;
269 server_config_.SetInitialStreamFlowControlWindowToSend(window);
272 void set_server_initial_session_flow_control_receive_window(uint32 window) {
273 CHECK(server_thread_.get() == nullptr);
274 DVLOG(1) << "Setting server initial session flow control window: "
275 << window;
276 server_config_.SetInitialSessionFlowControlWindowToSend(window);
279 const QuicSentPacketManager *
280 GetSentPacketManagerFromFirstServerSession() const {
281 QuicDispatcher* dispatcher =
282 QuicServerPeer::GetDispatcher(server_thread_->server());
283 QuicSession* session = dispatcher->session_map().begin()->second;
284 return &session->connection()->sent_packet_manager();
287 bool Initialize() {
288 QuicTagVector copt;
290 if (GetParam().use_pacing) {
291 copt.push_back(kPACE);
293 server_config_.SetConnectionOptionsToSend(copt);
295 // TODO(nimia): Consider setting the congestion control algorithm for the
296 // client as well according to the test parameter.
297 copt.push_back(GetParam().congestion_control_tag);
299 if (GetParam().use_fec) {
300 // Set FEC config in client's connection options and in client session.
301 copt.push_back(kFHDR);
304 client_config_.SetConnectionOptionsToSend(copt);
306 // Start the server first, because CreateQuicClient() attempts
307 // to connect to the server.
308 StartServer();
309 client_.reset(CreateQuicClient(client_writer_));
310 if (GetParam().use_fec) {
311 // Set FecPolicy to always protect data on all streams.
312 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
314 static EpollEvent event(EPOLLOUT, false);
315 client_writer_->Initialize(
316 reinterpret_cast<QuicEpollConnectionHelper*>(
317 QuicConnectionPeer::GetHelper(
318 client_->client()->session()->connection())),
319 new ClientDelegate(client_->client()));
320 return client_->client()->connected();
323 virtual void SetUp() override {
324 // The ownership of these gets transferred to the QuicPacketWriterWrapper
325 // and TestWriterFactory when Initialize() is executed.
326 client_writer_ = new PacketDroppingTestWriter();
327 server_writer_ = new PacketDroppingTestWriter();
330 virtual void TearDown() override {
331 StopServer();
334 void StartServer() {
335 server_thread_.reset(
336 new ServerThread(
337 new QuicServer(server_config_, server_supported_versions_),
338 server_address_,
339 strike_register_no_startup_period_));
340 server_thread_->Initialize();
341 server_address_ = IPEndPoint(server_address_.address(),
342 server_thread_->GetPort());
343 QuicDispatcher* dispatcher =
344 QuicServerPeer::GetDispatcher(server_thread_->server());
345 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
346 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
347 packet_writer_factory);
348 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
349 server_writer_->Initialize(
350 QuicDispatcherPeer::GetHelper(dispatcher),
351 new ServerDelegate(packet_writer_factory, dispatcher));
352 server_thread_->Start();
353 server_started_ = true;
356 void StopServer() {
357 if (!server_started_)
358 return;
359 if (server_thread_.get()) {
360 server_thread_->Quit();
361 server_thread_->Join();
365 void AddToCache(StringPiece method,
366 StringPiece path,
367 StringPiece version,
368 StringPiece response_code,
369 StringPiece response_detail,
370 StringPiece body) {
371 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
372 method, path, version, response_code, response_detail, body);
375 void SetPacketLossPercentage(int32 loss) {
376 // TODO(rtenneti): enable when we can do random packet loss tests in
377 // chrome's tree.
378 if (loss != 0 && loss != 100)
379 return;
380 client_writer_->set_fake_packet_loss_percentage(loss);
381 server_writer_->set_fake_packet_loss_percentage(loss);
384 void SetPacketSendDelay(QuicTime::Delta delay) {
385 // TODO(rtenneti): enable when we can do random packet send delay tests in
386 // chrome's tree.
387 // client_writer_->set_fake_packet_delay(delay);
388 // server_writer_->set_fake_packet_delay(delay);
391 void SetReorderPercentage(int32 reorder) {
392 // TODO(rtenneti): enable when we can do random packet reorder tests in
393 // chrome's tree.
394 // client_writer_->set_fake_reorder_percentage(reorder);
395 // server_writer_->set_fake_reorder_percentage(reorder);
398 // Verifies that the client and server connections were both free of packets
399 // being discarded, based on connection stats.
400 // Calls server_thread_ Pause() and Resume(), which may only be called once
401 // per test.
402 void VerifyCleanConnection(bool had_packet_loss) {
403 QuicConnectionStats client_stats =
404 client_->client()->session()->connection()->GetStats();
405 if (!had_packet_loss) {
406 EXPECT_EQ(0u, client_stats.packets_lost);
408 EXPECT_EQ(0u, client_stats.packets_discarded);
409 EXPECT_EQ(0u, client_stats.packets_dropped);
410 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
412 server_thread_->Pause();
413 QuicDispatcher* dispatcher =
414 QuicServerPeer::GetDispatcher(server_thread_->server());
415 ASSERT_EQ(1u, dispatcher->session_map().size());
416 QuicSession* session = dispatcher->session_map().begin()->second;
417 QuicConnectionStats server_stats = session->connection()->GetStats();
418 if (!had_packet_loss) {
419 EXPECT_EQ(0u, server_stats.packets_lost);
421 EXPECT_EQ(0u, server_stats.packets_discarded);
422 // TODO(ianswett): Restore the check for packets_dropped equals 0.
423 // The expect for packets received is equal to packets processed fails
424 // due to version negotiation packets.
425 server_thread_->Resume();
428 IPEndPoint server_address_;
429 string server_hostname_;
430 scoped_ptr<ServerThread> server_thread_;
431 scoped_ptr<QuicTestClient> client_;
432 PacketDroppingTestWriter* client_writer_;
433 PacketDroppingTestWriter* server_writer_;
434 bool server_started_;
435 QuicConfig client_config_;
436 QuicConfig server_config_;
437 QuicVersionVector client_supported_versions_;
438 QuicVersionVector server_supported_versions_;
439 QuicVersion negotiated_version_;
440 bool strike_register_no_startup_period_;
443 // Run all end to end tests with all supported versions.
444 INSTANTIATE_TEST_CASE_P(EndToEndTests,
445 EndToEndTest,
446 ::testing::ValuesIn(GetTestParams()));
448 TEST_P(EndToEndTest, SimpleRequestResponse) {
449 ASSERT_TRUE(Initialize());
451 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
452 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
455 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
456 // try bots) and selectively disable this test.
457 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
458 IPAddressNumber ip;
459 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
460 server_address_ = IPEndPoint(ip, server_address_.port());
461 ASSERT_TRUE(Initialize());
463 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
464 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
467 TEST_P(EndToEndTest, SeparateFinPacket) {
468 ASSERT_TRUE(Initialize());
470 HTTPMessage request(HttpConstants::HTTP_1_1,
471 HttpConstants::POST, "/foo");
472 request.set_has_complete_message(false);
474 client_->SendMessage(request);
476 client_->SendData(string(), true);
478 client_->WaitForResponse();
479 EXPECT_EQ(kFooResponseBody, client_->response_body());
480 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
482 request.AddBody("foo", true);
484 client_->SendMessage(request);
485 client_->SendData(string(), true);
486 client_->WaitForResponse();
487 EXPECT_EQ(kFooResponseBody, client_->response_body());
488 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
491 TEST_P(EndToEndTest, MultipleRequestResponse) {
492 ASSERT_TRUE(Initialize());
494 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
495 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
496 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
497 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
500 TEST_P(EndToEndTest, MultipleClients) {
501 ASSERT_TRUE(Initialize());
502 scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
504 HTTPMessage request(HttpConstants::HTTP_1_1,
505 HttpConstants::POST, "/foo");
506 request.AddHeader("content-length", "3");
507 request.set_has_complete_message(false);
509 client_->SendMessage(request);
510 client2->SendMessage(request);
512 client_->SendData("bar", true);
513 client_->WaitForResponse();
514 EXPECT_EQ(kFooResponseBody, client_->response_body());
515 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
517 client2->SendData("eep", true);
518 client2->WaitForResponse();
519 EXPECT_EQ(kFooResponseBody, client2->response_body());
520 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
523 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
524 // Send a large enough request to guarantee fragmentation.
525 string huge_request =
526 "https://www.google.com/some/path?query=" + string(kMaxPacketSize, '.');
527 AddToCache("GET", huge_request, "HTTP/1.1", "200", "OK", kBarResponseBody);
529 ASSERT_TRUE(Initialize());
531 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
532 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
535 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
536 // Send a large enough request to guarantee fragmentation.
537 string huge_request =
538 "https://www.google.com/some/path?query=" + string(kMaxPacketSize, '.');
539 AddToCache("GET", huge_request, "HTTP/1.1", "200", "OK", kBarResponseBody);
541 ASSERT_TRUE(Initialize());
542 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
543 SetReorderPercentage(50);
545 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
546 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
549 TEST_P(EndToEndTest, PostMissingBytes) {
550 ASSERT_TRUE(Initialize());
552 // Add a content length header with no body.
553 HTTPMessage request(HttpConstants::HTTP_1_1,
554 HttpConstants::POST, "/foo");
555 request.AddHeader("content-length", "3");
556 request.set_skip_message_validation(true);
558 // This should be detected as stream fin without complete request,
559 // triggering an error response.
560 client_->SendCustomSynchronousRequest(request);
561 EXPECT_EQ("bad", client_->response_body());
562 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
565 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
566 // http://crbug.com/297040.
567 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
568 ASSERT_TRUE(Initialize());
570 client_->client()->WaitForCryptoHandshakeConfirmed();
572 // 1 MB body.
573 string body;
574 GenerateBody(&body, 1024 * 1024);
576 HTTPMessage request(HttpConstants::HTTP_1_1,
577 HttpConstants::POST, "/foo");
578 request.AddBody(body, true);
580 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
581 VerifyCleanConnection(false);
584 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
585 ASSERT_TRUE(Initialize());
586 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
588 client_->client()->WaitForCryptoHandshakeConfirmed();
590 // 100 KB body.
591 string body;
592 GenerateBody(&body, 100 * 1024);
594 HTTPMessage request(HttpConstants::HTTP_1_1,
595 HttpConstants::POST, "/foo");
596 request.AddBody(body, true);
598 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
599 VerifyCleanConnection(false);
602 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
603 // Connect with lower fake packet loss than we'd like to test. Until
604 // b/10126687 is fixed, losing handshake packets is pretty brutal.
605 SetPacketLossPercentage(5);
606 ASSERT_TRUE(Initialize());
608 // Wait for the server SHLO before upping the packet loss.
609 client_->client()->WaitForCryptoHandshakeConfirmed();
610 SetPacketLossPercentage(30);
612 // 10 KB body.
613 string body;
614 GenerateBody(&body, 1024 * 10);
616 HTTPMessage request(HttpConstants::HTTP_1_1,
617 HttpConstants::POST, "/foo");
618 request.AddBody(body, true);
620 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
621 VerifyCleanConnection(true);
624 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
625 // Connect with lower fake packet loss than we'd like to test. Until
626 // b/10126687 is fixed, losing handshake packets is pretty brutal.
627 SetPacketLossPercentage(5);
628 ASSERT_TRUE(Initialize());
630 // Wait for the server SHLO before upping the packet loss.
631 client_->client()->WaitForCryptoHandshakeConfirmed();
632 SetPacketLossPercentage(10);
633 client_writer_->set_fake_blocked_socket_percentage(10);
635 // 10 KB body.
636 string body;
637 GenerateBody(&body, 1024 * 10);
639 HTTPMessage request(HttpConstants::HTTP_1_1,
640 HttpConstants::POST, "/foo");
641 request.AddBody(body, true);
643 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
646 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
647 ASSERT_TRUE(Initialize());
649 client_->client()->WaitForCryptoHandshakeConfirmed();
650 // Both of these must be called when the writer is not actively used.
651 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
652 SetReorderPercentage(30);
654 // 1 MB body.
655 string body;
656 GenerateBody(&body, 1024 * 1024);
658 HTTPMessage request(HttpConstants::HTTP_1_1,
659 HttpConstants::POST, "/foo");
660 request.AddBody(body, true);
662 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
665 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
666 // Have the server accept 0-RTT without waiting a startup period.
667 strike_register_no_startup_period_ = true;
669 // Send a request and then disconnect. This prepares the client to attempt
670 // a 0-RTT handshake for the next request.
671 ASSERT_TRUE(Initialize());
673 string body;
674 GenerateBody(&body, 20480);
676 HTTPMessage request(HttpConstants::HTTP_1_1,
677 HttpConstants::POST, "/foo");
678 request.AddBody(body, true);
680 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
681 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
683 client_->Disconnect();
685 // The 0-RTT handshake should succeed.
686 client_->Connect();
687 client_->WaitForResponseForMs(-1);
688 ASSERT_TRUE(client_->client()->connected());
689 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
690 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
692 client_->Disconnect();
694 // Restart the server so that the 0-RTT handshake will take 1 RTT.
695 StopServer();
696 server_writer_ = new PacketDroppingTestWriter();
697 StartServer();
699 client_->Connect();
700 ASSERT_TRUE(client_->client()->connected());
701 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
702 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
703 VerifyCleanConnection(false);
706 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
707 ASSERT_TRUE(Initialize());
708 client_->client()->WaitForCryptoHandshakeConfirmed();
709 server_thread_->WaitForCryptoHandshakeConfirmed();
711 FecPolicy expected_policy =
712 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
714 // Verify that server's FEC configuration is correct.
715 server_thread_->Pause();
716 QuicDispatcher* dispatcher =
717 QuicServerPeer::GetDispatcher(server_thread_->server());
718 ASSERT_EQ(1u, dispatcher->session_map().size());
719 QuicSession* session = dispatcher->session_map().begin()->second;
720 EXPECT_EQ(expected_policy,
721 QuicSessionPeer::GetHeadersStream(session)->fec_policy());
722 server_thread_->Resume();
724 // Verify that client's FEC configuration is correct.
725 EXPECT_EQ(expected_policy,
726 QuicSessionPeer::GetHeadersStream(
727 client_->client()->session())->fec_policy());
728 EXPECT_EQ(expected_policy,
729 client_->GetOrCreateStream()->fec_policy());
732 // TODO(shess): This is flaky on ChromiumOS bots.
733 // http://crbug.com/374871
734 TEST_P(EndToEndTest, DISABLED_LargePostSmallBandwidthLargeBuffer) {
735 ASSERT_TRUE(Initialize());
736 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
737 // 256KB per second with a 256KB buffer from server to client. Wireless
738 // clients commonly have larger buffers, but our max CWND is 200.
739 server_writer_->set_max_bandwidth_and_buffer_size(
740 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
742 client_->client()->WaitForCryptoHandshakeConfirmed();
744 // 1 MB body.
745 string body;
746 GenerateBody(&body, 1024 * 1024);
748 HTTPMessage request(HttpConstants::HTTP_1_1,
749 HttpConstants::POST, "/foo");
750 request.AddBody(body, true);
752 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
753 // This connection will not drop packets, because the buffer size is larger
754 // than the default receive window.
755 VerifyCleanConnection(false);
758 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
759 // Regression test for b/14677858.
760 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
761 // if currently connection level flow control blocked. If set, this results in
762 // an infinite loop in the EpollServer, as the alarm fires and is immediately
763 // rescheduled.
764 ASSERT_TRUE(Initialize());
765 client_->client()->WaitForCryptoHandshakeConfirmed();
767 // Ensure both stream and connection level are flow control blocked by setting
768 // the send window offset to 0.
769 const uint64 kFlowControlWindow =
770 server_config_.GetInitialFlowControlWindowToSend();
771 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
772 QuicSession* session = client_->client()->session();
773 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
774 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
775 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
776 EXPECT_TRUE(session->flow_controller()->IsBlocked());
778 // Make sure that the stream has data pending so that it will be marked as
779 // write blocked when it receives a stream level WINDOW_UPDATE.
780 stream->SendBody("hello", false);
782 // The stream now attempts to write, fails because it is still connection
783 // level flow control blocked, and is added to the write blocked list.
784 QuicWindowUpdateFrame window_update(stream->id(), 2 * kFlowControlWindow);
785 stream->OnWindowUpdateFrame(window_update);
787 // Prior to fixing b/14677858 this call would result in an infinite loop in
788 // Chromium. As a proxy for detecting this, we now check whether the
789 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
790 // connection is still flow control blocked.
791 session->connection()->OnCanWrite();
793 QuicAlarm* resume_writes_alarm =
794 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
795 EXPECT_FALSE(resume_writes_alarm->IsSet());
798 TEST_P(EndToEndTest, InvalidStream) {
799 ASSERT_TRUE(Initialize());
800 client_->client()->WaitForCryptoHandshakeConfirmed();
802 string body;
803 GenerateBody(&body, kMaxPacketSize);
805 HTTPMessage request(HttpConstants::HTTP_1_1,
806 HttpConstants::POST, "/foo");
807 request.AddBody(body, true);
808 // Force the client to write with a stream ID belonging to a nonexistent
809 // server-side stream.
810 QuicSessionPeer::SetNextStreamId(client_->client()->session(), 2);
812 client_->SendCustomSynchronousRequest(request);
813 // EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
814 EXPECT_EQ(QUIC_PACKET_FOR_NONEXISTENT_STREAM, client_->connection_error());
817 // TODO(rch): this test seems to cause net_unittests timeouts :|
818 TEST_P(EndToEndTest, DISABLED_MultipleTermination) {
819 ASSERT_TRUE(Initialize());
821 HTTPMessage request(HttpConstants::HTTP_1_1,
822 HttpConstants::POST, "/foo");
823 request.AddHeader("content-length", "3");
824 request.set_has_complete_message(false);
826 // Set the offset so we won't frame. Otherwise when we pick up termination
827 // before HTTP framing is complete, we send an error and close the stream,
828 // and the second write is picked up as writing on a closed stream.
829 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
830 ASSERT_TRUE(stream != nullptr);
831 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
833 client_->SendData("bar", true);
834 client_->WaitForWriteToFlush();
836 // By default the stream protects itself from writes after terminte is set.
837 // Override this to test the server handling buggy clients.
838 ReliableQuicStreamPeer::SetWriteSideClosed(
839 false, client_->GetOrCreateStream());
841 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
844 TEST_P(EndToEndTest, Timeout) {
845 client_config_.SetIdleConnectionStateLifetime(
846 QuicTime::Delta::FromMicroseconds(500),
847 QuicTime::Delta::FromMicroseconds(500));
848 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
849 // that's enough to validate timeout in this case.
850 Initialize();
851 while (client_->client()->connected()) {
852 client_->client()->WaitForEvents();
856 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
857 ValueRestore<bool> old_flag(&FLAGS_quic_allow_more_open_streams, true);
859 // Negotiate 1 max open stream.
860 client_config_.SetMaxStreamsPerConnection(1, 1);
861 ASSERT_TRUE(Initialize());
862 client_->client()->WaitForCryptoHandshakeConfirmed();
864 // Make the client misbehave after negotiation.
865 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
866 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(),
867 kServerMaxStreams + 1);
869 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
870 request.AddHeader("content-length", "3");
871 request.set_has_complete_message(false);
873 // The server supports a small number of additional streams beyond the
874 // negotiated limit. Open enough streams to go beyond that limit.
875 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
876 client_->SendMessage(request);
878 client_->WaitForResponse();
880 EXPECT_FALSE(client_->connected());
881 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
882 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
885 TEST_P(EndToEndTest, NegotiateCongestionControl) {
886 ASSERT_TRUE(Initialize());
887 client_->client()->WaitForCryptoHandshakeConfirmed();
889 CongestionControlType expected_congestion_control_type;
890 switch (GetParam().congestion_control_tag) {
891 case kRENO:
892 expected_congestion_control_type = kReno;
893 break;
894 case kTBBR:
895 expected_congestion_control_type = kBBR;
896 break;
897 case kQBIC:
898 expected_congestion_control_type = kCubic;
899 break;
900 default:
901 DLOG(FATAL) << "Unexpected congestion control tag";
904 EXPECT_EQ(expected_congestion_control_type,
905 QuicSentPacketManagerPeer::GetCongestionControlAlgorithm(
906 *GetSentPacketManagerFromFirstServerSession())
907 ->GetCongestionControlType());
910 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
911 // Server limits the number of max streams to 2.
912 server_config_.SetMaxStreamsPerConnection(2, 2);
913 // Client tries to negotiate for 10.
914 client_config_.SetMaxStreamsPerConnection(10, 5);
916 ASSERT_TRUE(Initialize());
917 client_->client()->WaitForCryptoHandshakeConfirmed();
918 QuicConfig* client_negotiated_config = client_->client()->session()->config();
919 EXPECT_EQ(2u, client_negotiated_config->MaxStreamsPerConnection());
922 TEST_P(EndToEndTest, LimitCongestionWindowAndRTT) {
923 // Client tries to request twice the server's max initial window, and the
924 // server limits it to the max.
925 client_config_.SetInitialCongestionWindowToSend(2 * kMaxInitialWindow);
926 client_config_.SetInitialRoundTripTimeUsToSend(1000);
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 const QuicSentPacketManager& client_sent_packet_manager =
938 client_->client()->session()->connection()->sent_packet_manager();
939 const QuicSentPacketManager& server_sent_packet_manager =
940 *GetSentPacketManagerFromFirstServerSession();
942 // The client shouldn't set it's initial window based on the negotiated value.
943 EXPECT_EQ(kDefaultInitialWindow * kDefaultTCPMSS,
944 client_sent_packet_manager.GetCongestionWindow());
945 EXPECT_EQ(kMaxInitialWindow * kDefaultTCPMSS,
946 server_sent_packet_manager.GetCongestionWindow());
948 EXPECT_EQ(GetParam().use_pacing, server_sent_packet_manager.using_pacing());
949 EXPECT_EQ(GetParam().use_pacing, client_sent_packet_manager.using_pacing());
951 // The client *should* set the intitial RTT.
952 EXPECT_EQ(1000u, client_sent_packet_manager.GetRttStats()->initial_rtt_us());
953 EXPECT_EQ(1000u, server_sent_packet_manager.GetRttStats()->initial_rtt_us());
955 // Now use the negotiated limits with packet loss.
956 SetPacketLossPercentage(30);
958 // 10 KB body.
959 string body;
960 GenerateBody(&body, 1024 * 10);
962 HTTPMessage request(HttpConstants::HTTP_1_1,
963 HttpConstants::POST, "/foo");
964 request.AddBody(body, true);
966 server_thread_->Resume();
968 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
971 TEST_P(EndToEndTest, MaxInitialRTT) {
972 // Client tries to suggest twice the server's max initial rtt and the server
973 // uses the max.
974 client_config_.SetInitialRoundTripTimeUsToSend(
975 2 * kMaxInitialRoundTripTimeUs);
977 ASSERT_TRUE(Initialize());
978 client_->client()->WaitForCryptoHandshakeConfirmed();
979 server_thread_->WaitForCryptoHandshakeConfirmed();
981 // Pause the server so we can access the server's internals without races.
982 server_thread_->Pause();
983 QuicDispatcher* dispatcher =
984 QuicServerPeer::GetDispatcher(server_thread_->server());
985 ASSERT_EQ(1u, dispatcher->session_map().size());
986 QuicSession* session = dispatcher->session_map().begin()->second;
987 const QuicSentPacketManager& client_sent_packet_manager =
988 client_->client()->session()->connection()->sent_packet_manager();
989 const QuicSentPacketManager& server_sent_packet_manager =
990 session->connection()->sent_packet_manager();
992 // Now that acks have been exchanged, the RTT estimate has decreased on the
993 // server and is not infinite on the client.
994 EXPECT_FALSE(
995 client_sent_packet_manager.GetRttStats()->SmoothedRtt().IsInfinite());
996 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
997 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
998 EXPECT_GE(
999 static_cast<int64>(kMaxInitialRoundTripTimeUs),
1000 server_sent_packet_manager.GetRttStats()->SmoothedRtt().ToMicroseconds());
1001 server_thread_->Resume();
1004 TEST_P(EndToEndTest, MinInitialRTT) {
1005 // Client tries to suggest 0 and the server uses the default.
1006 client_config_.SetInitialRoundTripTimeUsToSend(0);
1008 ASSERT_TRUE(Initialize());
1009 client_->client()->WaitForCryptoHandshakeConfirmed();
1010 server_thread_->WaitForCryptoHandshakeConfirmed();
1012 // Pause the server so we can access the server's internals without races.
1013 server_thread_->Pause();
1014 QuicDispatcher* dispatcher =
1015 QuicServerPeer::GetDispatcher(server_thread_->server());
1016 ASSERT_EQ(1u, dispatcher->session_map().size());
1017 QuicSession* session = dispatcher->session_map().begin()->second;
1018 const QuicSentPacketManager& client_sent_packet_manager =
1019 client_->client()->session()->connection()->sent_packet_manager();
1020 const QuicSentPacketManager& server_sent_packet_manager =
1021 session->connection()->sent_packet_manager();
1023 // Now that acks have been exchanged, the RTT estimate has decreased on the
1024 // server and is not infinite on the client.
1025 EXPECT_FALSE(
1026 client_sent_packet_manager.GetRttStats()->SmoothedRtt().IsInfinite());
1027 // Expect the default rtt of 100ms.
1028 EXPECT_EQ(static_cast<int64>(100 * base::Time::kMicrosecondsPerMillisecond),
1029 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1030 // Ensure the bandwidth is valid.
1031 client_sent_packet_manager.BandwidthEstimate();
1032 server_sent_packet_manager.BandwidthEstimate();
1033 server_thread_->Resume();
1036 TEST_P(EndToEndTest, ResetConnection) {
1037 ASSERT_TRUE(Initialize());
1038 client_->client()->WaitForCryptoHandshakeConfirmed();
1040 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1041 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1042 client_->ResetConnection();
1043 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1044 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1047 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1048 SetPacketLossPercentage(1);
1049 ASSERT_TRUE(Initialize());
1050 string large_body;
1051 GenerateBody(&large_body, 10240);
1052 int max_streams = 100;
1054 AddToCache("GET", "/large_response", "HTTP/1.1", "200", "OK", large_body);;
1056 client_->client()->WaitForCryptoHandshakeConfirmed();
1057 SetPacketLossPercentage(10);
1059 for (int i = 0; i < max_streams; ++i) {
1060 EXPECT_LT(0, client_->SendRequest("/large_response"));
1063 // WaitForEvents waits 50ms and returns true if there are outstanding
1064 // requests.
1065 while (client_->client()->WaitForEvents() == true) {
1069 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1070 ASSERT_TRUE(Initialize());
1071 string small_body;
1072 GenerateBody(&small_body, 256);
1074 AddToCache("GET", "/small_response", "HTTP/1.1", "200", "OK", small_body);
1076 client_->client()->WaitForCryptoHandshakeConfirmed();
1078 QuicSession* session = client_->client()->session();
1079 // Lose the request.
1080 SetPacketLossPercentage(100);
1081 EXPECT_LT(0, client_->SendRequest("/small_response"));
1082 client_->client()->WaitForEvents();
1083 // Transmit the cancel, and ensure the connection is torn down properly.
1084 SetPacketLossPercentage(0);
1085 QuicStreamId stream_id = kClientDataStreamId1;
1086 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1088 // WaitForEvents waits 50ms and returns true if there are outstanding
1089 // requests.
1090 while (client_->client()->WaitForEvents() == true) {
1092 // It should be completely fine to RST a stream before any data has been
1093 // received for that stream.
1094 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1097 class WrongAddressWriter : public QuicPacketWriterWrapper {
1098 public:
1099 WrongAddressWriter() {
1100 IPAddressNumber ip;
1101 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1102 self_address_ = IPEndPoint(ip, 0);
1105 virtual WriteResult WritePacket(
1106 const char* buffer,
1107 size_t buf_len,
1108 const IPAddressNumber& real_self_address,
1109 const IPEndPoint& peer_address) override {
1110 // Use wrong address!
1111 return QuicPacketWriterWrapper::WritePacket(
1112 buffer, buf_len, self_address_.address(), peer_address);
1115 virtual bool IsWriteBlockedDataBuffered() const override {
1116 return false;
1119 IPEndPoint self_address_;
1122 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1123 // Tests that the client's IP can not change during an established QUIC
1124 // connection. If it changes, the connection is closed by the server as we do
1125 // not yet support IP migration.
1126 ASSERT_TRUE(Initialize());
1128 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1129 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1131 WrongAddressWriter* writer = new WrongAddressWriter();
1133 writer->set_writer(new QuicDefaultPacketWriter(client_->client()->fd()));
1134 QuicConnectionPeer::SetWriter(client_->client()->session()->connection(),
1135 writer,
1136 /* owns_writer= */ true);
1138 client_->SendSynchronousRequest("/bar");
1140 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1141 EXPECT_EQ(QUIC_ERROR_MIGRATING_ADDRESS, client_->connection_error());
1144 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1145 // Tests that the client's port can change during an established QUIC
1146 // connection, and that doing so does not result in the connection being
1147 // closed by the server.
1148 ASSERT_TRUE(Initialize());
1150 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1151 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1153 // Store the client address which was used to send the first request.
1154 IPEndPoint old_address = client_->client()->client_address();
1156 // Stop listening on the old FD.
1157 EpollServer* eps = client_->epoll_server();
1158 int old_fd = client_->client()->fd();
1159 eps->UnregisterFD(old_fd);
1160 // Create a new socket before closing the old one, which will result in a new
1161 // ephemeral port.
1162 QuicClientPeer::CreateUDPSocket(client_->client());
1163 close(old_fd);
1165 // The packet writer needs to be updated to use the new FD.
1166 client_->client()->CreateQuicPacketWriter();
1168 // Change the internal state of the client and connection to use the new port,
1169 // this is done because in a real NAT rebinding the client wouldn't see any
1170 // port change, and so expects no change to incoming port.
1171 // This is kind of ugly, but needed as we are simply swapping out the client
1172 // FD rather than any more complex NAT rebinding simulation.
1173 int new_port = client_->client()->client_address().port();
1174 QuicClientPeer::SetClientPort(client_->client(), new_port);
1175 QuicConnectionPeer::SetSelfAddress(
1176 client_->client()->session()->connection(),
1177 IPEndPoint(
1178 client_->client()->session()->connection()->self_address().address(),
1179 new_port));
1181 // Register the new FD for epoll events.
1182 int new_fd = client_->client()->fd();
1183 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1185 // Send a second request, using the new FD.
1186 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1187 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1189 // Verify that the client's ephemeral port is different.
1190 IPEndPoint new_address = client_->client()->client_address();
1191 EXPECT_EQ(old_address.address(), new_address.address());
1192 EXPECT_NE(old_address.port(), new_address.port());
1196 TEST_P(EndToEndTest, DifferentFlowControlWindowsQ019) {
1197 // TODO(rjshade): Remove this test when removing QUIC_VERSION_19.
1198 // Client and server can set different initial flow control receive windows.
1199 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1200 // in the crypto handshake.
1202 const uint32 kClientIFCW = 123456;
1203 set_client_initial_flow_control_receive_window(kClientIFCW);
1205 const uint32 kServerIFCW = 654321;
1206 set_server_initial_flow_control_receive_window(kServerIFCW);
1208 ASSERT_TRUE(Initialize());
1209 if (negotiated_version_ > QUIC_VERSION_19) {
1210 return;
1213 // Values are exchanged during crypto handshake, so wait for that to finish.
1214 client_->client()->WaitForCryptoHandshakeConfirmed();
1215 server_thread_->WaitForCryptoHandshakeConfirmed();
1217 // Client should have the right value for server's receive window.
1218 EXPECT_EQ(kServerIFCW, client_->client()
1219 ->session()
1220 ->config()
1221 ->ReceivedInitialFlowControlWindowBytes());
1223 // Server should have the right value for client's receive window.
1224 server_thread_->Pause();
1225 QuicDispatcher* dispatcher =
1226 QuicServerPeer::GetDispatcher(server_thread_->server());
1227 QuicSession* session = dispatcher->session_map().begin()->second;
1228 EXPECT_EQ(kClientIFCW,
1229 session->config()->ReceivedInitialFlowControlWindowBytes());
1230 server_thread_->Resume();
1233 TEST_P(EndToEndTest, DifferentFlowControlWindowsQ020) {
1234 // TODO(rjshade): Rename to DifferentFlowControlWindows when removing
1235 // QUIC_VERSION_19.
1236 // Client and server can set different initial flow control receive windows.
1237 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1238 // in the crypto handshake.
1239 const uint32 kClientStreamIFCW = 123456;
1240 const uint32 kClientSessionIFCW = 234567;
1241 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1242 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1244 const uint32 kServerStreamIFCW = 654321;
1245 const uint32 kServerSessionIFCW = 765432;
1246 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1247 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1249 ASSERT_TRUE(Initialize());
1250 if (negotiated_version_ == QUIC_VERSION_19) {
1251 return;
1254 // Values are exchanged during crypto handshake, so wait for that to finish.
1255 client_->client()->WaitForCryptoHandshakeConfirmed();
1256 server_thread_->WaitForCryptoHandshakeConfirmed();
1258 // Open a data stream to make sure the stream level flow control is updated.
1259 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1260 stream->SendBody("hello", false);
1262 // Client should have the right values for server's receive window.
1263 EXPECT_EQ(kServerStreamIFCW,
1264 client_->client()
1265 ->session()
1266 ->config()
1267 ->ReceivedInitialStreamFlowControlWindowBytes());
1268 EXPECT_EQ(kServerSessionIFCW,
1269 client_->client()
1270 ->session()
1271 ->config()
1272 ->ReceivedInitialSessionFlowControlWindowBytes());
1273 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1274 stream->flow_controller()));
1275 EXPECT_EQ(kServerSessionIFCW,
1276 QuicFlowControllerPeer::SendWindowOffset(
1277 client_->client()->session()->flow_controller()));
1279 // Server should have the right values for client's receive window.
1280 server_thread_->Pause();
1281 QuicDispatcher* dispatcher =
1282 QuicServerPeer::GetDispatcher(server_thread_->server());
1283 QuicSession* session = dispatcher->session_map().begin()->second;
1284 EXPECT_EQ(kClientStreamIFCW,
1285 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1286 EXPECT_EQ(kClientSessionIFCW,
1287 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1288 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1289 session->flow_controller()));
1290 server_thread_->Resume();
1293 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1294 // The special headers and crypto streams should be subject to per-stream flow
1295 // control limits, but should not be subject to connection level flow control.
1296 const uint32 kStreamIFCW = 123456;
1297 const uint32 kSessionIFCW = 234567;
1298 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
1299 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
1300 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
1301 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
1303 ASSERT_TRUE(Initialize());
1304 if (negotiated_version_ < QUIC_VERSION_21) {
1305 return;
1308 // Wait for crypto handshake to finish. This should have contributed to the
1309 // crypto stream flow control window, but not affected the session flow
1310 // control window.
1311 client_->client()->WaitForCryptoHandshakeConfirmed();
1312 server_thread_->WaitForCryptoHandshakeConfirmed();
1314 QuicCryptoStream* crypto_stream =
1315 QuicSessionPeer::GetCryptoStream(client_->client()->session());
1316 EXPECT_LT(
1317 QuicFlowControllerPeer::SendWindowSize(crypto_stream->flow_controller()),
1318 kStreamIFCW);
1319 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1320 client_->client()->session()->flow_controller()));
1322 // Send a request with no body, and verify that the connection level window
1323 // has not been affected.
1324 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1326 QuicHeadersStream* headers_stream =
1327 QuicSessionPeer::GetHeadersStream(client_->client()->session());
1328 EXPECT_LT(
1329 QuicFlowControllerPeer::SendWindowSize(headers_stream->flow_controller()),
1330 kStreamIFCW);
1331 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1332 client_->client()->session()->flow_controller()));
1334 // Server should be in a similar state: connection flow control window should
1335 // not have any bytes marked as received.
1336 server_thread_->Pause();
1337 QuicDispatcher* dispatcher =
1338 QuicServerPeer::GetDispatcher(server_thread_->server());
1339 QuicSession* session = dispatcher->session_map().begin()->second;
1340 QuicFlowController* server_connection_flow_controller =
1341 session->flow_controller();
1342 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
1343 server_connection_flow_controller));
1344 server_thread_->Resume();
1347 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1348 // Regression test for b/16010251.
1349 // A stream created on receipt of a simple request with no body will never get
1350 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1351 // the locally closed streams map: it will never be removed if so.
1352 ASSERT_TRUE(Initialize());
1354 // Send a simple headers only request, and receive response.
1355 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1356 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1358 // Now verify that the server is not waiting for a final FIN or RST.
1359 server_thread_->Pause();
1360 QuicDispatcher* dispatcher =
1361 QuicServerPeer::GetDispatcher(server_thread_->server());
1362 QuicSession* session = dispatcher->session_map().begin()->second;
1363 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1364 session).size());
1365 server_thread_->Resume();
1368 } // namespace
1369 } // namespace test
1370 } // namespace tools
1371 } // namespace net