Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / tools / quic / end_to_end_test.cc
blob651f499be7873d7b34bc5756182d17529d7af9bc
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 bool auto_tune_flow_control_window)
96 : client_supported_versions(client_supported_versions),
97 server_supported_versions(server_supported_versions),
98 negotiated_version(negotiated_version),
99 use_fec(use_fec),
100 client_supports_stateless_rejects(client_supports_stateless_rejects),
101 server_uses_stateless_rejects_if_peer_supported(
102 server_uses_stateless_rejects_if_peer_supported),
103 congestion_control_tag(congestion_control_tag),
104 auto_tune_flow_control_window(auto_tune_flow_control_window) {}
106 friend ostream& operator<<(ostream& os, const TestParams& p) {
107 os << "{ server_supported_versions: "
108 << QuicVersionVectorToString(p.server_supported_versions);
109 os << " client_supported_versions: "
110 << QuicVersionVectorToString(p.client_supported_versions);
111 os << " negotiated_version: " << QuicVersionToString(p.negotiated_version);
112 os << " client_supports_stateless_rejects: "
113 << p.client_supports_stateless_rejects;
114 os << " server_uses_stateless_rejects_if_peer_supported: "
115 << p.server_uses_stateless_rejects_if_peer_supported;
116 os << " use_fec: " << p.use_fec;
117 os << " congestion_control_tag: "
118 << QuicUtils::TagToString(p.congestion_control_tag);
119 os << " auto_tune_flow_control_window: " << p.auto_tune_flow_control_window
120 << " }";
121 return os;
124 QuicVersionVector client_supported_versions;
125 QuicVersionVector server_supported_versions;
126 QuicVersion negotiated_version;
127 bool use_fec;
128 bool client_supports_stateless_rejects;
129 bool server_uses_stateless_rejects_if_peer_supported;
130 QuicTag congestion_control_tag;
131 bool auto_tune_flow_control_window;
134 // Constructs various test permutations.
135 vector<TestParams> GetTestParams() {
136 // Divide the versions into buckets in which the intra-frame format
137 // is compatible. When clients encounter QUIC version negotiation
138 // they simply retransmit all packets using the new version's
139 // QUIC framing. However, they are unable to change the intra-frame
140 // layout (for example to change SPDY/4 headers to SPDY/3). So
141 // these tests need to ensure that clients are never attempting
142 // to do 0-RTT across incompatible versions. Chromium only supports
143 // a single version at a time anyway. :)
144 QuicVersionVector all_supported_versions = QuicSupportedVersions();
145 QuicVersionVector client_version_buckets[2];
146 for (const QuicVersion version : all_supported_versions) {
147 if (version <= QUIC_VERSION_24) {
148 // SPDY/4 compression but SPDY/3 headers
149 client_version_buckets[0].push_back(version);
150 } else {
151 // SPDY/4
152 client_version_buckets[1].push_back(version);
156 vector<TestParams> params;
157 // TODO(rtenneti): Add kTBBR after BBR code is checked in.
158 // for (const QuicTag congestion_control_tag : {kRENO, kTBBR, kQBIC}) {
159 for (const QuicTag congestion_control_tag : {kRENO, kQBIC}) {
160 for (const bool use_fec : {false, true}) {
161 for (const QuicVersionVector& client_versions : client_version_buckets) {
162 // A number of end to end tests fail when stateless rejects are enabled
163 // *and* there are more than two QUIC versions.
164 // TODO(b/23745998) Re-enable client stateless reject support.
165 for (bool client_supports_stateless_rejects : {false}) {
166 // TODO(b/23745998) Re-enable server stateless reject support.
167 for (bool server_uses_stateless_rejects_if_peer_supported : {false}) {
168 for (bool auto_tune_flow_control_window : {true, false}) {
169 CHECK(!client_versions.empty());
170 // Add an entry for server and client supporting all versions.
171 params.push_back(TestParams(
172 client_versions, all_supported_versions,
173 client_versions.front(), use_fec,
174 client_supports_stateless_rejects,
175 server_uses_stateless_rejects_if_peer_supported,
176 congestion_control_tag, auto_tune_flow_control_window));
178 // Test client supporting all versions and server supporting 1
179 // version. Simulate an old server and exercise version downgrade
180 // in the client. Protocol negotiation should occur. Skip the i =
181 // 0 case because it is essentially the same as the default case.
182 for (const QuicVersion version : client_versions) {
183 QuicVersionVector server_supported_versions;
184 server_supported_versions.push_back(version);
185 params.push_back(TestParams(
186 client_versions, server_supported_versions,
187 server_supported_versions.front(), use_fec,
188 client_supports_stateless_rejects,
189 server_uses_stateless_rejects_if_peer_supported,
190 congestion_control_tag, auto_tune_flow_control_window));
198 return params;
201 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
202 public:
203 ServerDelegate(TestWriterFactory* writer_factory,
204 QuicDispatcher* dispatcher)
205 : writer_factory_(writer_factory),
206 dispatcher_(dispatcher) {}
207 ~ServerDelegate() override {}
208 void OnPacketSent(WriteResult result) override {
209 writer_factory_->OnPacketSent(result);
211 void OnCanWrite() override { dispatcher_->OnCanWrite(); }
213 private:
214 TestWriterFactory* writer_factory_;
215 QuicDispatcher* dispatcher_;
218 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
219 public:
220 explicit ClientDelegate(QuicClient* client) : client_(client) {}
221 ~ClientDelegate() override {}
222 void OnPacketSent(WriteResult result) override {}
223 void OnCanWrite() override {
224 EpollEvent event(EPOLLOUT, false);
225 client_->OnEvent(client_->fd(), &event);
228 private:
229 QuicClient* client_;
232 class EndToEndTest : public ::testing::TestWithParam<TestParams> {
233 protected:
234 EndToEndTest()
235 : initialized_(false),
236 server_address_(IPEndPoint(Loopback4(), 0)),
237 server_hostname_("example.com"),
238 server_started_(false),
239 strike_register_no_startup_period_(false) {
240 client_supported_versions_ = GetParam().client_supported_versions;
241 server_supported_versions_ = GetParam().server_supported_versions;
242 negotiated_version_ = GetParam().negotiated_version;
243 FLAGS_enable_quic_fec = GetParam().use_fec;
245 VLOG(1) << "Using Configuration: " << GetParam();
247 // Use different flow control windows for client/server.
248 client_config_.SetInitialStreamFlowControlWindowToSend(
249 2 * kInitialStreamFlowControlWindowForTest);
250 client_config_.SetInitialSessionFlowControlWindowToSend(
251 2 * kInitialSessionFlowControlWindowForTest);
252 server_config_.SetInitialStreamFlowControlWindowToSend(
253 3 * kInitialStreamFlowControlWindowForTest);
254 server_config_.SetInitialSessionFlowControlWindowToSend(
255 3 * kInitialSessionFlowControlWindowForTest);
257 QuicInMemoryCachePeer::ResetForTests();
258 AddToCache("/foo", 200, "OK", kFooResponseBody);
259 AddToCache("/bar", 200, "OK", kBarResponseBody);
262 ~EndToEndTest() override {
263 // TODO(rtenneti): port RecycleUnusedPort if needed.
264 // RecycleUnusedPort(server_address_.port());
265 QuicInMemoryCachePeer::ResetForTests();
268 QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
269 QuicTestClient* client = new QuicTestClient(
270 server_address_, server_hostname_,
271 /*secure=*/true, client_config_, client_supported_versions_);
272 client->UseWriter(writer);
273 client->Connect();
274 return client;
277 void set_client_initial_stream_flow_control_receive_window(uint32 window) {
278 CHECK(client_.get() == nullptr);
279 DVLOG(1) << "Setting client initial stream flow control window: " << window;
280 client_config_.SetInitialStreamFlowControlWindowToSend(window);
283 void set_client_initial_session_flow_control_receive_window(uint32 window) {
284 CHECK(client_.get() == nullptr);
285 DVLOG(1) << "Setting client initial session flow control window: "
286 << window;
287 client_config_.SetInitialSessionFlowControlWindowToSend(window);
290 void set_server_initial_stream_flow_control_receive_window(uint32 window) {
291 CHECK(server_thread_.get() == nullptr);
292 DVLOG(1) << "Setting server initial stream flow control window: "
293 << window;
294 server_config_.SetInitialStreamFlowControlWindowToSend(window);
297 void set_server_initial_session_flow_control_receive_window(uint32 window) {
298 CHECK(server_thread_.get() == nullptr);
299 DVLOG(1) << "Setting server initial session flow control window: "
300 << window;
301 server_config_.SetInitialSessionFlowControlWindowToSend(window);
304 const QuicSentPacketManager *
305 GetSentPacketManagerFromFirstServerSession() const {
306 QuicDispatcher* dispatcher =
307 QuicServerPeer::GetDispatcher(server_thread_->server());
308 QuicSession* session = dispatcher->session_map().begin()->second;
309 return &session->connection()->sent_packet_manager();
312 bool Initialize() {
313 QuicTagVector copt;
314 server_config_.SetConnectionOptionsToSend(copt);
316 // TODO(nimia): Consider setting the congestion control algorithm for the
317 // client as well according to the test parameter.
318 copt.push_back(GetParam().congestion_control_tag);
320 if (GetParam().use_fec) {
321 // Set FEC config in client's connection options and in client session.
322 copt.push_back(kFHDR);
324 if (GetParam().client_supports_stateless_rejects) {
325 copt.push_back(kSREJ);
327 if (GetParam().auto_tune_flow_control_window) {
328 copt.push_back(kAFCW);
329 copt.push_back(kIFW5);
331 client_config_.SetConnectionOptionsToSend(copt);
333 // Start the server first, because CreateQuicClient() attempts
334 // to connect to the server.
335 StartServer();
336 client_.reset(CreateQuicClient(client_writer_));
337 if (GetParam().use_fec) {
338 // Set FecPolicy to always protect data on all streams.
339 client_->SetFecPolicy(FEC_PROTECT_ALWAYS);
341 static EpollEvent event(EPOLLOUT, false);
342 client_writer_->Initialize(
343 reinterpret_cast<QuicEpollConnectionHelper*>(
344 QuicConnectionPeer::GetHelper(
345 client_->client()->session()->connection())),
346 new ClientDelegate(client_->client()));
347 initialized_ = true;
348 return client_->client()->connected();
351 void SetUp() override {
352 // The ownership of these gets transferred to the QuicPacketWriterWrapper
353 // and TestWriterFactory when Initialize() is executed.
354 client_writer_ = new PacketDroppingTestWriter();
355 server_writer_ = new PacketDroppingTestWriter();
358 void TearDown() override {
359 ASSERT_TRUE(initialized_) << "You must call Initialize() in every test "
360 << "case. Otherwise, your test will leak memory.";
361 StopServer();
364 void StartServer() {
365 server_thread_.reset(new ServerThread(
366 new QuicServer(server_config_, server_supported_versions_),
367 /*is_secure=*/true, server_address_,
368 strike_register_no_startup_period_));
369 server_thread_->Initialize();
370 server_address_ = IPEndPoint(server_address_.address(),
371 server_thread_->GetPort());
372 QuicDispatcher* dispatcher =
373 QuicServerPeer::GetDispatcher(server_thread_->server());
374 TestWriterFactory* packet_writer_factory = new TestWriterFactory();
375 QuicDispatcherPeer::SetPacketWriterFactory(dispatcher,
376 packet_writer_factory);
377 QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
379 if (GetParam().server_uses_stateless_rejects_if_peer_supported) {
380 // Enable stateless rejects and force the server to always send
381 // them.
382 FLAGS_enable_quic_stateless_reject_support = true;
383 FLAGS_quic_session_map_threshold_for_stateless_rejects = 0;
384 } else {
385 FLAGS_enable_quic_stateless_reject_support = false;
386 FLAGS_quic_session_map_threshold_for_stateless_rejects = -1;
389 server_writer_->Initialize(
390 QuicDispatcherPeer::GetHelper(dispatcher),
391 new ServerDelegate(packet_writer_factory, dispatcher));
392 server_thread_->Start();
393 server_started_ = true;
396 void StopServer() {
397 if (!server_started_)
398 return;
399 if (server_thread_.get()) {
400 server_thread_->Quit();
401 server_thread_->Join();
405 void AddToCache(StringPiece path,
406 int response_code,
407 StringPiece response_detail,
408 StringPiece body) {
409 QuicInMemoryCache::GetInstance()->AddSimpleResponse(
410 "www.google.com", path, response_code, response_detail, body);
413 void SetPacketLossPercentage(int32 loss) {
414 // TODO(rtenneti): enable when we can do random packet loss tests in
415 // chrome's tree.
416 if (loss != 0 && loss != 100)
417 return;
418 client_writer_->set_fake_packet_loss_percentage(loss);
419 server_writer_->set_fake_packet_loss_percentage(loss);
422 void SetPacketSendDelay(QuicTime::Delta delay) {
423 // TODO(rtenneti): enable when we can do random packet send delay tests in
424 // chrome's tree.
425 // client_writer_->set_fake_packet_delay(delay);
426 // server_writer_->set_fake_packet_delay(delay);
429 void SetReorderPercentage(int32 reorder) {
430 // TODO(rtenneti): enable when we can do random packet reorder tests in
431 // chrome's tree.
432 // client_writer_->set_fake_reorder_percentage(reorder);
433 // server_writer_->set_fake_reorder_percentage(reorder);
436 // Verifies that the client and server connections were both free of packets
437 // being discarded, based on connection stats.
438 // Calls server_thread_ Pause() and Resume(), which may only be called once
439 // per test.
440 void VerifyCleanConnection(bool had_packet_loss) {
441 QuicConnectionStats client_stats =
442 client_->client()->session()->connection()->GetStats();
443 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
444 // if (!had_packet_loss) {
445 // EXPECT_EQ(0u, client_stats.packets_lost);
446 // }
447 EXPECT_EQ(0u, client_stats.packets_discarded);
448 EXPECT_EQ(0u, client_stats.packets_dropped);
449 EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
451 const int num_expected_stateless_rejects =
452 (BothSidesSupportStatelessRejects() &&
453 client_->client()->session()->GetNumSentClientHellos() > 0)
455 : 0;
456 EXPECT_EQ(num_expected_stateless_rejects,
457 client_->client()->num_stateless_rejects_received());
459 server_thread_->Pause();
460 QuicDispatcher* dispatcher =
461 QuicServerPeer::GetDispatcher(server_thread_->server());
462 ASSERT_EQ(1u, dispatcher->session_map().size());
463 QuicSession* session = dispatcher->session_map().begin()->second;
464 QuicConnectionStats server_stats = session->connection()->GetStats();
465 // TODO(ianswett): Re-enable this check once b/19572432 is fixed.
466 // if (!had_packet_loss) {
467 // EXPECT_EQ(0u, server_stats.packets_lost);
468 // }
469 EXPECT_EQ(0u, server_stats.packets_discarded);
470 // TODO(ianswett): Restore the check for packets_dropped equals 0.
471 // The expect for packets received is equal to packets processed fails
472 // due to version negotiation packets.
473 server_thread_->Resume();
476 bool BothSidesSupportStatelessRejects() {
477 return (GetParam().server_uses_stateless_rejects_if_peer_supported &&
478 GetParam().client_supports_stateless_rejects);
481 void ExpectFlowControlsSynced(QuicFlowController* client,
482 QuicFlowController* server) {
483 EXPECT_EQ(QuicFlowControllerPeer::SendWindowSize(client),
484 QuicFlowControllerPeer::ReceiveWindowSize(server));
485 EXPECT_EQ(QuicFlowControllerPeer::ReceiveWindowSize(client),
486 QuicFlowControllerPeer::SendWindowSize(server));
489 bool initialized_;
490 IPEndPoint server_address_;
491 string server_hostname_;
492 scoped_ptr<ServerThread> server_thread_;
493 scoped_ptr<QuicTestClient> client_;
494 PacketDroppingTestWriter* client_writer_;
495 PacketDroppingTestWriter* server_writer_;
496 bool server_started_;
497 QuicConfig client_config_;
498 QuicConfig server_config_;
499 QuicVersionVector client_supported_versions_;
500 QuicVersionVector server_supported_versions_;
501 QuicVersion negotiated_version_;
502 bool strike_register_no_startup_period_;
505 // Run all end to end tests with all supported versions.
506 INSTANTIATE_TEST_CASE_P(EndToEndTests,
507 EndToEndTest,
508 ::testing::ValuesIn(GetTestParams()));
510 TEST_P(EndToEndTest, SimpleRequestResponse) {
511 ASSERT_TRUE(Initialize());
513 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
514 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
517 // TODO(rch): figure out how to detect missing v6 supprt (like on the linux
518 // try bots) and selectively disable this test.
519 TEST_P(EndToEndTest, DISABLED_SimpleRequestResponsev6) {
520 IPAddressNumber ip;
521 CHECK(net::ParseIPLiteralToNumber("::1", &ip));
522 server_address_ = IPEndPoint(ip, server_address_.port());
523 ASSERT_TRUE(Initialize());
525 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
526 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
529 TEST_P(EndToEndTest, SeparateFinPacket) {
530 ASSERT_TRUE(Initialize());
532 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
533 request.set_has_complete_message(false);
535 // Send a request in two parts: the request and then an empty packet with FIN.
536 client_->SendMessage(request);
537 client_->SendData("", true);
538 client_->WaitForResponse();
539 EXPECT_EQ(kFooResponseBody, client_->response_body());
540 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
542 // Now do the same thing but with a content length.
543 request.AddBody("foo", true);
544 client_->SendMessage(request);
545 client_->SendData("", true);
546 client_->WaitForResponse();
547 EXPECT_EQ(kFooResponseBody, client_->response_body());
548 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
551 TEST_P(EndToEndTest, MultipleRequestResponse) {
552 ASSERT_TRUE(Initialize());
554 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
555 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
556 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
557 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
560 TEST_P(EndToEndTest, MultipleClients) {
561 ASSERT_TRUE(Initialize());
562 scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
564 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
565 request.AddHeader("content-length", "3");
566 request.set_has_complete_message(false);
568 client_->SendMessage(request);
569 client2->SendMessage(request);
571 client_->SendData("bar", true);
572 client_->WaitForResponse();
573 EXPECT_EQ(kFooResponseBody, client_->response_body());
574 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
576 client2->SendData("eep", true);
577 client2->WaitForResponse();
578 EXPECT_EQ(kFooResponseBody, client2->response_body());
579 EXPECT_EQ(200u, client2->response_headers()->parsed_response_code());
582 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
583 // Send a large enough request to guarantee fragmentation.
584 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
585 AddToCache(huge_request, 200, "OK", kBarResponseBody);
587 ASSERT_TRUE(Initialize());
589 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
590 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
593 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
594 // Send a large enough request to guarantee fragmentation.
595 string huge_request = "/some/path?query=" + string(kMaxPacketSize, '.');
596 AddToCache(huge_request, 200, "OK", kBarResponseBody);
598 ASSERT_TRUE(Initialize());
599 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
600 SetReorderPercentage(50);
602 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest(huge_request));
603 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
606 TEST_P(EndToEndTest, PostMissingBytes) {
607 ASSERT_TRUE(Initialize());
609 // Add a content length header with no body.
610 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
611 request.AddHeader("content-length", "3");
612 request.set_skip_message_validation(true);
614 // This should be detected as stream fin without complete request,
615 // triggering an error response.
616 client_->SendCustomSynchronousRequest(request);
617 EXPECT_EQ("bad", client_->response_body());
618 EXPECT_EQ(500u, client_->response_headers()->parsed_response_code());
621 // TODO(rtenneti): DISABLED_LargePostNoPacketLoss seems to be flaky.
622 // http://crbug.com/297040.
623 TEST_P(EndToEndTest, DISABLED_LargePostNoPacketLoss) {
624 ASSERT_TRUE(Initialize());
626 client_->client()->WaitForCryptoHandshakeConfirmed();
628 // 1 MB body.
629 string body;
630 GenerateBody(&body, 1024 * 1024);
632 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
633 request.AddBody(body, true);
635 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
636 VerifyCleanConnection(false);
639 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
640 ASSERT_TRUE(Initialize());
641 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
643 client_->client()->WaitForCryptoHandshakeConfirmed();
645 // 100 KB body.
646 string body;
647 GenerateBody(&body, 100 * 1024);
649 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
650 request.AddBody(body, true);
652 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
653 VerifyCleanConnection(false);
656 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
657 if (!BothSidesSupportStatelessRejects()) {
658 // Connect with lower fake packet loss than we'd like to test.
659 // Until b/10126687 is fixed, losing handshake packets is pretty
660 // brutal.
661 // TODO(jokulik): Until we support redundant SREJ packets, don't
662 // drop handshake packets for stateless rejects.
663 SetPacketLossPercentage(5);
665 ASSERT_TRUE(Initialize());
667 // Wait for the server SHLO before upping the packet loss.
668 client_->client()->WaitForCryptoHandshakeConfirmed();
669 SetPacketLossPercentage(30);
671 // 10 KB body.
672 string body;
673 GenerateBody(&body, 1024 * 10);
675 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
676 request.AddBody(body, true);
678 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
679 VerifyCleanConnection(true);
682 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
683 if (!BothSidesSupportStatelessRejects()) {
684 // Connect with lower fake packet loss than we'd like to test. Until
685 // b/10126687 is fixed, losing handshake packets is pretty brutal.
686 // TODO(jokulik): Until we support redundant SREJ packets, don't
687 // drop handshake packets for stateless rejects.
688 SetPacketLossPercentage(5);
690 ASSERT_TRUE(Initialize());
692 // Wait for the server SHLO before upping the packet loss.
693 client_->client()->WaitForCryptoHandshakeConfirmed();
694 SetPacketLossPercentage(10);
695 client_writer_->set_fake_blocked_socket_percentage(10);
697 // 10 KB body.
698 string body;
699 GenerateBody(&body, 1024 * 10);
701 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
702 request.AddBody(body, true);
704 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
707 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
708 ASSERT_TRUE(Initialize());
710 client_->client()->WaitForCryptoHandshakeConfirmed();
711 // Both of these must be called when the writer is not actively used.
712 SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
713 SetReorderPercentage(30);
715 // 1 MB body.
716 string body;
717 GenerateBody(&body, 1024 * 1024);
719 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
720 request.AddBody(body, true);
722 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
725 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
726 // Have the server accept 0-RTT without waiting a startup period.
727 strike_register_no_startup_period_ = true;
729 // Send a request and then disconnect. This prepares the client to attempt
730 // a 0-RTT handshake for the next request.
731 ASSERT_TRUE(Initialize());
733 string body;
734 GenerateBody(&body, 20480);
736 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
737 request.AddBody(body, true);
739 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
740 // In the non-stateless case, the same session is used for both
741 // hellos, so the number of hellos sent on that session is 2. In
742 // the stateless case, the first client session will be completely
743 // torn down after the reject. The number of hellos on the latest
744 // session is 1.
745 const int expected_num_hellos_latest_session =
746 BothSidesSupportStatelessRejects() ? 1 : 2;
747 EXPECT_EQ(expected_num_hellos_latest_session,
748 client_->client()->session()->GetNumSentClientHellos());
749 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
751 client_->Disconnect();
753 // The 0-RTT handshake should succeed.
754 client_->Connect();
755 client_->WaitForResponseForMs(-1);
756 ASSERT_TRUE(client_->client()->connected());
757 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
758 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
759 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
761 client_->Disconnect();
763 // Restart the server so that the 0-RTT handshake will take 1 RTT.
764 StopServer();
765 server_writer_ = new PacketDroppingTestWriter();
766 StartServer();
768 client_->Connect();
769 ASSERT_TRUE(client_->client()->connected());
770 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
771 // In the non-stateless case, the same session is used for both
772 // hellos, so the number of hellos sent on that session is 2. In
773 // the stateless case, the first client session will be completely
774 // torn down after the reject. The number of hellos sent on the
775 // latest session is 1.
776 EXPECT_EQ(expected_num_hellos_latest_session,
777 client_->client()->session()->GetNumSentClientHellos());
778 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
780 VerifyCleanConnection(false);
783 TEST_P(EndToEndTest, SynchronousRequestZeroRTTFailure) {
784 // Have the server accept 0-RTT without waiting a startup period.
785 strike_register_no_startup_period_ = true;
787 // Send a request and then disconnect. This prepares the client to attempt
788 // a 0-RTT handshake for the next request.
789 ASSERT_TRUE(Initialize());
791 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
792 // In the non-stateless case, the same session is used for both
793 // hellos, so the number of hellos sent on that session is 2. In
794 // the stateless case, the first client session will be completely
795 // torn down after the reject. The number of hellos on that second
796 // latest session is 1.
797 const int expected_num_hellos_latest_session =
798 BothSidesSupportStatelessRejects() ? 1 : 2;
799 EXPECT_EQ(expected_num_hellos_latest_session,
800 client_->client()->session()->GetNumSentClientHellos());
801 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
803 client_->Disconnect();
805 // The 0-RTT handshake should succeed.
806 client_->Connect();
807 client_->WaitForInitialResponse();
808 ASSERT_TRUE(client_->client()->connected());
809 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
810 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
811 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
813 client_->Disconnect();
815 // Restart the server so that the 0-RTT handshake will take 1 RTT.
816 StopServer();
817 server_writer_ = new PacketDroppingTestWriter();
818 StartServer();
820 client_->Connect();
821 ASSERT_TRUE(client_->client()->connected());
822 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
823 // In the non-stateless case, the same session is used for both
824 // hellos, so the number of hellos sent on that session is 2. In
825 // the stateless case, the first client session will be completely
826 // torn down after the reject. The number of hellos sent on the
827 // latest session is 1.
828 EXPECT_EQ(expected_num_hellos_latest_session,
829 client_->client()->session()->GetNumSentClientHellos());
830 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
832 VerifyCleanConnection(false);
835 TEST_P(EndToEndTest, LargePostSynchronousRequest) {
836 // Have the server accept 0-RTT without waiting a startup period.
837 strike_register_no_startup_period_ = true;
839 // Send a request and then disconnect. This prepares the client to attempt
840 // a 0-RTT handshake for the next request.
841 ASSERT_TRUE(Initialize());
843 string body;
844 GenerateBody(&body, 20480);
846 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
847 request.AddBody(body, true);
849 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
850 // In the non-stateless case, the same session is used for both
851 // hellos, so the number of hellos sent on that session is 2. In
852 // the stateless case, the first client session will be completely
853 // torn down after the reject. The number of hellos on the latest
854 // session is 1.
855 const int expected_num_hellos_latest_session =
856 BothSidesSupportStatelessRejects() ? 1 : 2;
857 EXPECT_EQ(expected_num_hellos_latest_session,
858 client_->client()->session()->GetNumSentClientHellos());
859 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
861 client_->Disconnect();
863 // The 0-RTT handshake should succeed.
864 client_->Connect();
865 client_->WaitForInitialResponse();
866 ASSERT_TRUE(client_->client()->connected());
867 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
868 EXPECT_EQ(1, client_->client()->session()->GetNumSentClientHellos());
869 EXPECT_EQ(1, client_->client()->GetNumSentClientHellos());
871 client_->Disconnect();
873 // Restart the server so that the 0-RTT handshake will take 1 RTT.
874 StopServer();
875 server_writer_ = new PacketDroppingTestWriter();
876 StartServer();
878 client_->Connect();
879 ASSERT_TRUE(client_->client()->connected());
880 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
881 // In the non-stateless case, the same session is used for both
882 // hellos, so the number of hellos sent on that session is 2. In
883 // the stateless case, the first client session will be completely
884 // torn down after the reject. The number of hellos sent on the
885 // latest session is 1.
886 EXPECT_EQ(expected_num_hellos_latest_session,
887 client_->client()->session()->GetNumSentClientHellos());
888 EXPECT_EQ(2, client_->client()->GetNumSentClientHellos());
890 VerifyCleanConnection(false);
893 TEST_P(EndToEndTest, StatelessRejectWithPacketLoss) {
894 // In this test, we intentionally drop the first packet from the
895 // server, which corresponds with the initial REJ/SREJ response from
896 // the server. The REJ case will succeed, due to redundancy in the
897 // stateful handshake. The SREJ will fail, because there is
898 // (currently) no way to recover from a loss of the first SREJ, and
899 // all remaining state for the first handshake is black-holed on the
900 // time-wait list.
901 // TODO(jokulik): Once redundant SREJ support is added, this test
902 // should succeed.
903 server_writer_->set_fake_drop_first_n_packets(1);
904 ASSERT_EQ(!BothSidesSupportStatelessRejects(), Initialize());
907 TEST_P(EndToEndTest, SetInitialReceivedConnectionOptions) {
908 QuicTagVector initial_received_options;
909 initial_received_options.push_back(kTBBR);
910 initial_received_options.push_back(kIW10);
911 initial_received_options.push_back(kPRST);
912 EXPECT_TRUE(server_config_.SetInitialReceivedConnectionOptions(
913 initial_received_options));
915 ASSERT_TRUE(Initialize());
916 client_->client()->WaitForCryptoHandshakeConfirmed();
917 server_thread_->WaitForCryptoHandshakeConfirmed();
919 EXPECT_FALSE(server_config_.SetInitialReceivedConnectionOptions(
920 initial_received_options));
922 // Verify that server's configuration is correct.
923 server_thread_->Pause();
924 EXPECT_TRUE(server_config_.HasReceivedConnectionOptions());
925 EXPECT_TRUE(
926 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kTBBR));
927 EXPECT_TRUE(
928 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kIW10));
929 EXPECT_TRUE(
930 ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kPRST));
933 TEST_P(EndToEndTest, CorrectlyConfiguredFec) {
934 ASSERT_TRUE(Initialize());
935 client_->client()->WaitForCryptoHandshakeConfirmed();
936 server_thread_->WaitForCryptoHandshakeConfirmed();
938 FecPolicy expected_policy =
939 GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL;
941 // Verify that server's FEC configuration is correct.
942 server_thread_->Pause();
943 QuicDispatcher* dispatcher =
944 QuicServerPeer::GetDispatcher(server_thread_->server());
945 ASSERT_EQ(1u, dispatcher->session_map().size());
946 QuicSpdySession* session = dispatcher->session_map().begin()->second;
947 EXPECT_EQ(expected_policy,
948 QuicSpdySessionPeer::GetHeadersStream(session)->fec_policy());
949 server_thread_->Resume();
951 // Verify that client's FEC configuration is correct.
952 EXPECT_EQ(expected_policy, QuicSpdySessionPeer::GetHeadersStream(
953 client_->client()->session())->fec_policy());
954 EXPECT_EQ(expected_policy,
955 client_->GetOrCreateStream()->fec_policy());
958 TEST_P(EndToEndTest, LargePostSmallBandwidthLargeBuffer) {
959 ASSERT_TRUE(Initialize());
960 SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
961 // 256KB per second with a 256KB buffer from server to client. Wireless
962 // clients commonly have larger buffers, but our max CWND is 200.
963 server_writer_->set_max_bandwidth_and_buffer_size(
964 QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
966 client_->client()->WaitForCryptoHandshakeConfirmed();
968 // 1 MB body.
969 string body;
970 GenerateBody(&body, 1024 * 1024);
972 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
973 request.AddBody(body, true);
975 EXPECT_EQ(kFooResponseBody, client_->SendCustomSynchronousRequest(request));
976 // This connection will not drop packets, because the buffer size is larger
977 // than the default receive window.
978 VerifyCleanConnection(false);
981 TEST_P(EndToEndTest, DoNotSetResumeWriteAlarmIfConnectionFlowControlBlocked) {
982 // Regression test for b/14677858.
983 // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
984 // if currently connection level flow control blocked. If set, this results in
985 // an infinite loop in the EpollServer, as the alarm fires and is immediately
986 // rescheduled.
987 ASSERT_TRUE(Initialize());
988 client_->client()->WaitForCryptoHandshakeConfirmed();
990 // Ensure both stream and connection level are flow control blocked by setting
991 // the send window offset to 0.
992 const uint64 flow_control_window =
993 server_config_.GetInitialStreamFlowControlWindowToSend();
994 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
995 QuicSession* session = client_->client()->session();
996 QuicFlowControllerPeer::SetSendWindowOffset(stream->flow_controller(), 0);
997 QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
998 EXPECT_TRUE(stream->flow_controller()->IsBlocked());
999 EXPECT_TRUE(session->flow_controller()->IsBlocked());
1001 // Make sure that the stream has data pending so that it will be marked as
1002 // write blocked when it receives a stream level WINDOW_UPDATE.
1003 stream->SendBody("hello", false);
1005 // The stream now attempts to write, fails because it is still connection
1006 // level flow control blocked, and is added to the write blocked list.
1007 QuicWindowUpdateFrame window_update(stream->id(), 2 * flow_control_window);
1008 stream->OnWindowUpdateFrame(window_update);
1010 // Prior to fixing b/14677858 this call would result in an infinite loop in
1011 // Chromium. As a proxy for detecting this, we now check whether the
1012 // resume_writes_alarm is set after OnCanWrite. It should not be, as the
1013 // connection is still flow control blocked.
1014 session->connection()->OnCanWrite();
1016 QuicAlarm* resume_writes_alarm =
1017 QuicConnectionPeer::GetResumeWritesAlarm(session->connection());
1018 EXPECT_FALSE(resume_writes_alarm->IsSet());
1021 TEST_P(EndToEndTest, InvalidStream) {
1022 ASSERT_TRUE(Initialize());
1023 client_->client()->WaitForCryptoHandshakeConfirmed();
1025 string body;
1026 GenerateBody(&body, kMaxPacketSize);
1028 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1029 request.AddBody(body, true);
1030 // Force the client to write with a stream ID belonging to a nonexistent
1031 // server-side stream.
1032 QuicSessionPeer::SetNextStreamId(client_->client()->session(), 2);
1034 client_->SendCustomSynchronousRequest(request);
1035 // EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1036 EXPECT_EQ(QUIC_PACKET_FOR_NONEXISTENT_STREAM, client_->connection_error());
1039 // TODO(rch): this test seems to cause net_unittests timeouts :|
1040 TEST_P(EndToEndTest, DISABLED_MultipleTermination) {
1041 ASSERT_TRUE(Initialize());
1043 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1044 request.AddHeader("content-length", "3");
1045 request.set_has_complete_message(false);
1047 // Set the offset so we won't frame. Otherwise when we pick up termination
1048 // before HTTP framing is complete, we send an error and close the stream,
1049 // and the second write is picked up as writing on a closed stream.
1050 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1051 ASSERT_TRUE(stream != nullptr);
1052 ReliableQuicStreamPeer::SetStreamBytesWritten(3, stream);
1054 client_->SendData("bar", true);
1055 client_->WaitForWriteToFlush();
1057 // By default the stream protects itself from writes after terminte is set.
1058 // Override this to test the server handling buggy clients.
1059 ReliableQuicStreamPeer::SetWriteSideClosed(
1060 false, client_->GetOrCreateStream());
1062 EXPECT_DFATAL(client_->SendData("eep", true), "Fin already buffered");
1065 TEST_P(EndToEndTest, Timeout) {
1066 client_config_.SetIdleConnectionStateLifetime(
1067 QuicTime::Delta::FromMicroseconds(500),
1068 QuicTime::Delta::FromMicroseconds(500));
1069 // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
1070 // that's enough to validate timeout in this case.
1071 Initialize();
1072 while (client_->client()->connected()) {
1073 client_->client()->WaitForEvents();
1077 TEST_P(EndToEndTest, NegotiateMaxOpenStreams) {
1078 // Negotiate 1 max open stream.
1079 client_config_.SetMaxStreamsPerConnection(1, 1);
1080 ASSERT_TRUE(Initialize());
1081 client_->client()->WaitForCryptoHandshakeConfirmed();
1083 // Make the client misbehave after negotiation.
1084 const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
1085 QuicSessionPeer::SetMaxOpenStreams(client_->client()->session(),
1086 kServerMaxStreams + 1);
1088 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1089 request.AddHeader("content-length", "3");
1090 request.set_has_complete_message(false);
1092 // The server supports a small number of additional streams beyond the
1093 // negotiated limit. Open enough streams to go beyond that limit.
1094 for (int i = 0; i < kServerMaxStreams + 1; ++i) {
1095 client_->SendMessage(request);
1097 client_->WaitForResponse();
1099 EXPECT_FALSE(client_->connected());
1100 EXPECT_EQ(QUIC_STREAM_CONNECTION_ERROR, client_->stream_error());
1101 EXPECT_EQ(QUIC_TOO_MANY_OPEN_STREAMS, client_->connection_error());
1104 TEST_P(EndToEndTest, NegotiateCongestionControl) {
1105 ValueRestore<bool> old_flag(&FLAGS_quic_allow_bbr, true);
1106 ASSERT_TRUE(Initialize());
1107 client_->client()->WaitForCryptoHandshakeConfirmed();
1109 CongestionControlType expected_congestion_control_type = kReno;
1110 switch (GetParam().congestion_control_tag) {
1111 case kRENO:
1112 expected_congestion_control_type = kReno;
1113 break;
1114 case kTBBR:
1115 expected_congestion_control_type = kBBR;
1116 break;
1117 case kQBIC:
1118 expected_congestion_control_type = kCubic;
1119 break;
1120 default:
1121 DLOG(FATAL) << "Unexpected congestion control tag";
1124 EXPECT_EQ(expected_congestion_control_type,
1125 QuicSentPacketManagerPeer::GetSendAlgorithm(
1126 *GetSentPacketManagerFromFirstServerSession())
1127 ->GetCongestionControlType());
1130 TEST_P(EndToEndTest, LimitMaxOpenStreams) {
1131 // Server limits the number of max streams to 2.
1132 server_config_.SetMaxStreamsPerConnection(2, 2);
1133 // Client tries to negotiate for 10.
1134 client_config_.SetMaxStreamsPerConnection(10, 5);
1136 ASSERT_TRUE(Initialize());
1137 client_->client()->WaitForCryptoHandshakeConfirmed();
1138 QuicConfig* client_negotiated_config = client_->client()->session()->config();
1139 EXPECT_EQ(2u, client_negotiated_config->MaxStreamsPerConnection());
1142 TEST_P(EndToEndTest, ClientSuggestsRTT) {
1143 // Client suggests initial RTT, verify it is used.
1144 const uint32 kInitialRTT = 20000;
1145 client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT);
1147 ASSERT_TRUE(Initialize());
1148 client_->client()->WaitForCryptoHandshakeConfirmed();
1149 server_thread_->WaitForCryptoHandshakeConfirmed();
1151 // Pause the server so we can access the server's internals without races.
1152 server_thread_->Pause();
1153 QuicDispatcher* dispatcher =
1154 QuicServerPeer::GetDispatcher(server_thread_->server());
1155 ASSERT_EQ(1u, dispatcher->session_map().size());
1156 const QuicSentPacketManager& client_sent_packet_manager =
1157 client_->client()->session()->connection()->sent_packet_manager();
1158 const QuicSentPacketManager& server_sent_packet_manager =
1159 *GetSentPacketManagerFromFirstServerSession();
1161 EXPECT_EQ(kInitialRTT,
1162 client_sent_packet_manager.GetRttStats()->initial_rtt_us());
1163 EXPECT_EQ(kInitialRTT,
1164 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1165 server_thread_->Resume();
1168 TEST_P(EndToEndTest, MaxInitialRTT) {
1169 // Client tries to suggest twice the server's max initial rtt and the server
1170 // uses the max.
1171 client_config_.SetInitialRoundTripTimeUsToSend(
1172 2 * kMaxInitialRoundTripTimeUs);
1174 ASSERT_TRUE(Initialize());
1175 client_->client()->WaitForCryptoHandshakeConfirmed();
1176 server_thread_->WaitForCryptoHandshakeConfirmed();
1178 // Pause the server so we can access the server's internals without races.
1179 server_thread_->Pause();
1180 QuicDispatcher* dispatcher =
1181 QuicServerPeer::GetDispatcher(server_thread_->server());
1182 ASSERT_EQ(1u, dispatcher->session_map().size());
1183 QuicSession* session = dispatcher->session_map().begin()->second;
1184 const QuicSentPacketManager& client_sent_packet_manager =
1185 client_->client()->session()->connection()->sent_packet_manager();
1187 // Now that acks have been exchanged, the RTT estimate has decreased on the
1188 // server and is not infinite on the client.
1189 EXPECT_FALSE(
1190 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
1191 const RttStats& server_rtt_stats =
1192 *session->connection()->sent_packet_manager().GetRttStats();
1193 EXPECT_EQ(static_cast<int64>(kMaxInitialRoundTripTimeUs),
1194 server_rtt_stats.initial_rtt_us());
1195 EXPECT_GE(static_cast<int64>(kMaxInitialRoundTripTimeUs),
1196 server_rtt_stats.smoothed_rtt().ToMicroseconds());
1197 server_thread_->Resume();
1200 TEST_P(EndToEndTest, MinInitialRTT) {
1201 // Client tries to suggest 0 and the server uses the default.
1202 client_config_.SetInitialRoundTripTimeUsToSend(0);
1204 ASSERT_TRUE(Initialize());
1205 client_->client()->WaitForCryptoHandshakeConfirmed();
1206 server_thread_->WaitForCryptoHandshakeConfirmed();
1208 // Pause the server so we can access the server's internals without races.
1209 server_thread_->Pause();
1210 QuicDispatcher* dispatcher =
1211 QuicServerPeer::GetDispatcher(server_thread_->server());
1212 ASSERT_EQ(1u, dispatcher->session_map().size());
1213 QuicSession* session = dispatcher->session_map().begin()->second;
1214 const QuicSentPacketManager& client_sent_packet_manager =
1215 client_->client()->session()->connection()->sent_packet_manager();
1216 const QuicSentPacketManager& server_sent_packet_manager =
1217 session->connection()->sent_packet_manager();
1219 // Now that acks have been exchanged, the RTT estimate has decreased on the
1220 // server and is not infinite on the client.
1221 EXPECT_FALSE(
1222 client_sent_packet_manager.GetRttStats()->smoothed_rtt().IsInfinite());
1223 // Expect the default rtt of 100ms.
1224 EXPECT_EQ(static_cast<int64>(100 * kNumMicrosPerMilli),
1225 server_sent_packet_manager.GetRttStats()->initial_rtt_us());
1226 // Ensure the bandwidth is valid.
1227 client_sent_packet_manager.BandwidthEstimate();
1228 server_sent_packet_manager.BandwidthEstimate();
1229 server_thread_->Resume();
1232 TEST_P(EndToEndTest, 0ByteConnectionId) {
1233 client_config_.SetBytesForConnectionIdToSend(0);
1234 ASSERT_TRUE(Initialize());
1236 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1237 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1239 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1240 client_->client()->session()->connection());
1241 EXPECT_EQ(PACKET_0BYTE_CONNECTION_ID,
1242 header->public_header.connection_id_length);
1245 TEST_P(EndToEndTest, 1ByteConnectionId) {
1246 client_config_.SetBytesForConnectionIdToSend(1);
1247 ASSERT_TRUE(Initialize());
1249 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1250 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1251 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1252 client_->client()->session()->connection());
1253 EXPECT_EQ(PACKET_1BYTE_CONNECTION_ID,
1254 header->public_header.connection_id_length);
1257 TEST_P(EndToEndTest, 4ByteConnectionId) {
1258 client_config_.SetBytesForConnectionIdToSend(4);
1259 ASSERT_TRUE(Initialize());
1261 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1262 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1263 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1264 client_->client()->session()->connection());
1265 EXPECT_EQ(PACKET_4BYTE_CONNECTION_ID,
1266 header->public_header.connection_id_length);
1269 TEST_P(EndToEndTest, 8ByteConnectionId) {
1270 client_config_.SetBytesForConnectionIdToSend(8);
1271 ASSERT_TRUE(Initialize());
1273 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1274 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1275 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1276 client_->client()->session()->connection());
1277 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1278 header->public_header.connection_id_length);
1281 TEST_P(EndToEndTest, 15ByteConnectionId) {
1282 client_config_.SetBytesForConnectionIdToSend(15);
1283 ASSERT_TRUE(Initialize());
1285 // Our server is permissive and allows for out of bounds values.
1286 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1287 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1288 QuicPacketHeader* header = QuicConnectionPeer::GetLastHeader(
1289 client_->client()->session()->connection());
1290 EXPECT_EQ(PACKET_8BYTE_CONNECTION_ID,
1291 header->public_header.connection_id_length);
1294 TEST_P(EndToEndTest, ResetConnection) {
1295 ASSERT_TRUE(Initialize());
1296 client_->client()->WaitForCryptoHandshakeConfirmed();
1298 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1299 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1300 client_->ResetConnection();
1301 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1302 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1305 TEST_P(EndToEndTest, MaxStreamsUberTest) {
1306 if (!BothSidesSupportStatelessRejects()) {
1307 // Connect with lower fake packet loss than we'd like to test. Until
1308 // b/10126687 is fixed, losing handshake packets is pretty brutal.
1309 // TODO(jokulik): Until we support redundant SREJ packets, don't
1310 // drop handshake packets for stateless rejects.
1311 SetPacketLossPercentage(1);
1313 ASSERT_TRUE(Initialize());
1314 string large_body;
1315 GenerateBody(&large_body, 10240);
1316 int max_streams = 100;
1318 AddToCache("/large_response", 200, "OK", large_body);;
1320 client_->client()->WaitForCryptoHandshakeConfirmed();
1321 SetPacketLossPercentage(10);
1323 for (int i = 0; i < max_streams; ++i) {
1324 EXPECT_LT(0, client_->SendRequest("/large_response"));
1327 // WaitForEvents waits 50ms and returns true if there are outstanding
1328 // requests.
1329 while (client_->client()->WaitForEvents() == true) {
1333 TEST_P(EndToEndTest, StreamCancelErrorTest) {
1334 ASSERT_TRUE(Initialize());
1335 string small_body;
1336 GenerateBody(&small_body, 256);
1338 AddToCache("/small_response", 200, "OK", small_body);
1340 client_->client()->WaitForCryptoHandshakeConfirmed();
1342 QuicSession* session = client_->client()->session();
1343 // Lose the request.
1344 SetPacketLossPercentage(100);
1345 EXPECT_LT(0, client_->SendRequest("/small_response"));
1346 client_->client()->WaitForEvents();
1347 // Transmit the cancel, and ensure the connection is torn down properly.
1348 SetPacketLossPercentage(0);
1349 QuicStreamId stream_id = kClientDataStreamId1;
1350 session->SendRstStream(stream_id, QUIC_STREAM_CANCELLED, 0);
1352 // WaitForEvents waits 50ms and returns true if there are outstanding
1353 // requests.
1354 while (client_->client()->WaitForEvents() == true) {
1356 // It should be completely fine to RST a stream before any data has been
1357 // received for that stream.
1358 EXPECT_EQ(QUIC_NO_ERROR, client_->connection_error());
1361 class WrongAddressWriter : public QuicPacketWriterWrapper {
1362 public:
1363 WrongAddressWriter() {
1364 IPAddressNumber ip;
1365 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &ip));
1366 self_address_ = IPEndPoint(ip, 0);
1369 WriteResult WritePacket(const char* buffer,
1370 size_t buf_len,
1371 const IPAddressNumber& real_self_address,
1372 const IPEndPoint& peer_address) override {
1373 // Use wrong address!
1374 return QuicPacketWriterWrapper::WritePacket(
1375 buffer, buf_len, self_address_.address(), peer_address);
1378 bool IsWriteBlockedDataBuffered() const override { return false; }
1380 IPEndPoint self_address_;
1383 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
1384 ASSERT_TRUE(Initialize());
1386 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1387 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1389 // Store the client IP address which was used to send the first request.
1390 IPAddressNumber old_host = client_->client()->client_address().address();
1392 // Migrate socket to the new IP address.
1393 IPAddressNumber new_host;
1394 CHECK(net::ParseIPLiteralToNumber("127.0.0.2", &new_host));
1395 EXPECT_NE(old_host, new_host);
1396 ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
1398 // Send a request using the new socket.
1399 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1400 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1403 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
1404 // Tests that the client's port can change during an established QUIC
1405 // connection, and that doing so does not result in the connection being
1406 // closed by the server.
1407 ASSERT_TRUE(Initialize());
1409 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1410 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1412 // Store the client address which was used to send the first request.
1413 IPEndPoint old_address = client_->client()->client_address();
1415 // Stop listening on the old FD.
1416 EpollServer* eps = client_->epoll_server();
1417 int old_fd = client_->client()->fd();
1418 eps->UnregisterFD(old_fd);
1419 // Create a new socket before closing the old one, which will result in a new
1420 // ephemeral port.
1421 QuicClientPeer::CreateUDPSocket(client_->client());
1422 close(old_fd);
1424 // The packet writer needs to be updated to use the new FD.
1425 client_->client()->CreateQuicPacketWriter();
1427 // Change the internal state of the client and connection to use the new port,
1428 // this is done because in a real NAT rebinding the client wouldn't see any
1429 // port change, and so expects no change to incoming port.
1430 // This is kind of ugly, but needed as we are simply swapping out the client
1431 // FD rather than any more complex NAT rebinding simulation.
1432 int new_port = client_->client()->client_address().port();
1433 QuicClientPeer::SetClientPort(client_->client(), new_port);
1434 QuicConnectionPeer::SetSelfAddress(
1435 client_->client()->session()->connection(),
1436 IPEndPoint(
1437 client_->client()->session()->connection()->self_address().address(),
1438 new_port));
1440 // Register the new FD for epoll events.
1441 int new_fd = client_->client()->fd();
1442 eps->RegisterFD(new_fd, client_->client(), EPOLLIN | EPOLLOUT | EPOLLET);
1444 // Send a second request, using the new FD.
1445 EXPECT_EQ(kBarResponseBody, client_->SendSynchronousRequest("/bar"));
1446 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1448 // Verify that the client's ephemeral port is different.
1449 IPEndPoint new_address = client_->client()->client_address();
1450 EXPECT_EQ(old_address.address(), new_address.address());
1451 EXPECT_NE(old_address.port(), new_address.port());
1454 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
1455 // Client and server can set different initial flow control receive windows.
1456 // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
1457 // in the crypto handshake.
1458 const uint32 kClientStreamIFCW = 123456;
1459 const uint32 kClientSessionIFCW = 234567;
1460 set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
1461 set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
1463 uint32 kServerStreamIFCW =
1464 GetParam().auto_tune_flow_control_window ? 32 * 1024 : 654321;
1465 uint32 kServerSessionIFCW =
1466 GetParam().auto_tune_flow_control_window ? 48 * 1024 : 765432;
1467 set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
1468 set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
1470 ASSERT_TRUE(Initialize());
1472 // Values are exchanged during crypto handshake, so wait for that to finish.
1473 client_->client()->WaitForCryptoHandshakeConfirmed();
1474 server_thread_->WaitForCryptoHandshakeConfirmed();
1476 // Open a data stream to make sure the stream level flow control is updated.
1477 QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1478 stream->SendBody("hello", false);
1480 // Client should have the right values for server's receive window.
1481 EXPECT_EQ(kServerStreamIFCW,
1482 client_->client()
1483 ->session()
1484 ->config()
1485 ->ReceivedInitialStreamFlowControlWindowBytes());
1486 EXPECT_EQ(kServerSessionIFCW,
1487 client_->client()
1488 ->session()
1489 ->config()
1490 ->ReceivedInitialSessionFlowControlWindowBytes());
1491 EXPECT_EQ(kServerStreamIFCW, QuicFlowControllerPeer::SendWindowOffset(
1492 stream->flow_controller()));
1493 EXPECT_EQ(kServerSessionIFCW,
1494 QuicFlowControllerPeer::SendWindowOffset(
1495 client_->client()->session()->flow_controller()));
1497 // Server should have the right values for client's receive window.
1498 server_thread_->Pause();
1499 QuicDispatcher* dispatcher =
1500 QuicServerPeer::GetDispatcher(server_thread_->server());
1501 QuicSession* session = dispatcher->session_map().begin()->second;
1502 EXPECT_EQ(kClientStreamIFCW,
1503 session->config()->ReceivedInitialStreamFlowControlWindowBytes());
1504 EXPECT_EQ(kClientSessionIFCW,
1505 session->config()->ReceivedInitialSessionFlowControlWindowBytes());
1506 EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
1507 session->flow_controller()));
1508 server_thread_->Resume();
1511 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
1512 // The special headers and crypto streams should be subject to per-stream flow
1513 // control limits, but should not be subject to connection level flow control.
1514 const uint32 kStreamIFCW =
1515 GetParam().auto_tune_flow_control_window ? 32 * 1024 : 123456;
1516 const uint32 kSessionIFCW =
1517 GetParam().auto_tune_flow_control_window ? 48 * 1024 : 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, FlowControlsSynced) {
1565 const uint32 kClientIFCW = 64 * 1024;
1566 const uint32 kServerIFCW = 1024 * 1024;
1567 const float kSessionToStreamRatio = 1.5;
1568 set_client_initial_stream_flow_control_receive_window(kClientIFCW);
1569 set_client_initial_session_flow_control_receive_window(kSessionToStreamRatio *
1570 kClientIFCW);
1571 set_server_initial_stream_flow_control_receive_window(kServerIFCW);
1572 set_server_initial_session_flow_control_receive_window(kSessionToStreamRatio *
1573 kServerIFCW);
1575 ASSERT_TRUE(Initialize());
1577 client_->client()->WaitForCryptoHandshakeConfirmed();
1578 server_thread_->WaitForCryptoHandshakeConfirmed();
1580 server_thread_->Pause();
1581 QuicSpdySession* const client_session = client_->client()->session();
1582 QuicDispatcher* dispatcher =
1583 QuicServerPeer::GetDispatcher(server_thread_->server());
1584 QuicSpdySession* server_session = dispatcher->session_map().begin()->second;
1586 ExpectFlowControlsSynced(client_session->flow_controller(),
1587 server_session->flow_controller());
1588 ExpectFlowControlsSynced(
1589 QuicSessionPeer::GetCryptoStream(client_session)->flow_controller(),
1590 QuicSessionPeer::GetCryptoStream(server_session)->flow_controller());
1591 ExpectFlowControlsSynced(
1592 QuicSpdySessionPeer::GetHeadersStream(client_session)->flow_controller(),
1593 QuicSpdySessionPeer::GetHeadersStream(server_session)->flow_controller());
1595 EXPECT_EQ(static_cast<float>(QuicFlowControllerPeer::ReceiveWindowSize(
1596 client_session->flow_controller())) /
1597 QuicFlowControllerPeer::ReceiveWindowSize(
1598 QuicSpdySessionPeer::GetHeadersStream(client_session)
1599 ->flow_controller()),
1600 kSessionToStreamRatio);
1602 server_thread_->Resume();
1605 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
1606 // A stream created on receipt of a simple request with no body will never get
1607 // a stream frame with a FIN. Verify that we don't keep track of the stream in
1608 // the locally closed streams map: it will never be removed if so.
1609 ASSERT_TRUE(Initialize());
1611 // Send a simple headers only request, and receive response.
1612 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1613 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1615 // Now verify that the server is not waiting for a final FIN or RST.
1616 server_thread_->Pause();
1617 QuicDispatcher* dispatcher =
1618 QuicServerPeer::GetDispatcher(server_thread_->server());
1619 QuicSession* session = dispatcher->session_map().begin()->second;
1620 EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
1621 session).size());
1622 server_thread_->Resume();
1625 // A TestAckNotifierDelegate verifies that its OnAckNotification method has been
1626 // called exactly once on destruction.
1627 class TestAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
1628 public:
1629 TestAckNotifierDelegate() {}
1631 void OnAckNotification(int /*num_retransmitted_packets*/,
1632 int /*num_retransmitted_bytes*/,
1633 QuicTime::Delta /*delta_largest_observed*/) override {
1634 ASSERT_FALSE(has_been_notified_);
1635 has_been_notified_ = true;
1638 bool has_been_notified() const { return has_been_notified_; }
1640 protected:
1641 // Object is ref counted.
1642 ~TestAckNotifierDelegate() override { EXPECT_TRUE(has_been_notified_); }
1644 private:
1645 bool has_been_notified_ = false;
1648 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
1649 // Verify that even in the presence of packet loss and occasionally blocked
1650 // socket, an AckNotifierDelegate will get informed that the data it is
1651 // interested in has been ACKed. This tests end-to-end ACK notification, and
1652 // demonstrates that retransmissions do not break this functionality.
1653 if (!BothSidesSupportStatelessRejects()) {
1654 // TODO(jokulik): Until we support redundant SREJ packets, don't
1655 // drop handshake packets for stateless rejects.
1656 SetPacketLossPercentage(5);
1658 ASSERT_TRUE(Initialize());
1660 // Wait for the server SHLO before upping the packet loss.
1661 client_->client()->WaitForCryptoHandshakeConfirmed();
1662 SetPacketLossPercentage(30);
1663 client_writer_->set_fake_blocked_socket_percentage(10);
1665 // Create a POST request and send the headers only.
1666 HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo");
1667 request.set_has_complete_message(false);
1668 client_->SendMessage(request);
1670 // The TestAckNotifierDelegate will cause a failure if not notified.
1671 scoped_refptr<TestAckNotifierDelegate> delegate(new TestAckNotifierDelegate);
1673 // Test the AckNotifier's ability to track multiple packets by making the
1674 // request body exceed the size of a single packet.
1675 string request_string =
1676 "a request body bigger than one packet" + string(kMaxPacketSize, '.');
1678 // Send the request, and register the delegate for ACKs.
1679 client_->SendData(request_string, true, delegate.get());
1680 client_->WaitForResponse();
1681 EXPECT_EQ(kFooResponseBody, client_->response_body());
1682 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1684 // Send another request to flush out any pending ACKs on the server.
1685 client_->SendSynchronousRequest(request_string);
1687 // Pause the server to avoid races.
1688 server_thread_->Pause();
1689 // Make sure the delegate does get the notification it expects.
1690 while (!delegate->has_been_notified()) {
1691 // Waits for up to 50 ms.
1692 client_->client()->WaitForEvents();
1694 server_thread_->Resume();
1697 // Send a public reset from the server for a different connection ID.
1698 // It should be ignored.
1699 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
1700 ASSERT_TRUE(Initialize());
1702 // Send the public reset.
1703 QuicConnectionId incorrect_connection_id =
1704 client_->client()->session()->connection()->connection_id() + 1;
1705 QuicPublicResetPacket header;
1706 header.public_header.connection_id = incorrect_connection_id;
1707 header.public_header.reset_flag = true;
1708 header.public_header.version_flag = false;
1709 header.rejected_packet_number = 10101;
1710 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1711 Perspective::IS_SERVER);
1712 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1713 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1714 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1715 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1716 .Times(1);
1717 // We must pause the server's thread in order to call WritePacket without
1718 // race conditions.
1719 server_thread_->Pause();
1720 server_writer_->WritePacket(packet->data(), packet->length(),
1721 server_address_.address(),
1722 client_->client()->client_address());
1723 server_thread_->Resume();
1725 // The connection should be unaffected.
1726 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1727 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1729 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1732 // Send a public reset from the client for a different connection ID.
1733 // It should be ignored.
1734 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
1735 ASSERT_TRUE(Initialize());
1737 // Send the public reset.
1738 QuicConnectionId incorrect_connection_id =
1739 client_->client()->session()->connection()->connection_id() + 1;
1740 QuicPublicResetPacket header;
1741 header.public_header.connection_id = incorrect_connection_id;
1742 header.public_header.reset_flag = true;
1743 header.public_header.version_flag = false;
1744 header.rejected_packet_number = 10101;
1745 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1746 Perspective::IS_CLIENT);
1747 scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header));
1748 client_writer_->WritePacket(packet->data(), packet->length(),
1749 client_->client()->client_address().address(),
1750 server_address_);
1752 // The connection should be unaffected.
1753 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1754 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1757 // Send a version negotiation packet from the server for a different
1758 // connection ID. It should be ignored.
1759 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
1760 ASSERT_TRUE(Initialize());
1762 // Send the version negotiation packet.
1763 QuicConnectionId incorrect_connection_id =
1764 client_->client()->session()->connection()->connection_id() + 1;
1765 QuicVersionNegotiationPacket header;
1766 header.connection_id = incorrect_connection_id;
1767 header.reset_flag = true;
1768 header.version_flag = true;
1769 QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
1770 Perspective::IS_SERVER);
1771 scoped_ptr<QuicEncryptedPacket> packet(
1772 framer.BuildVersionNegotiationPacket(header, server_supported_versions_));
1773 testing::NiceMock<MockQuicConnectionDebugVisitor> visitor;
1774 client_->client()->session()->connection()->set_debug_visitor(&visitor);
1775 EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
1776 .Times(1);
1777 // We must pause the server's thread in order to call WritePacket without
1778 // race conditions.
1779 server_thread_->Pause();
1780 server_writer_->WritePacket(packet->data(), packet->length(),
1781 server_address_.address(),
1782 client_->client()->client_address());
1783 server_thread_->Resume();
1785 // The connection should be unaffected.
1786 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1787 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1789 client_->client()->session()->connection()->set_debug_visitor(nullptr);
1792 // A bad header shouldn't tear down the connection, because the receiver can't
1793 // tell the connection ID.
1794 TEST_P(EndToEndTest, BadPacketHeaderTruncated) {
1795 ASSERT_TRUE(Initialize());
1797 // Start the connection.
1798 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1799 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1801 // Packet with invalid public flags.
1802 char packet[] = {// public flags (8 byte connection_id)
1803 0x3C,
1804 // truncated connection ID
1805 0x11};
1806 client_writer_->WritePacket(&packet[0], sizeof(packet),
1807 client_->client()->client_address().address(),
1808 server_address_);
1809 // Give the server time to process the packet.
1810 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1811 // Pause the server so we can access the server's internals without races.
1812 server_thread_->Pause();
1813 QuicDispatcher* dispatcher =
1814 QuicServerPeer::GetDispatcher(server_thread_->server());
1815 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1816 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1817 server_thread_->Resume();
1819 // The connection should not be terminated.
1820 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1821 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1824 // A bad header shouldn't tear down the connection, because the receiver can't
1825 // tell the connection ID.
1826 TEST_P(EndToEndTest, BadPacketHeaderFlags) {
1827 ASSERT_TRUE(Initialize());
1829 // Start the connection.
1830 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1831 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1833 // Packet with invalid public flags.
1834 char packet[] = {
1835 // invalid public flags
1836 0xFF,
1837 // connection_id
1838 0x10,
1839 0x32,
1840 0x54,
1841 0x76,
1842 0x98,
1843 0xBA,
1844 0xDC,
1845 0xFE,
1846 // packet sequence number
1847 0xBC,
1848 0x9A,
1849 0x78,
1850 0x56,
1851 0x34,
1852 0x12,
1853 // private flags
1854 0x00,
1856 client_writer_->WritePacket(&packet[0], sizeof(packet),
1857 client_->client()->client_address().address(),
1858 server_address_);
1859 // Give the server time to process the packet.
1860 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1861 // Pause the server so we can access the server's internals without races.
1862 server_thread_->Pause();
1863 QuicDispatcher* dispatcher =
1864 QuicServerPeer::GetDispatcher(server_thread_->server());
1865 EXPECT_EQ(QUIC_INVALID_PACKET_HEADER,
1866 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1867 server_thread_->Resume();
1869 // The connection should not be terminated.
1870 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1871 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1874 // Send a packet from the client with bad encrypted data. The server should not
1875 // tear down the connection.
1876 TEST_P(EndToEndTest, BadEncryptedData) {
1877 ASSERT_TRUE(Initialize());
1879 // Start the connection.
1880 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1881 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1883 scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
1884 client_->client()->session()->connection()->connection_id(), false, false,
1885 1, "At least 20 characters.", PACKET_8BYTE_CONNECTION_ID,
1886 PACKET_6BYTE_PACKET_NUMBER));
1887 // Damage the encrypted data.
1888 string damaged_packet(packet->data(), packet->length());
1889 damaged_packet[30] ^= 0x01;
1890 DVLOG(1) << "Sending bad packet.";
1891 client_writer_->WritePacket(damaged_packet.data(), damaged_packet.length(),
1892 client_->client()->client_address().address(),
1893 server_address_);
1894 // Give the server time to process the packet.
1895 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
1896 // This error is sent to the connection's OnError (which ignores it), so the
1897 // dispatcher doesn't see it.
1898 // Pause the server so we can access the server's internals without races.
1899 server_thread_->Pause();
1900 QuicDispatcher* dispatcher =
1901 QuicServerPeer::GetDispatcher(server_thread_->server());
1902 EXPECT_EQ(QUIC_NO_ERROR,
1903 QuicDispatcherPeer::GetAndClearLastError(dispatcher));
1904 server_thread_->Resume();
1906 // The connection should not be terminated.
1907 EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1908 EXPECT_EQ(200u, client_->response_headers()->parsed_response_code());
1911 } // namespace
1912 } // namespace test
1913 } // namespace tools
1914 } // namespace net