Update mojo surfaces bindings and mojo/cc/ glue
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blob28c277f97bbc964604616290a355b3711f7aa632
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_sent_packet_manager.h"
25 #include "net/quic/quic_server_id.h"
26 #include "net/quic/quic_utils.h"
27 #include "net/quic/test_tools/quic_connection_peer.h"
28 #include "net/quic/test_tools/quic_flow_controller_peer.h"
29 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
30 #include "net/quic/test_tools/quic_session_peer.h"
31 #include "net/quic/test_tools/quic_test_utils.h"
32 #include "net/quic/test_tools/reliable_quic_stream_peer.h"
33 #include "net/test/gtest_util.h"
34 #include "net/tools/epoll_server/epoll_server.h"
35 #include "net/tools/quic/quic_epoll_connection_helper.h"
36 #include "net/tools/quic/quic_in_memory_cache.h"
37 #include "net/tools/quic/quic_packet_writer_wrapper.h"
38 #include "net/tools/quic/quic_server.h"
39 #include "net/tools/quic/quic_socket_utils.h"
40 #include "net/tools/quic/quic_spdy_client_stream.h"
41 #include "net/tools/quic/test_tools/http_message.h"
42 #include "net/tools/quic/test_tools/packet_dropping_test_writer.h"
43 #include "net/tools/quic/test_tools/quic_client_peer.h"
44 #include "net/tools/quic/test_tools/quic_dispatcher_peer.h"
45 #include "net/tools/quic/test_tools/quic_in_memory_cache_peer.h"
46 #include "net/tools/quic/test_tools/quic_server_peer.h"
47 #include "net/tools/quic/test_tools/quic_test_client.h"
48 #include "net/tools/quic/test_tools/server_thread.h"
49 #include "testing/gtest/include/gtest/gtest.h"
51 using base::StringPiece;
52 using base::WaitableEvent;
53 using net::EpollServer;
54 using net::test::GenerateBody;
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_pacing,
83 bool use_fec,
84 QuicTag congestion_control_tag)
85 : client_supported_versions(client_supported_versions),
86 server_supported_versions(server_supported_versions),
87 negotiated_version(negotiated_version),
88 use_pacing(use_pacing),
89 use_fec(use_fec),
90 congestion_control_tag(congestion_control_tag) {
93 friend ostream& operator<<(ostream& os, const TestParams& p) {
94 os << "{ server_supported_versions: "
95 << QuicVersionVectorToString(p.server_supported_versions);
96 os << " client_supported_versions: "
97 << QuicVersionVectorToString(p.client_supported_versions);
98 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
99 os << " use_pacing: " << p.use_pacing;
100 os << " use_fec: " << p.use_fec;
101 os << " congestion_control_tag: "
102 << QuicUtils::TagToString(p.congestion_control_tag) << " }";
103 return os;
106 QuicVersionVector client_supported_versions;
107 QuicVersionVector server_supported_versions;
108 QuicVersion negotiated_version;
109 bool use_pacing;
110 bool use_fec;
111 QuicTag congestion_control_tag;
114 // Constructs various test permutations.
115 vector<TestParams> GetTestParams() {
116 vector<TestParams> params;
117 QuicVersionVector all_supported_versions = QuicSupportedVersions();
118 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
119 // QuicTag congestion_control_tags[] = {kRENO, kTBBR, kQBIC};
120 QuicTag congestion_control_tags[] = {kRENO, kQBIC};
121 for (size_t congestion_control_index = 0;
122 congestion_control_index < arraysize(congestion_control_tags);
123 congestion_control_index++) {
124 QuicTag congestion_control_tag =
125 congestion_control_tags[congestion_control_index];
126 for (int use_fec = 0; use_fec < 2; ++use_fec) {
127 for (int use_pacing = 0; use_pacing < 2; ++use_pacing) {
128 // Add an entry for server and client supporting all versions.
129 params.push_back(TestParams(all_supported_versions,
130 all_supported_versions,
131 all_supported_versions[0],
132 use_pacing != 0,
133 use_fec != 0,
134 congestion_control_tag));
136 // Test client supporting all versions and server supporting 1 version.
137 // Simulate an old server and exercise version downgrade in the client.
138 // Protocol negotiation should occur. Skip the i = 0 case because it is
139 // essentially the same as the default case.
140 for (size_t i = 1; i < all_supported_versions.size(); ++i) {
141 QuicVersionVector server_supported_versions;
142 server_supported_versions.push_back(all_supported_versions[i]);
143 if (all_supported_versions[i] >= QUIC_VERSION_18) {
144 // Until flow control is globally rolled out and we remove
145 // QUIC_VERSION_16, the server MUST support at least one QUIC
146 // version that does not use flow control.
147 server_supported_versions.push_back(QUIC_VERSION_16);
149 params.push_back(TestParams(all_supported_versions,
150 server_supported_versions,
151 server_supported_versions[0],
152 use_pacing != 0,
153 use_fec != 0,
154 congestion_control_tag));
159 return params;
162 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
163 public:
164 ServerDelegate(TestWriterFactory* writer_factory,
165 QuicDispatcher* dispatcher)
166 : writer_factory_(writer_factory),
167 dispatcher_(dispatcher) {}
168 virtual ~ServerDelegate() {}
169 virtual void OnPacketSent(WriteResult result) override {
170 writer_factory_->OnPacketSent(result);
172 virtual void OnCanWrite() OVERRIDE { dispatcher_->OnCanWrite(); }
173 private:
174 TestWriterFactory* writer_factory_;
175 QuicDispatcher* dispatcher_;
178 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
179 public:
180 explicit ClientDelegate(QuicClient* client) : client_(client) {}
181 virtual ~ClientDelegate() {}
182 virtual void OnPacketSent(WriteResult result) OVERRIDE {}
183 virtual void OnCanWrite() OVERRIDE {
184 EpollEvent event(EPOLLOUT, false);
185 client_->OnEvent(client_->fd(), &event);
187 private:
188 QuicClient* client_;
191 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
192 protected:
193 EndToEndTest()
194 : server_hostname_("example.com"),
195 server_started_(false),
196 strike_register_no_startup_period_(false) {
197 net::IPAddressNumber ip;
198 CHECK(net::ParseIPLiteralToNumber("127.0.0.1", &ip));
199 server_address_ = IPEndPoint(ip, 0);
201 client_supported_versions_ = GetParam().client_supported_versions;
202 server_supported_versions_ = GetParam().server_supported_versions;
203 negotiated_version_ = GetParam().negotiated_version;
204 FLAGS_enable_quic_fec = GetParam().use_fec;
206 VLOG(1) << "Using Configuration: " << GetParam();
208 client_config_.SetDefaults();
209 server_config_.SetDefaults();
211 // Use different flow control windows for client/server.
212 client_config_.SetInitialFlowControlWindowToSend(
213 2 * kInitialSessionFlowControlWindowForTest);
214 client_config_.SetInitialStreamFlowControlWindowToSend(
215 2 * kInitialStreamFlowControlWindowForTest);
216 client_config_.SetInitialSessionFlowControlWindowToSend(
217 2 * kInitialSessionFlowControlWindowForTest);
218 server_config_.SetInitialFlowControlWindowToSend(
219 3 * kInitialSessionFlowControlWindowForTest);
220 server_config_.SetInitialStreamFlowControlWindowToSend(
221 3 * kInitialStreamFlowControlWindowForTest);
222 server_config_.SetInitialSessionFlowControlWindowToSend(
223 3 * kInitialSessionFlowControlWindowForTest);
225 QuicInMemoryCachePeer::ResetForTests();
226 AddToCache("GET", "https://www.google.com/foo",
227 "HTTP/1.1", "200", "OK", kFooResponseBody);
228 AddToCache("GET", "https://www.google.com/bar",
229 "HTTP/1.1", "200", "OK", kBarResponseBody);
232 virtual ~EndToEndTest() {
233 // TODO(rtenneti): port RecycleUnusedPort if needed.
234 // RecycleUnusedPort(server_address_.port());
235 QuicInMemoryCachePeer::ResetForTests();
238 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
239 QuicTestClient* client = new QuicTestClient(
240 server_address_,
241 server_hostname_,
242 false, // not secure
243 client_config_,
244 client_supported_versions_);
245 client->UseWriter(writer);
246 client->Connect();
247 return client;
250 void set_client_initial_flow_control_receive_window(uint32 window) {
251 CHECK(client_.get() == NULL);
252 DVLOG(1) << "Setting client initial flow control window: " << window;
253 client_config_.SetInitialFlowControlWindowToSend(window);
256 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
257 CHECK(client_.get() == NULL);
258 DVLOG(1) << "Setting client initial stream flow control window: " << window;
259 client_config_.SetInitialStreamFlowControlWindowToSend(window);
262 void set_client_initial_session_flow_control_receive_window(uint32 window) {
263 CHECK(client_.get() == NULL);
264 DVLOG(1) << "Setting client initial session flow control window: "
265 << window;
266 client_config_.SetInitialSessionFlowControlWindowToSend(window);
269 void set_server_initial_flow_control_receive_window(uint32 window) {
270 CHECK(server_thread_.get() == NULL);
271 DVLOG(1) << "Setting server initial flow control window: " << window;
272 server_config_.SetInitialFlowControlWindowToSend(window);
275 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
276 CHECK(server_thread_.get() == NULL);
277 DVLOG(1) << "Setting server initial stream flow control window: "
278 << window;
279 server_config_.SetInitialStreamFlowControlWindowToSend(window);
282 void set_server_initial_session_flow_control_receive_window(uint32 window) {
283 CHECK(server_thread_.get() == NULL);
284 DVLOG(1) << "Setting server initial session flow control window: "
285 << window;
286 server_config_.SetInitialSessionFlowControlWindowToSend(window);
289 const QuicSentPacketManager *
290 GetSentPacketManagerFromFirstServerSession() const {
291 QuicDispatcher* dispatcher =
292 QuicServerPeer::GetDispatcher(server_thread_->server());
293 QuicSession* session = dispatcher->session_map().begin()->second;
294 return &session->connection()->sent_packet_manager();
297 bool Initialize() {
298 QuicTagVector copt;
300 if (GetParam().use_pacing) {
301 copt.push_back(kPACE);
303 server_config_.SetConnectionOptionsToSend(copt);
305 // TODO(nimia): Consider setting the congestion control algorithm for the
306 // client as well according to the test parameter.
307 copt.push_back(GetParam().congestion_control_tag);
309 if (GetParam().use_fec) {
310 // Set FEC config in client's connection options and in client session.
311 copt.push_back(kFHDR);
314 client_config_.SetConnectionOptionsToSend(copt);
316 // Start the server first, because CreateQuicClient() attempts
317 // to connect to the server.
318 StartServer();
319 client_.reset(CreateQuicClient(client_writer_));
320 if (GetParam().use_fec) {
321 // Set FecPolicy to always protect data on all streams.
322 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
324 static EpollEvent event(EPOLLOUT, false);
325 client_writer_->Initialize(
326 reinterpret_cast<QuicEpollConnectionHelper*>(
327 QuicConnectionPeer::GetHelper(
328 client_->client()->session()->connection())),
329 new ClientDelegate(client_->client()));
330 return client_->client()->connected();
333 virtual void SetUp() OVERRIDE {
334 // The ownership of these gets transferred to the QuicPacketWriterWrapper
335 // and TestWriterFactory when Initialize() is executed.
336 client_writer_ = new PacketDroppingTestWriter();
337 server_writer_ = new PacketDroppingTestWriter();
340 virtual void TearDown() OVERRIDE {
341 StopServer();
344 void StartServer() {
345 server_thread_.reset(
346 new ServerThread(
347 new QuicServer(server_config_, server_supported_versions_),
348 server_address_,
349 strike_register_no_startup_period_));
350 server_thread_->Initialize();
351 server_address_ = IPEndPoint(server_address_.address(),
352 server_thread_->GetPort());
353 QuicDispatcher* dispatcher =
354 QuicServerPeer::GetDispatcher(server_thread_->server());
355 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
356 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
357 packet_writer_factory);
358 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
359 server_writer_->Initialize(
360 QuicDispatcherPeer::GetHelper(dispatcher),
361 new ServerDelegate(packet_writer_factory, dispatcher));
362 server_thread_->Start();
363 server_started_ = true;
366 void StopServer() {
367 if (!server_started_)
368 return;
369 if (server_thread_.get()) {
370 server_thread_->Quit();
371 server_thread_->Join();
375 void AddToCache(StringPiece method,
376 StringPiece path,
377 StringPiece version,
378 StringPiece response_code,
379 StringPiece response_detail,
380 StringPiece body) {
381 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
382 method, path, version, response_code, response_detail, body);
385 void SetPacketLossPercentage(int32 loss) {
386 // TODO(rtenneti): enable when we can do random packet loss tests in
387 // chrome's tree.
388 if (loss != 0 && loss != 100)
389 return;
390 client_writer_->set_fake_packet_loss_percentage(loss);
391 server_writer_->set_fake_packet_loss_percentage(loss);
394 void SetPacketSendDelay(QuicTime::Delta delay) {
395 // TODO(rtenneti): enable when we can do random packet send delay tests in
396 // chrome's tree.
397 // client_writer_->set_fake_packet_delay(delay);
398 // server_writer_->set_fake_packet_delay(delay);
401 void SetReorderPercentage(int32 reorder) {
402 // TODO(rtenneti): enable when we can do random packet reorder tests in
403 // chrome's tree.
404 // client_writer_->set_fake_reorder_percentage(reorder);
405 // server_writer_->set_fake_reorder_percentage(reorder);
408 // Verifies that the client and server connections were both free of packets
409 // being discarded, based on connection stats.
410 // Calls server_thread_ Pause() and Resume(), which may only be called once
411 // per test.
412 void VerifyCleanConnection(bool had_packet_loss) {
413 QuicConnectionStats client_stats =
414 client_->client()->session()->connection()->GetStats();
415 if (!had_packet_loss) {
416 EXPECT_EQ(0u, client_stats.packets_lost);
418 EXPECT_EQ(0u, client_stats.packets_discarded);
419 EXPECT_EQ(0u, client_stats.packets_dropped);
420 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
422 server_thread_->Pause();
423 QuicDispatcher* dispatcher =
424 QuicServerPeer::GetDispatcher(server_thread_->server());
425 ASSERT_EQ(1u, dispatcher->session_map().size());
426 QuicSession* session = dispatcher->session_map().begin()->second;
427 QuicConnectionStats server_stats = session->connection()->GetStats();
428 if (!had_packet_loss) {
429 EXPECT_EQ(0u, server_stats.packets_lost);
431 EXPECT_EQ(0u, server_stats.packets_discarded);
432 // TODO(ianswett): Restore the check for packets_dropped equals 0.
433 // The expect for packets received is equal to packets processed fails
434 // due to version negotiation packets.
435 server_thread_->Resume();
438 IPEndPoint server_address_;
439 string server_hostname_;
440 scoped_ptr<ServerThread> server_thread_;
441 scoped_ptr<QuicTestClient> client_;
442 PacketDroppingTestWriter* client_writer_;
443 PacketDroppingTestWriter* server_writer_;
444 bool server_started_;
445 QuicConfig client_config_;
446 QuicConfig server_config_;
447 QuicVersionVector client_supported_versions_;
448 QuicVersionVector server_supported_versions_;
449 QuicVersion negotiated_version_;
450 bool strike_register_no_startup_period_;
453 // Run all end to end tests with all supported versions.
454 INSTANTIATE_TEST_CASE_P(EndToEndTests,
455 EndToEndTest,
456 ::testing::ValuesIn(GetTestParams()));
458 TEST_P(EndToEndTest, SimpleRequestResponse) {
459 ASSERT_TRUE(Initialize());
461 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
462 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
465 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
466 // try bots) and selectively disable this test.
467 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
468 IPAddressNumber ip;
469 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
470 server_address_ = IPEndPoint(ip, server_address_.port());
471 ASSERT_TRUE(Initialize());
473 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
474 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
477 TEST_P(EndToEndTest, SeparateFinPacket) {
478 ASSERT_TRUE(Initialize());
480 HTTPMessage request(HttpConstants::HTTP_1_1,
481 HttpConstants::POST, "/foo");
482 request.set_has_complete_message(false);
484 client_->SendMessage(request);
486 client_->SendData(string(), true);
488 client_->WaitForResponse();
489 EXPECT_EQ(kFooResponseBody, client_->response_body());
490 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
492 request.AddBody("foo", true);
494 client_->SendMessage(request);
495 client_->SendData(string(), true);
496 client_->WaitForResponse();
497 EXPECT_EQ(kFooResponseBody, client_->response_body());
498 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
501 TEST_P(EndToEndTest, MultipleRequestResponse) {
502 ASSERT_TRUE(Initialize());
504 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
505 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
506 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
507 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
510 TEST_P(EndToEndTest, MultipleClients) {
511 ASSERT_TRUE(Initialize());
512 scoped_ptr<QuicTestClient> client2(CreateQuicClient(NULL));
514 HTTPMessage request(HttpConstants::HTTP_1_1,
515 HttpConstants::POST, "/foo");
516 request.AddHeader("content-length", "3");
517 request.set_has_complete_message(false);
519 client_->SendMessage(request);
520 client2->SendMessage(request);
522 client_->SendData("bar", true);
523 client_->WaitForResponse();
524 EXPECT_EQ(kFooResponseBody, client_->response_body());
525 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
527 client2->SendData("eep", true);
528 client2->WaitForResponse();
529 EXPECT_EQ(kFooResponseBody, client2->response_body());
530 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
533 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
534 // Send a large enough request to guarantee fragmentation.
535 string huge_request =
536 "https://www.google.com/some/path?query=" + string(kMaxPacketSize, '.');
537 AddToCache("GET", huge_request, "HTTP/1.1", "200", "OK", kBarResponseBody);
539 ASSERT_TRUE(Initialize());
541 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
542 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
545 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
546 // Send a large enough request to guarantee fragmentation.
547 string huge_request =
548 "https://www.google.com/some/path?query=" + string(kMaxPacketSize, '.');
549 AddToCache("GET", huge_request, "HTTP/1.1", "200", "OK", kBarResponseBody);
551 ASSERT_TRUE(Initialize());
552 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
553 SetReorderPercentage(50);
555 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
556 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
559 TEST_P(EndToEndTest, PostMissingBytes) {
560 ASSERT_TRUE(Initialize());
562 // Add a content length header with no body.
563 HTTPMessage request(HttpConstants::HTTP_1_1,
564 HttpConstants::POST, "/foo");
565 request.AddHeader("content-length", "3");
566 request.set_skip_message_validation(true);
568 // This should be detected as stream fin without complete request,
569 // triggering an error response.
570 client_->SendCustomSynchronousRequest(request);
571 EXPECT_EQ("bad", client_->response_body());
572 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
575 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
576 // http://crbug.com/297040.
577 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
578 ASSERT_TRUE(Initialize());
580 client_->client()->WaitForCryptoHandshakeConfirmed();
582 // 1 MB body.
583 string body;
584 GenerateBody(&body, 1024 * 1024);
586 HTTPMessage request(HttpConstants::HTTP_1_1,
587 HttpConstants::POST, "/foo");
588 request.AddBody(body, true);
590 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
591 VerifyCleanConnection(false);
594 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
595 ASSERT_TRUE(Initialize());
596 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
598 client_->client()->WaitForCryptoHandshakeConfirmed();
600 // 100 KB body.
601 string body;
602 GenerateBody(&body, 100 * 1024);
604 HTTPMessage request(HttpConstants::HTTP_1_1,
605 HttpConstants::POST, "/foo");
606 request.AddBody(body, true);
608 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
609 VerifyCleanConnection(false);
612 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
613 // Connect with lower fake packet loss than we'd like to test. Until
614 // b/10126687 is fixed, losing handshake packets is pretty brutal.
615 SetPacketLossPercentage(5);
616 ASSERT_TRUE(Initialize());
618 // Wait for the server SHLO before upping the packet loss.
619 client_->client()->WaitForCryptoHandshakeConfirmed();
620 SetPacketLossPercentage(30);
622 // 10 KB body.
623 string body;
624 GenerateBody(&body, 1024 * 10);
626 HTTPMessage request(HttpConstants::HTTP_1_1,
627 HttpConstants::POST, "/foo");
628 request.AddBody(body, true);
630 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
631 VerifyCleanConnection(true);
634 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
635 // Connect with lower fake packet loss than we'd like to test. Until
636 // b/10126687 is fixed, losing handshake packets is pretty brutal.
637 SetPacketLossPercentage(5);
638 ASSERT_TRUE(Initialize());
640 // Wait for the server SHLO before upping the packet loss.
641 client_->client()->WaitForCryptoHandshakeConfirmed();
642 SetPacketLossPercentage(10);
643 client_writer_->set_fake_blocked_socket_percentage(10);
645 // 10 KB body.
646 string body;
647 GenerateBody(&body, 1024 * 10);
649 HTTPMessage request(HttpConstants::HTTP_1_1,
650 HttpConstants::POST, "/foo");
651 request.AddBody(body, true);
653 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
656 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
657 ASSERT_TRUE(Initialize());
659 client_->client()->WaitForCryptoHandshakeConfirmed();
660 // Both of these must be called when the writer is not actively used.
661 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
662 SetReorderPercentage(30);
664 // 1 MB body.
665 string body;
666 GenerateBody(&body, 1024 * 1024);
668 HTTPMessage request(HttpConstants::HTTP_1_1,
669 HttpConstants::POST, "/foo");
670 request.AddBody(body, true);
672 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
675 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
676 // Have the server accept 0-RTT without waiting a startup period.
677 strike_register_no_startup_period_ = true;
679 // Send a request and then disconnect. This prepares the client to attempt
680 // a 0-RTT handshake for the next request.
681 ASSERT_TRUE(Initialize());
683 string body;
684 GenerateBody(&body, 20480);
686 HTTPMessage request(HttpConstants::HTTP_1_1,
687 HttpConstants::POST, "/foo");
688 request.AddBody(body, true);
690 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
691 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
693 client_->Disconnect();
695 // The 0-RTT handshake should succeed.
696 client_->Connect();
697 if (client_supported_versions_[0] >= QUIC_VERSION_18 &&
698 negotiated_version_ <= QUIC_VERSION_16) {
699 // If the version negotiation has resulted in a downgrade, then the client
700 // must wait for the handshake to complete before sending any data.
701 // Otherwise it may have queued frames which will trigger a
702 // DFATAL when they are serialized after the downgrade.
703 client_->client()->WaitForCryptoHandshakeConfirmed();
705 client_->WaitForResponseForMs(-1);
706 ASSERT_TRUE(client_->client()->connected());
707 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
708 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
710 client_->Disconnect();
712 // Restart the server so that the 0-RTT handshake will take 1 RTT.
713 StopServer();
714 server_writer_ = new PacketDroppingTestWriter();
715 StartServer();
717 client_->Connect();
718 if (client_supported_versions_[0] >= QUIC_VERSION_18 &&
719 negotiated_version_ <= QUIC_VERSION_16) {
720 // If the version negotiation has resulted in a downgrade, then the client
721 // must wait for the handshake to complete before sending any data.
722 // Otherwise it may have queued frames which will trigger a
723 // DFATAL when they are serialized after the downgrade.
724 client_->client()->WaitForCryptoHandshakeConfirmed();
726 ASSERT_TRUE(client_->client()->connected());
727 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
728 EXPECT_EQ(2, client_->client()->session()->GetNumSentClientHellos());
729 VerifyCleanConnection(false);
732 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
733 ASSERT_TRUE(Initialize());
734 client_->client()->WaitForCryptoHandshakeConfirmed();
735 server_thread_->WaitForCryptoHandshakeConfirmed();
737 FecPolicy expected_policy =
738 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
740 // Verify that server's FEC configuration is correct.
741 server_thread_->Pause();
742 QuicDispatcher* dispatcher =
743 QuicServerPeer::GetDispatcher(server_thread_->server());
744 ASSERT_EQ(1u, dispatcher->session_map().size());
745 QuicSession* session = dispatcher->session_map().begin()->second;
746 EXPECT_EQ(expected_policy,
747 QuicSessionPeer::GetHeadersStream(session)->fec_policy());
748 server_thread_->Resume();
750 // Verify that client's FEC configuration is correct.
751 EXPECT_EQ(expected_policy,
752 QuicSessionPeer::GetHeadersStream(
753 client_->client()->session())->fec_policy());
754 EXPECT_EQ(expected_policy,
755 client_->GetOrCreateStream()->fec_policy());
758 // TODO(shess): This is flaky on ChromiumOS bots.
759 // http://crbug.com/374871
760 TEST_P(EndToEndTest, DISABLED_LargePostSmallBandwidthLargeBuffer) {
761 ASSERT_TRUE(Initialize());
762 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
763 // 256KB per second with a 256KB buffer from server to client. Wireless
764 // clients commonly have larger buffers, but our max CWND is 200.
765 server_writer_->set_max_bandwidth_and_buffer_size(
766 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
768 client_->client()->WaitForCryptoHandshakeConfirmed();
770 // 1 MB body.
771 string body;
772 GenerateBody(&body, 1024 * 1024);
774 HTTPMessage request(HttpConstants::HTTP_1_1,
775 HttpConstants::POST, "/foo");
776 request.AddBody(body, true);
778 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
779 // This connection will not drop packets, because the buffer size is larger
780 // than the default receive window.
781 VerifyCleanConnection(false);
784 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
785 // Regression test for b/14677858.
786 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
787 // if currently connection level flow control blocked. If set, this results in
788 // an infinite loop in the EpollServer, as the alarm fires and is immediately
789 // rescheduled.
790 ASSERT_TRUE(Initialize());
791 if (negotiated_version_ < QUIC_VERSION_19) {
792 return;
794 client_->client()->WaitForCryptoHandshakeConfirmed();
796 // Ensure both stream and connection level are flow control blocked by setting
797 // the send window offset to 0.
798 const uint64 kFlowControlWindow =
799 server_config_.GetInitialFlowControlWindowToSend();
800 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
801 QuicSession* session = client_->client()->session();
802 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
803 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
804 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
805 EXPECT_TRUE(session->flow_controller()->IsBlocked());
807 // Make sure that the stream has data pending so that it will be marked as
808 // write blocked when it receives a stream level WINDOW_UPDATE.
809 stream->SendBody("hello", false);
811 // The stream now attempts to write, fails because it is still connection
812 // level flow control blocked, and is added to the write blocked list.
813 QuicWindowUpdateFrame window_update(stream->id(), 2 * kFlowControlWindow);
814 stream->OnWindowUpdateFrame(window_update);
816 // Prior to fixing b/14677858 this call would result in an infinite loop in
817 // Chromium. As a proxy for detecting this, we now check whether the
818 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
819 // connection is still flow control blocked.
820 session->connection()->OnCanWrite();
822 QuicAlarm* resume_writes_alarm =
823 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
824 EXPECT_FALSE(resume_writes_alarm->IsSet());
827 TEST_P(EndToEndTest, InvalidStream) {
828 ASSERT_TRUE(Initialize());
829 client_->client()->WaitForCryptoHandshakeConfirmed();
831 string body;
832 GenerateBody(&body, kMaxPacketSize);
834 HTTPMessage request(HttpConstants::HTTP_1_1,
835 HttpConstants::POST, "/foo");
836 request.AddBody(body, true);
837 // Force the client to write with a stream ID belonging to a nonexistent
838 // server-side stream.
839 QuicSessionPeer::SetNextStreamId(client_->client()->session(), 2);
841 client_->SendCustomSynchronousRequest(request);
842 // EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
843 EXPECT_EQ(QUIC_PACKET_FOR_NONEXISTENT_STREAM, client_->connection_error());
846 // TODO(rch): this test seems to cause net_unittests timeouts :|
847 TEST_P(EndToEndTest, DISABLED_MultipleTermination) {
848 ASSERT_TRUE(Initialize());
850 HTTPMessage request(HttpConstants::HTTP_1_1,
851 HttpConstants::POST, "/foo");
852 request.AddHeader("content-length", "3");
853 request.set_has_complete_message(false);
855 // Set the offset so we won't frame. Otherwise when we pick up termination
856 // before HTTP framing is complete, we send an error and close the stream,
857 // and the second write is picked up as writing on a closed stream.
858 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
859 ASSERT_TRUE(stream != NULL);
860 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
862 client_->SendData("bar", true);
863 client_->WaitForWriteToFlush();
865 // By default the stream protects itself from writes after terminte is set.
866 // Override this to test the server handling buggy clients.
867 ReliableQuicStreamPeer::SetWriteSideClosed(
868 false, client_->GetOrCreateStream());
870 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
873 TEST_P(EndToEndTest, Timeout) {
874 client_config_.set_idle_connection_state_lifetime(
875 QuicTime::Delta::FromMicroseconds(500),
876 QuicTime::Delta::FromMicroseconds(500));
877 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
878 // that's enough to validate timeout in this case.
879 Initialize();
880 while (client_->client()->connected()) {
881 client_->client()->WaitForEvents();
885 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
886 // Negotiate 1 max open stream.
887 client_config_.set_max_streams_per_connection(1, 1);
888 ASSERT_TRUE(Initialize());
889 client_->client()->WaitForCryptoHandshakeConfirmed();
891 // Make the client misbehave after negotiation.
892 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(), 10);
894 HTTPMessage request(HttpConstants::HTTP_1_1,
895 HttpConstants::POST, "/foo");
896 request.AddHeader("content-length", "3");
897 request.set_has_complete_message(false);
899 // Open two simultaneous streams.
900 client_->SendMessage(request);
901 client_->SendMessage(request);
902 client_->WaitForResponse();
904 EXPECT_FALSE(client_->connected());
905 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
906 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
909 TEST_P(EndToEndTest, NegotiateCongestionControl) {
910 ASSERT_TRUE(Initialize());
911 client_->client()->WaitForCryptoHandshakeConfirmed();
913 CongestionControlType expected_congestion_control_type;
914 switch (GetParam().congestion_control_tag) {
915 case kRENO:
916 expected_congestion_control_type = kReno;
917 break;
918 case kTBBR:
919 expected_congestion_control_type = kBBR;
920 break;
921 case kQBIC:
922 expected_congestion_control_type = kCubic;
923 break;
924 default:
925 DLOG(FATAL) << "Unexpected congestion control tag";
928 EXPECT_EQ(expected_congestion_control_type,
929 QuicSentPacketManagerPeer::GetCongestionControlAlgorithm(
930 *GetSentPacketManagerFromFirstServerSession())
931 ->GetCongestionControlType());
934 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
935 // Server limits the number of max streams to 2.
936 server_config_.set_max_streams_per_connection(2, 2);
937 // Client tries to negotiate for 10.
938 client_config_.set_max_streams_per_connection(10, 5);
940 ASSERT_TRUE(Initialize());
941 client_->client()->WaitForCryptoHandshakeConfirmed();
942 QuicConfig* client_negotiated_config = client_->client()->session()->config();
943 EXPECT_EQ(2u, client_negotiated_config->max_streams_per_connection());
946 // TODO(rtenneti): DISABLED_LimitCongestionWindowAndRTT seems to be flaky.
947 // http://crbug.com/321870.
948 TEST_P(EndToEndTest, DISABLED_LimitCongestionWindowAndRTT) {
949 // Client tries to request twice the server's max initial window, and the
950 // server limits it to the max.
951 client_config_.SetInitialCongestionWindowToSend(2 * kMaxInitialWindow);
952 client_config_.SetInitialRoundTripTimeUsToSend(1);
954 ASSERT_TRUE(Initialize());
955 client_->client()->WaitForCryptoHandshakeConfirmed();
956 server_thread_->WaitForCryptoHandshakeConfirmed();
958 // Pause the server so we can access the server's internals without races.
959 server_thread_->Pause();
960 QuicDispatcher* dispatcher =
961 QuicServerPeer::GetDispatcher(server_thread_->server());
962 ASSERT_EQ(1u, dispatcher->session_map().size());
963 const QuicSentPacketManager& client_sent_packet_manager =
964 client_->client()->session()->connection()->sent_packet_manager();
965 const QuicSentPacketManager& server_sent_packet_manager =
966 *GetSentPacketManagerFromFirstServerSession();
968 // The client shouldn't set it's initial window based on the negotiated value.
969 EXPECT_EQ(kDefaultInitialWindow * kDefaultTCPMSS,
970 client_sent_packet_manager.GetCongestionWindow());
971 EXPECT_EQ(kMaxInitialWindow * kDefaultTCPMSS,
972 server_sent_packet_manager.GetCongestionWindow());
974 EXPECT_EQ(GetParam().use_pacing, server_sent_packet_manager.using_pacing());
975 EXPECT_EQ(GetParam().use_pacing, client_sent_packet_manager.using_pacing());
977 EXPECT_EQ(100000u,
978 client_sent_packet_manager.GetRttStats()->initial_rtt_us());
979 EXPECT_EQ(1u, server_sent_packet_manager.GetRttStats()->initial_rtt_us());
981 // Now use the negotiated limits with packet loss.
982 SetPacketLossPercentage(30);
984 // 10 KB body.
985 string body;
986 GenerateBody(&body, 1024 * 10);
988 HTTPMessage request(HttpConstants::HTTP_1_1,
989 HttpConstants::POST, "/foo");
990 request.AddBody(body, true);
992 server_thread_->Resume();
994 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
997 TEST_P(EndToEndTest, MaxInitialRTT) {
998 // Client tries to suggest twice the server's max initial rtt and the server
999 // uses the max.
1000 client_config_.SetInitialRoundTripTimeUsToSend(
1001 2 * kMaxInitialRoundTripTimeUs);
1003 ASSERT_TRUE(Initialize());
1004 client_->client()->WaitForCryptoHandshakeConfirmed();
1005 server_thread_->WaitForCryptoHandshakeConfirmed();
1007 // Pause the server so we can access the server's internals without races.
1008 server_thread_->Pause();
1009 QuicDispatcher* dispatcher =
1010 QuicServerPeer::GetDispatcher(server_thread_->server());
1011 ASSERT_EQ(1u, dispatcher->session_map().size());
1012 QuicSession* session = dispatcher->session_map().begin()->second;
1013 const QuicSentPacketManager& client_sent_packet_manager =
1014 client_->client()->session()->connection()->sent_packet_manager();
1015 const QuicSentPacketManager& server_sent_packet_manager =
1016 session->connection()->sent_packet_manager();
1018 // Now that acks have been exchanged, the RTT estimate has decreased on the
1019 // server and is not infinite on the client.
1020 EXPECT_FALSE(
1021 client_sent_packet_manager.GetRttStats()->SmoothedRtt().IsInfinite());
1022 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
1023 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1024 EXPECT_GE(
1025 static_cast<int64>(kMaxInitialRoundTripTimeUs),
1026 server_sent_packet_manager.GetRttStats()->SmoothedRtt().ToMicroseconds());
1027 server_thread_->Resume();
1030 TEST_P(EndToEndTest, MinInitialRTT) {
1031 // Client tries to suggest 0 and the server uses the default.
1032 client_config_.SetInitialRoundTripTimeUsToSend(0);
1034 ASSERT_TRUE(Initialize());
1035 client_->client()->WaitForCryptoHandshakeConfirmed();
1036 server_thread_->WaitForCryptoHandshakeConfirmed();
1038 // Pause the server so we can access the server's internals without races.
1039 server_thread_->Pause();
1040 QuicDispatcher* dispatcher =
1041 QuicServerPeer::GetDispatcher(server_thread_->server());
1042 ASSERT_EQ(1u, dispatcher->session_map().size());
1043 QuicSession* session = dispatcher->session_map().begin()->second;
1044 const QuicSentPacketManager& client_sent_packet_manager =
1045 client_->client()->session()->connection()->sent_packet_manager();
1046 const QuicSentPacketManager& server_sent_packet_manager =
1047 session->connection()->sent_packet_manager();
1049 // Now that acks have been exchanged, the RTT estimate has decreased on the
1050 // server and is not infinite on the client.
1051 EXPECT_FALSE(
1052 client_sent_packet_manager.GetRttStats()->SmoothedRtt().IsInfinite());
1053 // Expect the default rtt of 100ms.
1054 EXPECT_EQ(static_cast<int64>(100 * base::Time::kMicrosecondsPerMillisecond),
1055 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1056 // Ensure the bandwidth is valid.
1057 client_sent_packet_manager.BandwidthEstimate();
1058 server_sent_packet_manager.BandwidthEstimate();
1059 server_thread_->Resume();
1062 TEST_P(EndToEndTest, ResetConnection) {
1063 ASSERT_TRUE(Initialize());
1064 client_->client()->WaitForCryptoHandshakeConfirmed();
1066 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1067 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1068 client_->ResetConnection();
1069 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1070 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1073 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1074 SetPacketLossPercentage(1);
1075 ASSERT_TRUE(Initialize());
1076 string large_body;
1077 GenerateBody(&large_body, 10240);
1078 int max_streams = 100;
1080 AddToCache("GET", "/large_response", "HTTP/1.1", "200", "OK", large_body);;
1082 client_->client()->WaitForCryptoHandshakeConfirmed();
1083 SetPacketLossPercentage(10);
1085 for (int i = 0; i < max_streams; ++i) {
1086 EXPECT_LT(0, client_->SendRequest("/large_response"));
1089 // WaitForEvents waits 50ms and returns true if there are outstanding
1090 // requests.
1091 while (client_->client()->WaitForEvents() == true) {
1095 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1096 ASSERT_TRUE(Initialize());
1097 string small_body;
1098 GenerateBody(&small_body, 256);
1100 AddToCache("GET", "/small_response", "HTTP/1.1", "200", "OK", small_body);
1102 client_->client()->WaitForCryptoHandshakeConfirmed();
1104 QuicSession* session = client_->client()->session();
1105 // Lose the request.
1106 SetPacketLossPercentage(100);
1107 EXPECT_LT(0, client_->SendRequest("/small_response"));
1108 client_->client()->WaitForEvents();
1109 // Transmit the cancel, and ensure the connection is torn down properly.
1110 SetPacketLossPercentage(0);
1111 QuicStreamId stream_id = kClientDataStreamId1;
1112 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1114 // WaitForEvents waits 50ms and returns true if there are outstanding
1115 // requests.
1116 while (client_->client()->WaitForEvents() == true) {
1118 // It should be completely fine to RST a stream before any data has been
1119 // received for that stream.
1120 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1123 class WrongAddressWriter : public QuicPacketWriterWrapper {
1124 public:
1125 WrongAddressWriter() {
1126 IPAddressNumber ip;
1127 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1128 self_address_ = IPEndPoint(ip, 0);
1131 virtual WriteResult WritePacket(
1132 const char* buffer,
1133 size_t buf_len,
1134 const IPAddressNumber& real_self_address,
1135 const IPEndPoint& peer_address) OVERRIDE {
1136 // Use wrong address!
1137 return QuicPacketWriterWrapper::WritePacket(
1138 buffer, buf_len, self_address_.address(), peer_address);
1141 virtual bool IsWriteBlockedDataBuffered() const OVERRIDE {
1142 return false;
1145 IPEndPoint self_address_;
1148 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1149 // Tests that the client's IP can not change during an established QUIC
1150 // connection. If it changes, the connection is closed by the server as we do
1151 // not yet support IP migration.
1152 ASSERT_TRUE(Initialize());
1154 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1155 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1157 WrongAddressWriter* writer = new WrongAddressWriter();
1159 writer->set_writer(new QuicDefaultPacketWriter(client_->client()->fd()));
1160 QuicConnectionPeer::SetWriter(client_->client()->session()->connection(),
1161 writer,
1162 /* owns_writer= */ true);
1164 client_->SendSynchronousRequest("/bar");
1166 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1167 EXPECT_EQ(QUIC_ERROR_MIGRATING_ADDRESS, client_->connection_error());
1170 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1171 // Tests that the client's port can change during an established QUIC
1172 // connection, and that doing so does not result in the connection being
1173 // closed by the server.
1174 ASSERT_TRUE(Initialize());
1176 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1177 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1179 // Store the client address which was used to send the first request.
1180 IPEndPoint old_address = client_->client()->client_address();
1182 // Stop listening on the old FD.
1183 EpollServer* eps = client_->epoll_server();
1184 int old_fd = client_->client()->fd();
1185 eps->UnregisterFD(old_fd);
1186 // Create a new socket before closing the old one, which will result in a new
1187 // ephemeral port.
1188 QuicClientPeer::CreateUDPSocket(client_->client());
1189 close(old_fd);
1191 // The packet writer needs to be updated to use the new FD.
1192 client_->client()->CreateQuicPacketWriter();
1194 // Change the internal state of the client and connection to use the new port,
1195 // this is done because in a real NAT rebinding the client wouldn't see any
1196 // port change, and so expects no change to incoming port.
1197 // This is kind of ugly, but needed as we are simply swapping out the client
1198 // FD rather than any more complex NAT rebinding simulation.
1199 int new_port = client_->client()->client_address().port();
1200 QuicClientPeer::SetClientPort(client_->client(), new_port);
1201 QuicConnectionPeer::SetSelfAddress(
1202 client_->client()->session()->connection(),
1203 IPEndPoint(
1204 client_->client()->session()->connection()->self_address().address(),
1205 new_port));
1207 // Register the new FD for epoll events.
1208 int new_fd = client_->client()->fd();
1209 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1211 // Send a second request, using the new FD.
1212 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1213 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1215 // Verify that the client's ephemeral port is different.
1216 IPEndPoint new_address = client_->client()->client_address();
1217 EXPECT_EQ(old_address.address(), new_address.address());
1218 EXPECT_NE(old_address.port(), new_address.port());
1222 TEST_P(EndToEndTest, DifferentFlowControlWindowsQ019) {
1223 // TODO(rjshade): Remove this test when removing QUIC_VERSION_19.
1224 // Client and server can set different initial flow control receive windows.
1225 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1226 // in the crypto handshake.
1228 const uint32 kClientIFCW = 123456;
1229 set_client_initial_flow_control_receive_window(kClientIFCW);
1231 const uint32 kServerIFCW = 654321;
1232 set_server_initial_flow_control_receive_window(kServerIFCW);
1234 ASSERT_TRUE(Initialize());
1235 if (negotiated_version_ > QUIC_VERSION_19) {
1236 return;
1239 // Values are exchanged during crypto handshake, so wait for that to finish.
1240 client_->client()->WaitForCryptoHandshakeConfirmed();
1241 server_thread_->WaitForCryptoHandshakeConfirmed();
1243 // Client should have the right value for server's receive window.
1244 EXPECT_EQ(kServerIFCW, client_->client()
1245 ->session()
1246 ->config()
1247 ->ReceivedInitialFlowControlWindowBytes());
1249 // Server should have the right value for client's receive window.
1250 server_thread_->Pause();
1251 QuicDispatcher* dispatcher =
1252 QuicServerPeer::GetDispatcher(server_thread_->server());
1253 QuicSession* session = dispatcher->session_map().begin()->second;
1254 EXPECT_EQ(kClientIFCW,
1255 session->config()->ReceivedInitialFlowControlWindowBytes());
1256 server_thread_->Resume();
1259 TEST_P(EndToEndTest, DifferentFlowControlWindowsQ020) {
1260 // TODO(rjshade): Rename to DifferentFlowControlWindows when removing
1261 // QUIC_VERSION_19.
1262 // Client and server can set different initial flow control receive windows.
1263 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1264 // in the crypto handshake.
1265 const uint32 kClientStreamIFCW = 123456;
1266 const uint32 kClientSessionIFCW = 234567;
1267 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1268 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1270 const uint32 kServerStreamIFCW = 654321;
1271 const uint32 kServerSessionIFCW = 765432;
1272 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1273 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1275 ASSERT_TRUE(Initialize());
1276 if (negotiated_version_ <= QUIC_VERSION_19) {
1277 return;
1280 // Values are exchanged during crypto handshake, so wait for that to finish.
1281 client_->client()->WaitForCryptoHandshakeConfirmed();
1282 server_thread_->WaitForCryptoHandshakeConfirmed();
1284 // Open a data stream to make sure the stream level flow control is updated.
1285 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1286 stream->SendBody("hello", false);
1288 // Client should have the right values for server's receive window.
1289 EXPECT_EQ(kServerStreamIFCW,
1290 client_->client()
1291 ->session()
1292 ->config()
1293 ->ReceivedInitialStreamFlowControlWindowBytes());
1294 EXPECT_EQ(kServerSessionIFCW,
1295 client_->client()
1296 ->session()
1297 ->config()
1298 ->ReceivedInitialSessionFlowControlWindowBytes());
1299 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1300 stream->flow_controller()));
1301 EXPECT_EQ(kServerSessionIFCW,
1302 QuicFlowControllerPeer::SendWindowOffset(
1303 client_->client()->session()->flow_controller()));
1305 // Server should have the right values for client's receive window.
1306 server_thread_->Pause();
1307 QuicDispatcher* dispatcher =
1308 QuicServerPeer::GetDispatcher(server_thread_->server());
1309 QuicSession* session = dispatcher->session_map().begin()->second;
1310 EXPECT_EQ(kClientStreamIFCW,
1311 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1312 EXPECT_EQ(kClientSessionIFCW,
1313 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1314 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1315 session->flow_controller()));
1316 server_thread_->Resume();
1319 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1320 // The special headers and crypto streams should be subject to per-stream flow
1321 // control limits, but should not be subject to connection level flow control.
1322 const uint32 kStreamIFCW = 123456;
1323 const uint32 kSessionIFCW = 234567;
1324 set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
1325 set_client_initial_session_flow_control_receive_window(kSessionIFCW);
1326 set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
1327 set_server_initial_session_flow_control_receive_window(kSessionIFCW);
1329 ASSERT_TRUE(Initialize());
1330 if (negotiated_version_ <= QUIC_VERSION_20) {
1331 return;
1334 // Wait for crypto handshake to finish. This should have contributed to the
1335 // crypto stream flow control window, but not affected the session flow
1336 // control window.
1337 client_->client()->WaitForCryptoHandshakeConfirmed();
1338 server_thread_->WaitForCryptoHandshakeConfirmed();
1340 QuicCryptoStream* crypto_stream =
1341 QuicSessionPeer::GetCryptoStream(client_->client()->session());
1342 EXPECT_LT(
1343 QuicFlowControllerPeer::SendWindowSize(crypto_stream->flow_controller()),
1344 kStreamIFCW);
1345 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1346 client_->client()->session()->flow_controller()));
1348 // Send a request with no body, and verify that the connection level window
1349 // has not been affected.
1350 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1352 QuicHeadersStream* headers_stream =
1353 QuicSessionPeer::GetHeadersStream(client_->client()->session());
1354 EXPECT_LT(
1355 QuicFlowControllerPeer::SendWindowSize(headers_stream->flow_controller()),
1356 kStreamIFCW);
1357 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
1358 client_->client()->session()->flow_controller()));
1360 // Server should be in a similar state: connection flow control window should
1361 // not have any bytes marked as received.
1362 server_thread_->Pause();
1363 QuicDispatcher* dispatcher =
1364 QuicServerPeer::GetDispatcher(server_thread_->server());
1365 QuicSession* session = dispatcher->session_map().begin()->second;
1366 QuicFlowController* server_connection_flow_controller =
1367 session->flow_controller();
1368 EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
1369 server_connection_flow_controller));
1370 server_thread_->Resume();
1373 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1374 // Regression test for b/16010251.
1375 // A stream created on receipt of a simple request with no body will never get
1376 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1377 // the locally closed streams map: it will never be removed if so.
1378 ASSERT_TRUE(Initialize());
1380 // Send a simple headers only request, and receive response.
1381 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1382 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1384 // Now verify that the server is not waiting for a final FIN or RST.
1385 server_thread_->Pause();
1386 QuicDispatcher* dispatcher =
1387 QuicServerPeer::GetDispatcher(server_thread_->server());
1388 QuicSession* session = dispatcher->session_map().begin()->second;
1389 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1390 session).size());
1391 server_thread_->Resume();
1394 } // namespace
1395 } // namespace test
1396 } // namespace tools
1397 } // namespace net