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