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