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