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