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