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 <cstddef>
6 #include <cstdint>
7 #include <list>
8 #include <memory>
9 #include <ostream>
10 #include <string>
11 #include <utility>
12 #include <vector>
13 
14 #include "absl/strings/string_view.h"
15 #include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
16 #include "net/third_party/quiche/src/quic/core/http/http_constants.h"
17 #include "net/third_party/quiche/src/quic/core/http/quic_spdy_client_stream.h"
18 #include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
19 #include "net/third_party/quiche/src/quic/core/quic_epoll_connection_helper.h"
20 #include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
21 #include "net/third_party/quiche/src/quic/core/quic_framer.h"
22 #include "net/third_party/quiche/src/quic/core/quic_packet_creator.h"
23 #include "net/third_party/quiche/src/quic/core/quic_packet_writer_wrapper.h"
24 #include "net/third_party/quiche/src/quic/core/quic_packets.h"
25 #include "net/third_party/quiche/src/quic/core/quic_session.h"
26 #include "net/third_party/quiche/src/quic/core/quic_utils.h"
27 #include "net/third_party/quiche/src/quic/platform/api/quic_epoll.h"
28 #include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
29 #include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
30 #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
31 #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
32 #include "net/third_party/quiche/src/quic/platform/api/quic_port_utils.h"
33 #include "net/third_party/quiche/src/quic/platform/api/quic_sleep.h"
34 #include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
35 #include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
36 #include "net/third_party/quiche/src/quic/platform/api/quic_test_loopback.h"
37 #include "net/third_party/quiche/src/quic/test_tools/bad_packet_writer.h"
38 #include "net/third_party/quiche/src/quic/test_tools/crypto_test_utils.h"
39 #include "net/third_party/quiche/src/quic/test_tools/packet_dropping_test_writer.h"
40 #include "net/third_party/quiche/src/quic/test_tools/packet_reordering_writer.h"
41 #include "net/third_party/quiche/src/quic/test_tools/qpack/qpack_encoder_peer.h"
42 #include "net/third_party/quiche/src/quic/test_tools/qpack/qpack_encoder_test_utils.h"
43 #include "net/third_party/quiche/src/quic/test_tools/qpack/qpack_header_table_peer.h"
44 #include "net/third_party/quiche/src/quic/test_tools/qpack/qpack_test_utils.h"
45 #include "net/third_party/quiche/src/quic/test_tools/quic_client_peer.h"
46 #include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
47 #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
48 #include "net/third_party/quiche/src/quic/test_tools/quic_dispatcher_peer.h"
49 #include "net/third_party/quiche/src/quic/test_tools/quic_flow_controller_peer.h"
50 #include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
51 #include "net/third_party/quiche/src/quic/test_tools/quic_server_peer.h"
52 #include "net/third_party/quiche/src/quic/test_tools/quic_session_peer.h"
53 #include "net/third_party/quiche/src/quic/test_tools/quic_spdy_session_peer.h"
54 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_id_manager_peer.h"
55 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_peer.h"
56 #include "net/third_party/quiche/src/quic/test_tools/quic_stream_sequencer_peer.h"
57 #include "net/third_party/quiche/src/quic/test_tools/quic_test_client.h"
58 #include "net/third_party/quiche/src/quic/test_tools/quic_test_server.h"
59 #include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
60 #include "net/third_party/quiche/src/quic/test_tools/server_thread.h"
61 #include "net/third_party/quiche/src/quic/test_tools/simple_session_cache.h"
62 #include "net/third_party/quiche/src/quic/tools/quic_backend_response.h"
63 #include "net/third_party/quiche/src/quic/tools/quic_client.h"
64 #include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h"
65 #include "net/third_party/quiche/src/quic/tools/quic_server.h"
66 #include "net/third_party/quiche/src/quic/tools/quic_simple_client_stream.h"
67 #include "net/third_party/quiche/src/quic/tools/quic_simple_server_stream.h"
68 #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
69 #include "net/third_party/quiche/src/common/platform/api/quiche_text_utils.h"
70 
71 using spdy::kV3LowestPriority;
72 using spdy::SpdyFramer;
73 using spdy::SpdyHeaderBlock;
74 using spdy::SpdySerializedFrame;
75 using spdy::SpdySettingsIR;
76 using ::testing::_;
77 using ::testing::Invoke;
78 using ::testing::NiceMock;
79 
80 namespace quic {
81 namespace test {
82 namespace {
83 
84 const char kFooResponseBody[] = "Artichoke hearts make me happy.";
85 const char kBarResponseBody[] = "Palm hearts are pretty delicious, also.";
86 const char kTestUserAgentId[] = "quic/core/http/end_to_end_test.cc";
87 const float kSessionToStreamRatio = 1.5;
88 
89 // Run all tests with the cross products of all versions.
90 struct TestParams {
TestParamsquic::test::__anon65d2caa30111::TestParams91   TestParams(const ParsedQuicVersion& version, QuicTag congestion_control_tag)
92       : version(version), congestion_control_tag(congestion_control_tag) {}
93 
operator <<(std::ostream & os,const TestParams & p)94   friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
95     os << "{ version: " << ParsedQuicVersionToString(p.version);
96     os << " congestion_control_tag: "
97        << QuicTagToString(p.congestion_control_tag) << " }";
98     return os;
99   }
100 
101   ParsedQuicVersion version;
102   QuicTag congestion_control_tag;
103 };
104 
105 // Used by ::testing::PrintToStringParamName().
PrintToString(const TestParams & p)106 std::string PrintToString(const TestParams& p) {
107   std::string rv =
108       quiche::QuicheStrCat(ParsedQuicVersionToString(p.version), "_",
109                            QuicTagToString(p.congestion_control_tag));
110   std::replace(rv.begin(), rv.end(), ',', '_');
111   std::replace(rv.begin(), rv.end(), ' ', '_');
112   return rv;
113 }
114 
115 // Constructs various test permutations.
GetTestParams()116 std::vector<TestParams> GetTestParams() {
117   std::vector<TestParams> params;
118   for (const QuicTag congestion_control_tag : {kRENO, kTBBR, kQBIC, kB2ON}) {
119     if (!GetQuicReloadableFlag(quic_allow_client_enabled_bbr_v2) &&
120         congestion_control_tag == kB2ON) {
121       continue;
122     }
123     for (const ParsedQuicVersion& version : CurrentSupportedVersions()) {
124       params.push_back(TestParams(version, congestion_control_tag));
125     }  // End of outer version loop.
126   }    // End of congestion_control_tag loop.
127 
128   return params;
129 }
130 
WriteHeadersOnStream(QuicSpdyStream * stream)131 void WriteHeadersOnStream(QuicSpdyStream* stream) {
132   // Since QuicSpdyStream uses QuicHeaderList::empty() to detect too large
133   // headers, it also fails when receiving empty headers.
134   SpdyHeaderBlock headers;
135   headers["foo"] = "bar";
136   stream->WriteHeaders(std::move(headers), /* fin = */ false, nullptr);
137 }
138 
139 class ServerDelegate : public PacketDroppingTestWriter::Delegate {
140  public:
ServerDelegate(QuicDispatcher * dispatcher)141   explicit ServerDelegate(QuicDispatcher* dispatcher)
142       : dispatcher_(dispatcher) {}
143   ~ServerDelegate() override = default;
OnCanWrite()144   void OnCanWrite() override { dispatcher_->OnCanWrite(); }
145 
146  private:
147   QuicDispatcher* dispatcher_;
148 };
149 
150 class ClientDelegate : public PacketDroppingTestWriter::Delegate {
151  public:
ClientDelegate(QuicClient * client)152   explicit ClientDelegate(QuicClient* client) : client_(client) {}
153   ~ClientDelegate() override = default;
OnCanWrite()154   void OnCanWrite() override {
155     QuicEpollEvent event(EPOLLOUT);
156     client_->epoll_network_helper()->OnEvent(client_->GetLatestFD(), &event);
157   }
158 
159  private:
160   QuicClient* client_;
161 };
162 
163 class EndToEndTest : public QuicTestWithParam<TestParams> {
164  protected:
EndToEndTest()165   EndToEndTest()
166       : initialized_(false),
167         connect_to_server_on_initialize_(true),
168         server_address_(QuicSocketAddress(TestLoopback(),
169                                           QuicPickServerPortForTestsOrDie())),
170         server_hostname_("test.example.com"),
171         client_writer_(nullptr),
172         server_writer_(nullptr),
173         version_(GetParam().version),
174         client_supported_versions_({version_}),
175         server_supported_versions_(CurrentSupportedVersions()),
176         chlo_multiplier_(0),
177         stream_factory_(nullptr),
178         expected_server_connection_id_length_(kQuicDefaultConnectionIdLength) {
179     QUIC_LOG(INFO) << "Using Configuration: " << GetParam();
180 
181     // Use different flow control windows for client/server.
182     client_config_.SetInitialStreamFlowControlWindowToSend(
183         2 * kInitialStreamFlowControlWindowForTest);
184     client_config_.SetInitialSessionFlowControlWindowToSend(
185         2 * kInitialSessionFlowControlWindowForTest);
186     server_config_.SetInitialStreamFlowControlWindowToSend(
187         3 * kInitialStreamFlowControlWindowForTest);
188     server_config_.SetInitialSessionFlowControlWindowToSend(
189         3 * kInitialSessionFlowControlWindowForTest);
190 
191     // The default idle timeouts can be too strict when running on a busy
192     // machine.
193     const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(30);
194     client_config_.set_max_time_before_crypto_handshake(timeout);
195     client_config_.set_max_idle_time_before_crypto_handshake(timeout);
196     server_config_.set_max_time_before_crypto_handshake(timeout);
197     server_config_.set_max_idle_time_before_crypto_handshake(timeout);
198 
199     AddToCache("/foo", 200, kFooResponseBody);
200     AddToCache("/bar", 200, kBarResponseBody);
201     // Enable fixes for bugs found in tests and prod.
202     SetQuicRestartFlag(quic_enable_zero_rtt_for_tls_v2, true);
203     SetQuicReloadableFlag(quic_fix_out_of_order_sending2, true);
204   }
205 
~EndToEndTest()206   ~EndToEndTest() override { QuicRecyclePort(server_address_.port()); }
207 
CreateClientWithWriter()208   virtual void CreateClientWithWriter() {
209     client_.reset(CreateQuicClient(client_writer_));
210   }
211 
CreateQuicClient(QuicPacketWriterWrapper * writer)212   QuicTestClient* CreateQuicClient(QuicPacketWriterWrapper* writer) {
213     QuicTestClient* client =
214         new QuicTestClient(server_address_, server_hostname_, client_config_,
215                            client_supported_versions_,
216                            crypto_test_utils::ProofVerifierForTesting(),
217                            std::make_unique<SimpleSessionCache>());
218     client->SetUserAgentID(kTestUserAgentId);
219     client->UseWriter(writer);
220     if (!pre_shared_key_client_.empty()) {
221       client->client()->SetPreSharedKey(pre_shared_key_client_);
222     }
223     client->UseConnectionIdLength(override_server_connection_id_length_);
224     client->UseClientConnectionIdLength(override_client_connection_id_length_);
225     client->client()->set_connection_debug_visitor(connection_debug_visitor_);
226     client->Connect();
227     return client;
228   }
229 
set_smaller_flow_control_receive_window()230   void set_smaller_flow_control_receive_window() {
231     const uint32_t kClientIFCW = 64 * 1024;
232     const uint32_t kServerIFCW = 1024 * 1024;
233     set_client_initial_stream_flow_control_receive_window(kClientIFCW);
234     set_client_initial_session_flow_control_receive_window(
235         kSessionToStreamRatio * kClientIFCW);
236     set_server_initial_stream_flow_control_receive_window(kServerIFCW);
237     set_server_initial_session_flow_control_receive_window(
238         kSessionToStreamRatio * kServerIFCW);
239   }
240 
set_client_initial_stream_flow_control_receive_window(uint32_t window)241   void set_client_initial_stream_flow_control_receive_window(uint32_t window) {
242     ASSERT_TRUE(client_ == nullptr);
243     QUIC_DLOG(INFO) << "Setting client initial stream flow control window: "
244                     << window;
245     client_config_.SetInitialStreamFlowControlWindowToSend(window);
246   }
247 
set_client_initial_session_flow_control_receive_window(uint32_t window)248   void set_client_initial_session_flow_control_receive_window(uint32_t window) {
249     ASSERT_TRUE(client_ == nullptr);
250     QUIC_DLOG(INFO) << "Setting client initial session flow control window: "
251                     << window;
252     client_config_.SetInitialSessionFlowControlWindowToSend(window);
253   }
254 
set_client_initial_max_stream_data_incoming_bidirectional(uint32_t window)255   void set_client_initial_max_stream_data_incoming_bidirectional(
256       uint32_t window) {
257     ASSERT_TRUE(client_ == nullptr);
258     QUIC_DLOG(INFO)
259         << "Setting client initial max stream data incoming bidirectional: "
260         << window;
261     client_config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
262         window);
263   }
264 
set_server_initial_max_stream_data_outgoing_bidirectional(uint32_t window)265   void set_server_initial_max_stream_data_outgoing_bidirectional(
266       uint32_t window) {
267     ASSERT_TRUE(client_ == nullptr);
268     QUIC_DLOG(INFO)
269         << "Setting server initial max stream data outgoing bidirectional: "
270         << window;
271     server_config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(
272         window);
273   }
274 
set_server_initial_stream_flow_control_receive_window(uint32_t window)275   void set_server_initial_stream_flow_control_receive_window(uint32_t window) {
276     ASSERT_TRUE(server_thread_ == nullptr);
277     QUIC_DLOG(INFO) << "Setting server initial stream flow control window: "
278                     << window;
279     server_config_.SetInitialStreamFlowControlWindowToSend(window);
280   }
281 
set_server_initial_session_flow_control_receive_window(uint32_t window)282   void set_server_initial_session_flow_control_receive_window(uint32_t window) {
283     ASSERT_TRUE(server_thread_ == nullptr);
284     QUIC_DLOG(INFO) << "Setting server initial session flow control window: "
285                     << window;
286     server_config_.SetInitialSessionFlowControlWindowToSend(window);
287   }
288 
GetSentPacketManagerFromFirstServerSession()289   const QuicSentPacketManager* GetSentPacketManagerFromFirstServerSession() {
290     QuicConnection* server_connection = GetServerConnection();
291     if (server_connection == nullptr) {
292       ADD_FAILURE() << "Missing server connection";
293       return nullptr;
294     }
295     return &server_connection->sent_packet_manager();
296   }
297 
GetSentPacketManagerFromClientSession()298   const QuicSentPacketManager* GetSentPacketManagerFromClientSession() {
299     QuicConnection* client_connection = GetClientConnection();
300     if (client_connection == nullptr) {
301       ADD_FAILURE() << "Missing client connection";
302       return nullptr;
303     }
304     return &client_connection->sent_packet_manager();
305   }
306 
GetClientSession()307   QuicSpdyClientSession* GetClientSession() {
308     if (!client_) {
309       ADD_FAILURE() << "Missing QuicTestClient";
310       return nullptr;
311     }
312     if (client_->client() == nullptr) {
313       ADD_FAILURE() << "Missing MockableQuicClient";
314       return nullptr;
315     }
316     return client_->client()->client_session();
317   }
318 
GetClientConnection()319   QuicConnection* GetClientConnection() {
320     QuicSpdyClientSession* client_session = GetClientSession();
321     if (client_session == nullptr) {
322       ADD_FAILURE() << "Missing client session";
323       return nullptr;
324     }
325     return client_session->connection();
326   }
327 
GetServerConnection()328   QuicConnection* GetServerConnection() {
329     QuicSpdySession* server_session = GetServerSession();
330     if (server_session == nullptr) {
331       ADD_FAILURE() << "Missing server session";
332       return nullptr;
333     }
334     return server_session->connection();
335   }
336 
GetServerSession()337   QuicSpdySession* GetServerSession() {
338     if (!server_thread_) {
339       ADD_FAILURE() << "Missing server thread";
340       return nullptr;
341     }
342     QuicServer* quic_server = server_thread_->server();
343     if (quic_server == nullptr) {
344       ADD_FAILURE() << "Missing server";
345       return nullptr;
346     }
347     QuicDispatcher* dispatcher = QuicServerPeer::GetDispatcher(quic_server);
348     if (dispatcher == nullptr) {
349       ADD_FAILURE() << "Missing dispatcher";
350       return nullptr;
351     }
352     if (dispatcher->session_map().empty()) {
353       ADD_FAILURE() << "Empty dispatcher session map";
354       return nullptr;
355     }
356     EXPECT_EQ(1u, dispatcher->session_map().size());
357     return static_cast<QuicSpdySession*>(
358         dispatcher->session_map().begin()->second.get());
359   }
360 
Initialize()361   bool Initialize() {
362     QuicTagVector copt;
363     server_config_.SetConnectionOptionsToSend(copt);
364     copt = client_extra_copts_;
365 
366     // TODO(nimia): Consider setting the congestion control algorithm for the
367     // client as well according to the test parameter.
368     copt.push_back(GetParam().congestion_control_tag);
369     copt.push_back(k2PTO);
370     if (version_.HasIetfQuicFrames()) {
371       copt.push_back(kILD0);
372     }
373     copt.push_back(kPLE1);
374     client_config_.SetConnectionOptionsToSend(copt);
375 
376     // Start the server first, because CreateQuicClient() attempts
377     // to connect to the server.
378     StartServer();
379 
380     if (!connect_to_server_on_initialize_) {
381       initialized_ = true;
382       return true;
383     }
384 
385     CreateClientWithWriter();
386     if (!client_) {
387       ADD_FAILURE() << "Missing QuicTestClient";
388       return false;
389     }
390     MockableQuicClient* client = client_->client();
391     if (client == nullptr) {
392       ADD_FAILURE() << "Missing MockableQuicClient";
393       return false;
394     }
395     static QuicEpollEvent event(EPOLLOUT);
396     if (client_writer_ != nullptr) {
397       QuicConnection* client_connection = GetClientConnection();
398       if (client_connection == nullptr) {
399         ADD_FAILURE() << "Missing client connection";
400         return false;
401       }
402       client_writer_->Initialize(
403           QuicConnectionPeer::GetHelper(client_connection),
404           QuicConnectionPeer::GetAlarmFactory(client_connection),
405           std::make_unique<ClientDelegate>(client));
406     }
407     initialized_ = true;
408     return client->connected();
409   }
410 
SetUp()411   void SetUp() override {
412     // The ownership of these gets transferred to the QuicPacketWriterWrapper
413     // when Initialize() is executed.
414     client_writer_ = new PacketDroppingTestWriter();
415     server_writer_ = new PacketDroppingTestWriter();
416   }
417 
TearDown()418   void TearDown() override {
419     EXPECT_TRUE(initialized_) << "You must call Initialize() in every test "
420                               << "case. Otherwise, your test will leak memory.";
421     QuicConnection* client_connection = GetClientConnection();
422     if (client_connection != nullptr) {
423       client_connection->set_debug_visitor(nullptr);
424     } else {
425       ADD_FAILURE() << "Missing client connection";
426     }
427     StopServer();
428   }
429 
StartServer()430   void StartServer() {
431     auto* test_server = new QuicTestServer(
432         crypto_test_utils::ProofSourceForTesting(), server_config_,
433         server_supported_versions_, &memory_cache_backend_,
434         expected_server_connection_id_length_);
435     server_thread_ =
436         std::make_unique<ServerThread>(test_server, server_address_);
437     if (chlo_multiplier_ != 0) {
438       server_thread_->server()->SetChloMultiplier(chlo_multiplier_);
439     }
440     if (!pre_shared_key_server_.empty()) {
441       server_thread_->server()->SetPreSharedKey(pre_shared_key_server_);
442     }
443     server_thread_->Initialize();
444     server_address_ =
445         QuicSocketAddress(server_address_.host(), server_thread_->GetPort());
446     QuicDispatcher* dispatcher =
447         QuicServerPeer::GetDispatcher(server_thread_->server());
448     QuicDispatcherPeer::UseWriter(dispatcher, server_writer_);
449 
450     server_writer_->Initialize(QuicDispatcherPeer::GetHelper(dispatcher),
451                                QuicDispatcherPeer::GetAlarmFactory(dispatcher),
452                                std::make_unique<ServerDelegate>(dispatcher));
453     if (stream_factory_ != nullptr) {
454       static_cast<QuicTestServer*>(server_thread_->server())
455           ->SetSpdyStreamFactory(stream_factory_);
456     }
457 
458     server_thread_->Start();
459   }
460 
StopServer()461   void StopServer() {
462     if (server_thread_) {
463       server_thread_->Quit();
464       server_thread_->Join();
465     }
466   }
467 
AddToCache(absl::string_view path,int response_code,absl::string_view body)468   void AddToCache(absl::string_view path,
469                   int response_code,
470                   absl::string_view body) {
471     memory_cache_backend_.AddSimpleResponse(server_hostname_, path,
472                                             response_code, body);
473   }
474 
SetPacketLossPercentage(int32_t loss)475   void SetPacketLossPercentage(int32_t loss) {
476     client_writer_->set_fake_packet_loss_percentage(loss);
477     server_writer_->set_fake_packet_loss_percentage(loss);
478   }
479 
SetPacketSendDelay(QuicTime::Delta delay)480   void SetPacketSendDelay(QuicTime::Delta delay) {
481     client_writer_->set_fake_packet_delay(delay);
482     server_writer_->set_fake_packet_delay(delay);
483   }
484 
SetReorderPercentage(int32_t reorder)485   void SetReorderPercentage(int32_t reorder) {
486     client_writer_->set_fake_reorder_percentage(reorder);
487     server_writer_->set_fake_reorder_percentage(reorder);
488   }
489 
490   // Verifies that the client and server connections were both free of packets
491   // being discarded, based on connection stats.
492   // Calls server_thread_ Pause() and Resume(), which may only be called once
493   // per test.
VerifyCleanConnection(bool had_packet_loss)494   void VerifyCleanConnection(bool had_packet_loss) {
495     QuicConnection* client_connection = GetClientConnection();
496     if (client_connection == nullptr) {
497       ADD_FAILURE() << "Missing client connection";
498       return;
499     }
500     QuicConnectionStats client_stats = client_connection->GetStats();
501     // TODO(ianswett): Determine why this becomes even more flaky with BBR
502     // enabled.  b/62141144
503     if (!had_packet_loss && !GetQuicReloadableFlag(quic_default_to_bbr)) {
504       EXPECT_EQ(0u, client_stats.packets_lost);
505     }
506     EXPECT_EQ(0u, client_stats.packets_discarded);
507     // When client starts with an unsupported version, the version negotiation
508     // packet sent by server for the old connection (respond for the connection
509     // close packet) will be dropped by the client.
510     if (!ServerSendsVersionNegotiation()) {
511       EXPECT_EQ(0u, client_stats.packets_dropped);
512     }
513     if (!version_.UsesTls()) {
514       // Only enforce this for QUIC crypto because accounting of number of
515       // packets received, processed gets complicated with packets coalescing
516       // and key dropping. For example, a received undecryptable coalesced
517       // packet can be processed later and each sub-packet increases
518       // packets_processed.
519       EXPECT_EQ(client_stats.packets_received, client_stats.packets_processed);
520     }
521 
522     if (!server_thread_) {
523       ADD_FAILURE() << "Missing server thread";
524       return;
525     }
526     server_thread_->Pause();
527     QuicSpdySession* server_session = GetServerSession();
528     if (server_session != nullptr) {
529       QuicConnection* server_connection = server_session->connection();
530       if (server_connection != nullptr) {
531         QuicConnectionStats server_stats = server_connection->GetStats();
532         if (!had_packet_loss) {
533           EXPECT_EQ(0u, server_stats.packets_lost);
534         }
535         EXPECT_EQ(0u, server_stats.packets_discarded);
536         EXPECT_EQ(server_session->user_agent_id().value_or("MissingUserAgent"),
537                   kTestUserAgentId);
538       } else {
539         ADD_FAILURE() << "Missing server connection";
540       }
541     } else {
542       ADD_FAILURE() << "Missing server session";
543     }
544     // TODO(ianswett): Restore the check for packets_dropped equals 0.
545     // The expect for packets received is equal to packets processed fails
546     // due to version negotiation packets.
547     server_thread_->Resume();
548   }
549 
550   // Returns true when client starts with an unsupported version, and client
551   // closes connection when version negotiation is received.
ServerSendsVersionNegotiation()552   bool ServerSendsVersionNegotiation() {
553     return client_supported_versions_[0] != version_;
554   }
555 
SupportsIetfQuicWithTls(ParsedQuicVersion version)556   bool SupportsIetfQuicWithTls(ParsedQuicVersion version) {
557     return version.HasIetfInvariantHeader() &&
558            version.handshake_protocol == PROTOCOL_TLS1_3;
559   }
560 
ExpectFlowControlsSynced(QuicSession * client,QuicSession * server)561   static void ExpectFlowControlsSynced(QuicSession* client,
562                                        QuicSession* server) {
563     EXPECT_EQ(
564         QuicFlowControllerPeer::SendWindowSize(client->flow_controller()),
565         QuicFlowControllerPeer::ReceiveWindowSize(server->flow_controller()));
566     EXPECT_EQ(
567         QuicFlowControllerPeer::ReceiveWindowSize(client->flow_controller()),
568         QuicFlowControllerPeer::SendWindowSize(server->flow_controller()));
569   }
570 
ExpectFlowControlsSynced(QuicStream * client,QuicStream * server)571   static void ExpectFlowControlsSynced(QuicStream* client, QuicStream* server) {
572     EXPECT_EQ(QuicStreamPeer::SendWindowSize(client),
573               QuicStreamPeer::ReceiveWindowSize(server));
574     EXPECT_EQ(QuicStreamPeer::ReceiveWindowSize(client),
575               QuicStreamPeer::SendWindowSize(server));
576   }
577 
578   // Must be called before Initialize to have effect.
SetSpdyStreamFactory(QuicTestServer::StreamFactory * factory)579   void SetSpdyStreamFactory(QuicTestServer::StreamFactory* factory) {
580     stream_factory_ = factory;
581   }
582 
GetNthClientInitiatedBidirectionalId(int n)583   QuicStreamId GetNthClientInitiatedBidirectionalId(int n) {
584     return GetNthClientInitiatedBidirectionalStreamId(
585         version_.transport_version, n);
586   }
587 
GetNthServerInitiatedBidirectionalId(int n)588   QuicStreamId GetNthServerInitiatedBidirectionalId(int n) {
589     return GetNthServerInitiatedBidirectionalStreamId(
590         version_.transport_version, n);
591   }
592 
CheckResponseHeaders(QuicTestClient * client,const std::string & expected_status)593   bool CheckResponseHeaders(QuicTestClient* client,
594                             const std::string& expected_status) {
595     const spdy::SpdyHeaderBlock* response_headers = client->response_headers();
596     auto it = response_headers->find(":status");
597     if (it == response_headers->end()) {
598       ADD_FAILURE() << "Did not find :status header in response";
599       return false;
600     }
601     if (it->second != expected_status) {
602       ADD_FAILURE() << "Got bad :status response: \"" << it->second << "\"";
603       return false;
604     }
605     return true;
606   }
607 
CheckResponseHeaders(QuicTestClient * client)608   bool CheckResponseHeaders(QuicTestClient* client) {
609     return CheckResponseHeaders(client, "200");
610   }
611 
CheckResponseHeaders(const std::string & expected_status)612   bool CheckResponseHeaders(const std::string& expected_status) {
613     return CheckResponseHeaders(client_.get(), expected_status);
614   }
615 
CheckResponseHeaders()616   bool CheckResponseHeaders() { return CheckResponseHeaders(client_.get()); }
617 
CheckResponse(QuicTestClient * client,const std::string & received_response,const std::string & expected_response)618   bool CheckResponse(QuicTestClient* client,
619                      const std::string& received_response,
620                      const std::string& expected_response) {
621     EXPECT_THAT(client_->stream_error(), IsQuicStreamNoError());
622     EXPECT_THAT(client_->connection_error(), IsQuicNoError());
623 
624     if (received_response.empty() && !expected_response.empty()) {
625       ADD_FAILURE() << "Failed to get any response for request";
626       return false;
627     }
628     if (received_response != expected_response) {
629       ADD_FAILURE() << "Got wrong response: \"" << received_response << "\"";
630       return false;
631     }
632     return CheckResponseHeaders(client);
633   }
634 
SendSynchronousRequestAndCheckResponse(QuicTestClient * client,const std::string & request,const std::string & expected_response)635   bool SendSynchronousRequestAndCheckResponse(
636       QuicTestClient* client,
637       const std::string& request,
638       const std::string& expected_response) {
639     std::string received_response = client->SendSynchronousRequest(request);
640     return CheckResponse(client, received_response, expected_response);
641   }
642 
SendSynchronousRequestAndCheckResponse(const std::string & request,const std::string & expected_response)643   bool SendSynchronousRequestAndCheckResponse(
644       const std::string& request,
645       const std::string& expected_response) {
646     return SendSynchronousRequestAndCheckResponse(client_.get(), request,
647                                                   expected_response);
648   }
649 
SendSynchronousFooRequestAndCheckResponse(QuicTestClient * client)650   bool SendSynchronousFooRequestAndCheckResponse(QuicTestClient* client) {
651     return SendSynchronousRequestAndCheckResponse(client, "/foo",
652                                                   kFooResponseBody);
653   }
654 
SendSynchronousFooRequestAndCheckResponse()655   bool SendSynchronousFooRequestAndCheckResponse() {
656     return SendSynchronousFooRequestAndCheckResponse(client_.get());
657   }
658 
SendSynchronousBarRequestAndCheckResponse()659   bool SendSynchronousBarRequestAndCheckResponse() {
660     std::string received_response = client_->SendSynchronousRequest("/bar");
661     return CheckResponse(client_.get(), received_response, kBarResponseBody);
662   }
663 
WaitForFooResponseAndCheckIt(QuicTestClient * client)664   bool WaitForFooResponseAndCheckIt(QuicTestClient* client) {
665     client->WaitForResponse();
666     std::string received_response = client->response_body();
667     return CheckResponse(client_.get(), received_response, kFooResponseBody);
668   }
669 
WaitForFooResponseAndCheckIt()670   bool WaitForFooResponseAndCheckIt() {
671     return WaitForFooResponseAndCheckIt(client_.get());
672   }
673 
674   ScopedEnvironmentForThreads environment_;
675   bool initialized_;
676   // If true, the Initialize() function will create |client_| and starts to
677   // connect to the server.
678   // Default is true.
679   bool connect_to_server_on_initialize_;
680   QuicSocketAddress server_address_;
681   std::string server_hostname_;
682   QuicMemoryCacheBackend memory_cache_backend_;
683   std::unique_ptr<ServerThread> server_thread_;
684   std::unique_ptr<QuicTestClient> client_;
685   QuicConnectionDebugVisitor* connection_debug_visitor_ = nullptr;
686   PacketDroppingTestWriter* client_writer_;
687   PacketDroppingTestWriter* server_writer_;
688   QuicConfig client_config_;
689   QuicConfig server_config_;
690   ParsedQuicVersion version_;
691   ParsedQuicVersionVector client_supported_versions_;
692   ParsedQuicVersionVector server_supported_versions_;
693   QuicTagVector client_extra_copts_;
694   size_t chlo_multiplier_;
695   QuicTestServer::StreamFactory* stream_factory_;
696   std::string pre_shared_key_client_;
697   std::string pre_shared_key_server_;
698   int override_server_connection_id_length_ = -1;
699   int override_client_connection_id_length_ = -1;
700   uint8_t expected_server_connection_id_length_;
701 };
702 
703 // Run all end to end tests with all supported versions.
704 INSTANTIATE_TEST_SUITE_P(EndToEndTests,
705                          EndToEndTest,
706                          ::testing::ValuesIn(GetTestParams()),
707                          ::testing::PrintToStringParamName());
708 
TEST_P(EndToEndTest,HandshakeSuccessful)709 TEST_P(EndToEndTest, HandshakeSuccessful) {
710   ASSERT_TRUE(Initialize());
711   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
712   ASSERT_TRUE(server_thread_);
713   server_thread_->WaitForCryptoHandshakeConfirmed();
714   QuicSpdyClientSession* client_session = GetClientSession();
715   ASSERT_TRUE(client_session);
716   QuicCryptoStream* client_crypto_stream =
717       QuicSessionPeer::GetMutableCryptoStream(client_session);
718   ASSERT_TRUE(client_crypto_stream);
719   QuicStreamSequencer* client_sequencer =
720       QuicStreamPeer::sequencer(client_crypto_stream);
721   ASSERT_TRUE(client_sequencer);
722   EXPECT_FALSE(
723       QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(client_sequencer));
724 
725   // We've had bugs in the past where the connections could end up on the wrong
726   // version. This was never diagnosed but could have been due to in-connection
727   // version negotiation back when that existed. At this point in time, our test
728   // setup ensures that connections here always use |version_|, but we add this
729   // sanity check out of paranoia to catch a regression of this type.
730   QuicConnection* client_connection = GetClientConnection();
731   ASSERT_TRUE(client_connection);
732   EXPECT_EQ(client_connection->version(), version_);
733 
734   server_thread_->Pause();
735   QuicSpdySession* server_session = GetServerSession();
736   QuicConnection* server_connection = nullptr;
737   QuicCryptoStream* server_crypto_stream = nullptr;
738   QuicStreamSequencer* server_sequencer = nullptr;
739   if (server_session != nullptr) {
740     server_connection = server_session->connection();
741     server_crypto_stream =
742         QuicSessionPeer::GetMutableCryptoStream(server_session);
743   } else {
744     ADD_FAILURE() << "Missing server session";
745   }
746   if (server_crypto_stream != nullptr) {
747     server_sequencer = QuicStreamPeer::sequencer(server_crypto_stream);
748   } else {
749     ADD_FAILURE() << "Missing server crypto stream";
750   }
751   if (server_sequencer != nullptr) {
752     EXPECT_FALSE(
753         QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(server_sequencer));
754   } else {
755     ADD_FAILURE() << "Missing server sequencer";
756   }
757   if (server_connection != nullptr) {
758     EXPECT_EQ(server_connection->version(), version_);
759   } else {
760     ADD_FAILURE() << "Missing server connection";
761   }
762   server_thread_->Resume();
763 }
764 
TEST_P(EndToEndTest,SimpleRequestResponse)765 TEST_P(EndToEndTest, SimpleRequestResponse) {
766   ASSERT_TRUE(Initialize());
767 
768   SendSynchronousFooRequestAndCheckResponse();
769   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
770   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
771   if (version_.UsesHttp3()) {
772     QuicSpdyClientSession* client_session = GetClientSession();
773     ASSERT_TRUE(client_session);
774     EXPECT_TRUE(QuicSpdySessionPeer::GetSendControlStream(client_session));
775     EXPECT_TRUE(QuicSpdySessionPeer::GetReceiveControlStream(client_session));
776     server_thread_->Pause();
777     QuicSpdySession* server_session = GetServerSession();
778     if (server_session != nullptr) {
779       EXPECT_TRUE(QuicSpdySessionPeer::GetSendControlStream(server_session));
780       EXPECT_TRUE(QuicSpdySessionPeer::GetReceiveControlStream(server_session));
781     } else {
782       ADD_FAILURE() << "Missing server session";
783     }
784     server_thread_->Resume();
785   }
786   QuicConnectionStats client_stats = GetClientConnection()->GetStats();
787   EXPECT_TRUE(client_stats.handshake_completion_time.IsInitialized());
788 }
789 
TEST_P(EndToEndTest,HandshakeConfirmed)790 TEST_P(EndToEndTest, HandshakeConfirmed) {
791   ASSERT_TRUE(Initialize());
792   if (!version_.UsesTls()) {
793     return;
794   }
795   SendSynchronousFooRequestAndCheckResponse();
796   // Verify handshake state.
797   QuicSpdyClientSession* client_session = GetClientSession();
798   ASSERT_TRUE(client_session);
799   EXPECT_EQ(HANDSHAKE_CONFIRMED, client_session->GetHandshakeState());
800   server_thread_->Pause();
801   QuicSpdySession* server_session = GetServerSession();
802   if (server_session != nullptr) {
803     EXPECT_EQ(HANDSHAKE_CONFIRMED, server_session->GetHandshakeState());
804   } else {
805     ADD_FAILURE() << "Missing server session";
806   }
807   server_thread_->Resume();
808   client_->Disconnect();
809 }
810 
TEST_P(EndToEndTest,SendAndReceiveCoalescedPackets)811 TEST_P(EndToEndTest, SendAndReceiveCoalescedPackets) {
812   ASSERT_TRUE(Initialize());
813   if (!version_.CanSendCoalescedPackets()) {
814     return;
815   }
816   SendSynchronousFooRequestAndCheckResponse();
817   // Verify client successfully processes coalesced packets.
818   QuicConnection* client_connection = GetClientConnection();
819   ASSERT_TRUE(client_connection);
820   QuicConnectionStats client_stats = client_connection->GetStats();
821   EXPECT_LT(0u, client_stats.num_coalesced_packets_received);
822   EXPECT_EQ(client_stats.num_coalesced_packets_processed,
823             client_stats.num_coalesced_packets_received);
824   // TODO(fayang): verify server successfully processes coalesced packets.
825 }
826 
827 // Simple transaction, but set a non-default ack delay at the client
828 // and ensure it gets to the server.
TEST_P(EndToEndTest,SimpleRequestResponseWithAckDelayChange)829 TEST_P(EndToEndTest, SimpleRequestResponseWithAckDelayChange) {
830   // Force the ACK delay to be something other than the default.
831   constexpr uint32_t kClientMaxAckDelay = kDefaultDelayedAckTimeMs + 100u;
832   client_config_.SetMaxAckDelayToSendMs(kClientMaxAckDelay);
833   ASSERT_TRUE(Initialize());
834 
835   SendSynchronousFooRequestAndCheckResponse();
836   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
837   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
838 
839   server_thread_->Pause();
840   const QuicSentPacketManager* server_sent_packet_manager =
841       GetSentPacketManagerFromFirstServerSession();
842   if (server_sent_packet_manager != nullptr) {
843     EXPECT_EQ(
844         kClientMaxAckDelay,
845         server_sent_packet_manager->peer_max_ack_delay().ToMilliseconds());
846   } else {
847     ADD_FAILURE() << "Missing server sent packet manager";
848   }
849   server_thread_->Resume();
850 }
851 
852 // Simple transaction, but set a non-default ack exponent at the client
853 // and ensure it gets to the server.
TEST_P(EndToEndTest,SimpleRequestResponseWithAckExponentChange)854 TEST_P(EndToEndTest, SimpleRequestResponseWithAckExponentChange) {
855   const uint32_t kClientAckDelayExponent = 19;
856   EXPECT_NE(kClientAckDelayExponent, kDefaultAckDelayExponent);
857   // Force the ACK exponent to be something other than the default.
858   // Note that it is sent only with QUIC+TLS.
859   client_config_.SetAckDelayExponentToSend(kClientAckDelayExponent);
860   ASSERT_TRUE(Initialize());
861 
862   SendSynchronousFooRequestAndCheckResponse();
863 
864   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
865   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
866   server_thread_->Pause();
867   QuicConnection* server_connection = GetServerConnection();
868   if (server_connection != nullptr) {
869     if (version_.UsesTls()) {
870       // Should be only sent with QUIC+TLS.
871       EXPECT_EQ(kClientAckDelayExponent,
872                 server_connection->framer().peer_ack_delay_exponent());
873     } else {
874       // No change for QUIC_CRYPTO.
875       EXPECT_EQ(kDefaultAckDelayExponent,
876                 server_connection->framer().peer_ack_delay_exponent());
877     }
878     // No change, regardless of version.
879     EXPECT_EQ(kDefaultAckDelayExponent,
880               server_connection->framer().local_ack_delay_exponent());
881   } else {
882     ADD_FAILURE() << "Missing server connection";
883   }
884   server_thread_->Resume();
885 }
886 
TEST_P(EndToEndTest,SimpleRequestResponseForcedVersionNegotiation)887 TEST_P(EndToEndTest, SimpleRequestResponseForcedVersionNegotiation) {
888   client_supported_versions_.insert(client_supported_versions_.begin(),
889                                     QuicVersionReservedForNegotiation());
890   NiceMock<MockQuicConnectionDebugVisitor> visitor;
891   connection_debug_visitor_ = &visitor;
892   EXPECT_CALL(visitor, OnVersionNegotiationPacket(_)).Times(1);
893   ASSERT_TRUE(Initialize());
894   ASSERT_TRUE(ServerSendsVersionNegotiation());
895 
896   SendSynchronousFooRequestAndCheckResponse();
897 
898   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
899   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
900 }
901 
TEST_P(EndToEndTest,ForcedVersionNegotiation)902 TEST_P(EndToEndTest, ForcedVersionNegotiation) {
903   client_supported_versions_.insert(client_supported_versions_.begin(),
904                                     QuicVersionReservedForNegotiation());
905   ASSERT_TRUE(Initialize());
906   ASSERT_TRUE(ServerSendsVersionNegotiation());
907 
908   SendSynchronousFooRequestAndCheckResponse();
909 }
910 
TEST_P(EndToEndTest,SimpleRequestResponseZeroConnectionID)911 TEST_P(EndToEndTest, SimpleRequestResponseZeroConnectionID) {
912   if (!version_.AllowsVariableLengthConnectionIds()) {
913     ASSERT_TRUE(Initialize());
914     return;
915   }
916   override_server_connection_id_length_ = 0;
917   expected_server_connection_id_length_ = 0;
918   ASSERT_TRUE(Initialize());
919 
920   SendSynchronousFooRequestAndCheckResponse();
921   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
922   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
923   QuicConnection* client_connection = GetClientConnection();
924   ASSERT_TRUE(client_connection);
925   EXPECT_EQ(client_connection->connection_id(),
926             QuicUtils::CreateZeroConnectionId(version_.transport_version));
927 }
928 
TEST_P(EndToEndTest,ZeroConnectionID)929 TEST_P(EndToEndTest, ZeroConnectionID) {
930   if (!version_.AllowsVariableLengthConnectionIds()) {
931     ASSERT_TRUE(Initialize());
932     return;
933   }
934   override_server_connection_id_length_ = 0;
935   expected_server_connection_id_length_ = 0;
936   ASSERT_TRUE(Initialize());
937 
938   SendSynchronousFooRequestAndCheckResponse();
939   QuicConnection* client_connection = GetClientConnection();
940   ASSERT_TRUE(client_connection);
941   EXPECT_EQ(client_connection->connection_id(),
942             QuicUtils::CreateZeroConnectionId(version_.transport_version));
943 }
944 
TEST_P(EndToEndTest,BadConnectionIdLength)945 TEST_P(EndToEndTest, BadConnectionIdLength) {
946   if (!version_.AllowsVariableLengthConnectionIds()) {
947     ASSERT_TRUE(Initialize());
948     return;
949   }
950   override_server_connection_id_length_ = 9;
951   ASSERT_TRUE(Initialize());
952   SendSynchronousFooRequestAndCheckResponse();
953   EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
954                                                 ->client_session()
955                                                 ->connection()
956                                                 ->connection_id()
957                                                 .length());
958 }
959 
960 // Tests a very long (16-byte) initial destination connection ID to make
961 // sure the dispatcher properly replaces it with an 8-byte one.
TEST_P(EndToEndTest,LongBadConnectionIdLength)962 TEST_P(EndToEndTest, LongBadConnectionIdLength) {
963   if (!version_.AllowsVariableLengthConnectionIds()) {
964     ASSERT_TRUE(Initialize());
965     return;
966   }
967   override_server_connection_id_length_ = 16;
968   ASSERT_TRUE(Initialize());
969   SendSynchronousFooRequestAndCheckResponse();
970   EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
971                                                 ->client_session()
972                                                 ->connection()
973                                                 ->connection_id()
974                                                 .length());
975 }
976 
TEST_P(EndToEndTest,ClientConnectionId)977 TEST_P(EndToEndTest, ClientConnectionId) {
978   if (!version_.SupportsClientConnectionIds()) {
979     ASSERT_TRUE(Initialize());
980     return;
981   }
982   override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
983   ASSERT_TRUE(Initialize());
984   SendSynchronousFooRequestAndCheckResponse();
985   EXPECT_EQ(override_client_connection_id_length_, client_->client()
986                                                        ->client_session()
987                                                        ->connection()
988                                                        ->client_connection_id()
989                                                        .length());
990 }
991 
TEST_P(EndToEndTest,ForcedVersionNegotiationAndClientConnectionId)992 TEST_P(EndToEndTest, ForcedVersionNegotiationAndClientConnectionId) {
993   if (!version_.SupportsClientConnectionIds()) {
994     ASSERT_TRUE(Initialize());
995     return;
996   }
997   client_supported_versions_.insert(client_supported_versions_.begin(),
998                                     QuicVersionReservedForNegotiation());
999   override_client_connection_id_length_ = kQuicDefaultConnectionIdLength;
1000   ASSERT_TRUE(Initialize());
1001   ASSERT_TRUE(ServerSendsVersionNegotiation());
1002   SendSynchronousFooRequestAndCheckResponse();
1003   EXPECT_EQ(override_client_connection_id_length_, client_->client()
1004                                                        ->client_session()
1005                                                        ->connection()
1006                                                        ->client_connection_id()
1007                                                        .length());
1008 }
1009 
TEST_P(EndToEndTest,ForcedVersionNegotiationAndBadConnectionIdLength)1010 TEST_P(EndToEndTest, ForcedVersionNegotiationAndBadConnectionIdLength) {
1011   if (!version_.AllowsVariableLengthConnectionIds()) {
1012     ASSERT_TRUE(Initialize());
1013     return;
1014   }
1015   client_supported_versions_.insert(client_supported_versions_.begin(),
1016                                     QuicVersionReservedForNegotiation());
1017   override_server_connection_id_length_ = 9;
1018   ASSERT_TRUE(Initialize());
1019   ASSERT_TRUE(ServerSendsVersionNegotiation());
1020   SendSynchronousFooRequestAndCheckResponse();
1021   EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1022                                                 ->client_session()
1023                                                 ->connection()
1024                                                 ->connection_id()
1025                                                 .length());
1026 }
1027 
1028 // Forced Version Negotiation with a client connection ID and a long
1029 // connection ID.
TEST_P(EndToEndTest,ForcedVersNegoAndClientCIDAndLongCID)1030 TEST_P(EndToEndTest, ForcedVersNegoAndClientCIDAndLongCID) {
1031   if (!version_.SupportsClientConnectionIds() ||
1032       !version_.AllowsVariableLengthConnectionIds()) {
1033     ASSERT_TRUE(Initialize());
1034     return;
1035   }
1036   client_supported_versions_.insert(client_supported_versions_.begin(),
1037                                     QuicVersionReservedForNegotiation());
1038   override_server_connection_id_length_ = 16;
1039   override_client_connection_id_length_ = 18;
1040   ASSERT_TRUE(Initialize());
1041   ASSERT_TRUE(ServerSendsVersionNegotiation());
1042   SendSynchronousFooRequestAndCheckResponse();
1043   EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1044                                                 ->client_session()
1045                                                 ->connection()
1046                                                 ->connection_id()
1047                                                 .length());
1048   EXPECT_EQ(override_client_connection_id_length_, client_->client()
1049                                                        ->client_session()
1050                                                        ->connection()
1051                                                        ->client_connection_id()
1052                                                        .length());
1053 }
1054 
TEST_P(EndToEndTest,MixGoodAndBadConnectionIdLengths)1055 TEST_P(EndToEndTest, MixGoodAndBadConnectionIdLengths) {
1056   if (!version_.AllowsVariableLengthConnectionIds()) {
1057     ASSERT_TRUE(Initialize());
1058     return;
1059   }
1060 
1061   // Start client_ which will use a bad connection ID length.
1062   override_server_connection_id_length_ = 9;
1063   ASSERT_TRUE(Initialize());
1064   override_server_connection_id_length_ = -1;
1065 
1066   // Start client2 which will use a good connection ID length.
1067   std::unique_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
1068   SpdyHeaderBlock headers;
1069   headers[":method"] = "POST";
1070   headers[":path"] = "/foo";
1071   headers[":scheme"] = "https";
1072   headers[":authority"] = server_hostname_;
1073   headers["content-length"] = "3";
1074   client2->SendMessage(headers, "", /*fin=*/false);
1075   client2->SendData("eep", true);
1076 
1077   SendSynchronousFooRequestAndCheckResponse();
1078   EXPECT_EQ(kQuicDefaultConnectionIdLength, client_->client()
1079                                                 ->client_session()
1080                                                 ->connection()
1081                                                 ->connection_id()
1082                                                 .length());
1083 
1084   WaitForFooResponseAndCheckIt(client2.get());
1085   EXPECT_EQ(kQuicDefaultConnectionIdLength, client2->client()
1086                                                 ->client_session()
1087                                                 ->connection()
1088                                                 ->connection_id()
1089                                                 .length());
1090 }
1091 
TEST_P(EndToEndTest,SimpleRequestResponseWithIetfDraftSupport)1092 TEST_P(EndToEndTest, SimpleRequestResponseWithIetfDraftSupport) {
1093   if (!version_.HasIetfQuicFrames()) {
1094     ASSERT_TRUE(Initialize());
1095     return;
1096   }
1097   QuicVersionInitializeSupportForIetfDraft();
1098   ASSERT_TRUE(Initialize());
1099 
1100   SendSynchronousFooRequestAndCheckResponse();
1101 }
1102 
TEST_P(EndToEndTest,SimpleRequestResponseWithLargeReject)1103 TEST_P(EndToEndTest, SimpleRequestResponseWithLargeReject) {
1104   chlo_multiplier_ = 1;
1105   ASSERT_TRUE(Initialize());
1106 
1107   SendSynchronousFooRequestAndCheckResponse();
1108   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1109   if (version_.UsesTls()) {
1110     // REJ messages are a QUIC crypto feature, so TLS always returns false.
1111     EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1112   } else {
1113     EXPECT_TRUE(client_->client()->ReceivedInchoateReject());
1114   }
1115 }
1116 
TEST_P(EndToEndTest,SimpleRequestResponsev6)1117 TEST_P(EndToEndTest, SimpleRequestResponsev6) {
1118   server_address_ =
1119       QuicSocketAddress(QuicIpAddress::Loopback6(), server_address_.port());
1120   ASSERT_TRUE(Initialize());
1121 
1122   SendSynchronousFooRequestAndCheckResponse();
1123 }
1124 
TEST_P(EndToEndTest,ClientDoesNotAllowServerDataOnServerInitiatedBidirectionalStreams)1125 TEST_P(EndToEndTest,
1126        ClientDoesNotAllowServerDataOnServerInitiatedBidirectionalStreams) {
1127   set_client_initial_max_stream_data_incoming_bidirectional(0);
1128   ASSERT_TRUE(Initialize());
1129   SendSynchronousFooRequestAndCheckResponse();
1130 }
1131 
TEST_P(EndToEndTest,ServerDoesNotAllowClientDataOnServerInitiatedBidirectionalStreams)1132 TEST_P(EndToEndTest,
1133        ServerDoesNotAllowClientDataOnServerInitiatedBidirectionalStreams) {
1134   set_server_initial_max_stream_data_outgoing_bidirectional(0);
1135   ASSERT_TRUE(Initialize());
1136   SendSynchronousFooRequestAndCheckResponse();
1137 }
1138 
TEST_P(EndToEndTest,BothEndpointsDisallowDataOnServerInitiatedBidirectionalStreams)1139 TEST_P(EndToEndTest,
1140        BothEndpointsDisallowDataOnServerInitiatedBidirectionalStreams) {
1141   set_client_initial_max_stream_data_incoming_bidirectional(0);
1142   set_server_initial_max_stream_data_outgoing_bidirectional(0);
1143   ASSERT_TRUE(Initialize());
1144   SendSynchronousFooRequestAndCheckResponse();
1145 }
1146 
1147 // Regression test for a bug where we would always fail to decrypt the first
1148 // initial packet. Undecryptable packets can be seen after the handshake
1149 // is complete due to dropping the initial keys at that point, so we only test
1150 // for undecryptable packets before then.
TEST_P(EndToEndTest,NoUndecryptablePacketsBeforeHandshakeComplete)1151 TEST_P(EndToEndTest, NoUndecryptablePacketsBeforeHandshakeComplete) {
1152   ASSERT_TRUE(Initialize());
1153 
1154   SendSynchronousFooRequestAndCheckResponse();
1155 
1156   QuicConnection* client_connection = GetClientConnection();
1157   ASSERT_TRUE(client_connection);
1158   QuicConnectionStats client_stats = client_connection->GetStats();
1159   EXPECT_EQ(
1160       0u,
1161       client_stats.undecryptable_packets_received_before_handshake_complete);
1162 
1163   server_thread_->Pause();
1164   QuicConnection* server_connection = GetServerConnection();
1165   if (server_connection != nullptr) {
1166     QuicConnectionStats server_stats = server_connection->GetStats();
1167     EXPECT_EQ(
1168         0u,
1169         server_stats.undecryptable_packets_received_before_handshake_complete);
1170   } else {
1171     ADD_FAILURE() << "Missing server connection";
1172   }
1173   server_thread_->Resume();
1174 }
1175 
TEST_P(EndToEndTest,SeparateFinPacket)1176 TEST_P(EndToEndTest, SeparateFinPacket) {
1177   ASSERT_TRUE(Initialize());
1178 
1179   // Send a request in two parts: the request and then an empty packet with FIN.
1180   SpdyHeaderBlock headers;
1181   headers[":method"] = "POST";
1182   headers[":path"] = "/foo";
1183   headers[":scheme"] = "https";
1184   headers[":authority"] = server_hostname_;
1185   client_->SendMessage(headers, "", /*fin=*/false);
1186   client_->SendData("", true);
1187   WaitForFooResponseAndCheckIt();
1188 
1189   // Now do the same thing but with a content length.
1190   headers["content-length"] = "3";
1191   client_->SendMessage(headers, "", /*fin=*/false);
1192   client_->SendData("foo", true);
1193   WaitForFooResponseAndCheckIt();
1194 }
1195 
TEST_P(EndToEndTest,MultipleRequestResponse)1196 TEST_P(EndToEndTest, MultipleRequestResponse) {
1197   ASSERT_TRUE(Initialize());
1198 
1199   SendSynchronousFooRequestAndCheckResponse();
1200   SendSynchronousBarRequestAndCheckResponse();
1201 }
1202 
TEST_P(EndToEndTest,MultipleRequestResponseZeroConnectionID)1203 TEST_P(EndToEndTest, MultipleRequestResponseZeroConnectionID) {
1204   if (!version_.AllowsVariableLengthConnectionIds()) {
1205     ASSERT_TRUE(Initialize());
1206     return;
1207   }
1208   override_server_connection_id_length_ = 0;
1209   expected_server_connection_id_length_ = 0;
1210   ASSERT_TRUE(Initialize());
1211 
1212   SendSynchronousFooRequestAndCheckResponse();
1213   SendSynchronousBarRequestAndCheckResponse();
1214 }
1215 
TEST_P(EndToEndTest,MultipleStreams)1216 TEST_P(EndToEndTest, MultipleStreams) {
1217   // Verifies quic_test_client can track responses of all active streams.
1218   ASSERT_TRUE(Initialize());
1219 
1220   const int kNumRequests = 10;
1221 
1222   SpdyHeaderBlock headers;
1223   headers[":method"] = "POST";
1224   headers[":path"] = "/foo";
1225   headers[":scheme"] = "https";
1226   headers[":authority"] = server_hostname_;
1227   headers["content-length"] = "3";
1228 
1229   for (int i = 0; i < kNumRequests; ++i) {
1230     client_->SendMessage(headers, "bar", /*fin=*/true);
1231   }
1232 
1233   while (kNumRequests > client_->num_responses()) {
1234     client_->ClearPerRequestState();
1235     ASSERT_TRUE(WaitForFooResponseAndCheckIt());
1236   }
1237 }
1238 
TEST_P(EndToEndTest,MultipleClients)1239 TEST_P(EndToEndTest, MultipleClients) {
1240   ASSERT_TRUE(Initialize());
1241   std::unique_ptr<QuicTestClient> client2(CreateQuicClient(nullptr));
1242 
1243   SpdyHeaderBlock headers;
1244   headers[":method"] = "POST";
1245   headers[":path"] = "/foo";
1246   headers[":scheme"] = "https";
1247   headers[":authority"] = server_hostname_;
1248   headers["content-length"] = "3";
1249 
1250   client_->SendMessage(headers, "", /*fin=*/false);
1251   client2->SendMessage(headers, "", /*fin=*/false);
1252 
1253   client_->SendData("bar", true);
1254   WaitForFooResponseAndCheckIt();
1255 
1256   client2->SendData("eep", true);
1257   WaitForFooResponseAndCheckIt(client2.get());
1258 }
1259 
TEST_P(EndToEndTest,RequestOverMultiplePackets)1260 TEST_P(EndToEndTest, RequestOverMultiplePackets) {
1261   // Send a large enough request to guarantee fragmentation.
1262   std::string huge_request =
1263       "/some/path?query=" + std::string(kMaxOutgoingPacketSize, '.');
1264   AddToCache(huge_request, 200, kBarResponseBody);
1265 
1266   ASSERT_TRUE(Initialize());
1267 
1268   SendSynchronousRequestAndCheckResponse(huge_request, kBarResponseBody);
1269 }
1270 
TEST_P(EndToEndTest,MultiplePacketsRandomOrder)1271 TEST_P(EndToEndTest, MultiplePacketsRandomOrder) {
1272   // Send a large enough request to guarantee fragmentation.
1273   std::string huge_request =
1274       "/some/path?query=" + std::string(kMaxOutgoingPacketSize, '.');
1275   AddToCache(huge_request, 200, kBarResponseBody);
1276 
1277   ASSERT_TRUE(Initialize());
1278   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
1279   SetReorderPercentage(50);
1280 
1281   SendSynchronousRequestAndCheckResponse(huge_request, kBarResponseBody);
1282 }
1283 
TEST_P(EndToEndTest,PostMissingBytes)1284 TEST_P(EndToEndTest, PostMissingBytes) {
1285   ASSERT_TRUE(Initialize());
1286 
1287   // Add a content length header with no body.
1288   SpdyHeaderBlock headers;
1289   headers[":method"] = "POST";
1290   headers[":path"] = "/foo";
1291   headers[":scheme"] = "https";
1292   headers[":authority"] = server_hostname_;
1293   headers["content-length"] = "3";
1294 
1295   // This should be detected as stream fin without complete request,
1296   // triggering an error response.
1297   client_->SendCustomSynchronousRequest(headers, "");
1298   EXPECT_EQ(QuicSimpleServerStream::kErrorResponseBody,
1299             client_->response_body());
1300   CheckResponseHeaders("500");
1301 }
1302 
TEST_P(EndToEndTest,LargePostNoPacketLoss)1303 TEST_P(EndToEndTest, LargePostNoPacketLoss) {
1304   ASSERT_TRUE(Initialize());
1305 
1306   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1307 
1308   // 1 MB body.
1309   std::string body(1024 * 1024, 'a');
1310   SpdyHeaderBlock headers;
1311   headers[":method"] = "POST";
1312   headers[":path"] = "/foo";
1313   headers[":scheme"] = "https";
1314   headers[":authority"] = server_hostname_;
1315 
1316   EXPECT_EQ(kFooResponseBody,
1317             client_->SendCustomSynchronousRequest(headers, body));
1318   // TODO(ianswett): There should not be packet loss in this test, but on some
1319   // platforms the receive buffer overflows.
1320   VerifyCleanConnection(true);
1321 }
1322 
TEST_P(EndToEndTest,LargePostNoPacketLoss1sRTT)1323 TEST_P(EndToEndTest, LargePostNoPacketLoss1sRTT) {
1324   ASSERT_TRUE(Initialize());
1325   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(1000));
1326 
1327   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1328 
1329   // 100 KB body.
1330   std::string body(100 * 1024, 'a');
1331   SpdyHeaderBlock headers;
1332   headers[":method"] = "POST";
1333   headers[":path"] = "/foo";
1334   headers[":scheme"] = "https";
1335   headers[":authority"] = server_hostname_;
1336 
1337   EXPECT_EQ(kFooResponseBody,
1338             client_->SendCustomSynchronousRequest(headers, body));
1339   VerifyCleanConnection(false);
1340 }
1341 
TEST_P(EndToEndTest,LargePostWithPacketLoss)1342 TEST_P(EndToEndTest, LargePostWithPacketLoss) {
1343   // Connect with lower fake packet loss than we'd like to test.
1344   // Until b/10126687 is fixed, losing handshake packets is pretty
1345   // brutal.
1346   // Disable blackhole detection as this test is testing loss recovery.
1347   client_extra_copts_.push_back(kNBHD);
1348   SetPacketLossPercentage(5);
1349   ASSERT_TRUE(Initialize());
1350   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1351   SetPacketLossPercentage(30);
1352 
1353   // 10 KB body.
1354   std::string body(1024 * 10, 'a');
1355   SpdyHeaderBlock headers;
1356   headers[":method"] = "POST";
1357   headers[":path"] = "/foo";
1358   headers[":scheme"] = "https";
1359   headers[":authority"] = server_hostname_;
1360 
1361   EXPECT_EQ(kFooResponseBody,
1362             client_->SendCustomSynchronousRequest(headers, body));
1363   VerifyCleanConnection(true);
1364 }
1365 
1366 // Regression test for b/80090281.
TEST_P(EndToEndTest,LargePostWithPacketLossAndAlwaysBundleWindowUpdates)1367 TEST_P(EndToEndTest, LargePostWithPacketLossAndAlwaysBundleWindowUpdates) {
1368   // Disable blackhole detection as this test is testing loss recovery.
1369   client_extra_copts_.push_back(kNBHD);
1370   ASSERT_TRUE(Initialize());
1371   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1372   server_thread_->WaitForCryptoHandshakeConfirmed();
1373 
1374   // Normally server only bundles a retransmittable frame once every other
1375   // kMaxConsecutiveNonRetransmittablePackets ack-only packets. Setting the max
1376   // to 0 to reliably reproduce b/80090281.
1377   server_thread_->Schedule([this]() {
1378     QuicConnection* server_connection = GetServerConnection();
1379     if (server_connection != nullptr) {
1380       QuicConnectionPeer::
1381           SetMaxConsecutiveNumPacketsWithNoRetransmittableFrames(
1382               server_connection, 0);
1383     } else {
1384       ADD_FAILURE() << "Missing server connection";
1385     }
1386   });
1387 
1388   SetPacketLossPercentage(30);
1389 
1390   // 10 KB body.
1391   std::string body(1024 * 10, 'a');
1392   SpdyHeaderBlock headers;
1393   headers[":method"] = "POST";
1394   headers[":path"] = "/foo";
1395   headers[":scheme"] = "https";
1396   headers[":authority"] = server_hostname_;
1397 
1398   EXPECT_EQ(kFooResponseBody,
1399             client_->SendCustomSynchronousRequest(headers, body));
1400   VerifyCleanConnection(true);
1401 }
1402 
TEST_P(EndToEndTest,LargePostWithPacketLossAndBlockedSocket)1403 TEST_P(EndToEndTest, LargePostWithPacketLossAndBlockedSocket) {
1404   // Connect with lower fake packet loss than we'd like to test.  Until
1405   // b/10126687 is fixed, losing handshake packets is pretty brutal.
1406   // Disable blackhole detection as this test is testing loss recovery.
1407   client_extra_copts_.push_back(kNBHD);
1408   SetPacketLossPercentage(5);
1409   ASSERT_TRUE(Initialize());
1410   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1411   SetPacketLossPercentage(10);
1412   client_writer_->set_fake_blocked_socket_percentage(10);
1413 
1414   // 10 KB body.
1415   std::string body(1024 * 10, 'a');
1416   SpdyHeaderBlock headers;
1417   headers[":method"] = "POST";
1418   headers[":path"] = "/foo";
1419   headers[":scheme"] = "https";
1420   headers[":authority"] = server_hostname_;
1421 
1422   EXPECT_EQ(kFooResponseBody,
1423             client_->SendCustomSynchronousRequest(headers, body));
1424 }
1425 
TEST_P(EndToEndTest,LargePostNoPacketLossWithDelayAndReordering)1426 TEST_P(EndToEndTest, LargePostNoPacketLossWithDelayAndReordering) {
1427   ASSERT_TRUE(Initialize());
1428   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
1429   // Both of these must be called when the writer is not actively used.
1430   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
1431   SetReorderPercentage(30);
1432 
1433   // 1 MB body.
1434   std::string body(1024 * 1024, 'a');
1435   SpdyHeaderBlock headers;
1436   headers[":method"] = "POST";
1437   headers[":path"] = "/foo";
1438   headers[":scheme"] = "https";
1439   headers[":authority"] = server_hostname_;
1440 
1441   EXPECT_EQ(kFooResponseBody,
1442             client_->SendCustomSynchronousRequest(headers, body));
1443 }
1444 
TEST_P(EndToEndTest,LargePostZeroRTTFailure)1445 TEST_P(EndToEndTest, LargePostZeroRTTFailure) {
1446   // Send a request and then disconnect. This prepares the client to attempt
1447   // a 0-RTT handshake for the next request.
1448   ASSERT_TRUE(Initialize());
1449 
1450   std::string body(20480, 'a');
1451   SpdyHeaderBlock headers;
1452   headers[":method"] = "POST";
1453   headers[":path"] = "/foo";
1454   headers[":scheme"] = "https";
1455   headers[":authority"] = server_hostname_;
1456 
1457   EXPECT_EQ(kFooResponseBody,
1458             client_->SendCustomSynchronousRequest(headers, body));
1459   QuicSpdyClientSession* client_session = GetClientSession();
1460   ASSERT_TRUE(client_session);
1461   EXPECT_FALSE(client_session->EarlyDataAccepted());
1462   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1463   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1464   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1465 
1466   client_->Disconnect();
1467 
1468   // The 0-RTT handshake should succeed.
1469   client_->Connect();
1470   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1471   ASSERT_TRUE(client_->client()->connected());
1472   EXPECT_EQ(kFooResponseBody,
1473             client_->SendCustomSynchronousRequest(headers, body));
1474 
1475   client_session = GetClientSession();
1476   ASSERT_TRUE(client_session);
1477   EXPECT_TRUE(client_session->EarlyDataAccepted());
1478   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1479 
1480   client_->Disconnect();
1481 
1482   // Restart the server so that the 0-RTT handshake will take 1 RTT.
1483   StopServer();
1484   server_writer_ = new PacketDroppingTestWriter();
1485   StartServer();
1486 
1487   client_->Connect();
1488   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1489   ASSERT_TRUE(client_->client()->connected());
1490   EXPECT_EQ(kFooResponseBody,
1491             client_->SendCustomSynchronousRequest(headers, body));
1492   client_session = GetClientSession();
1493   ASSERT_TRUE(client_session);
1494   EXPECT_FALSE(client_session->EarlyDataAccepted());
1495   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1496   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1497   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1498   VerifyCleanConnection(false);
1499 }
1500 
1501 // Regression test for b/168020146.
1502 // TODO(renjietang): Reenable this test in Chrome once the BoringSSL fix is
1503 // rolled in.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (MultipleZeroRtt))1504 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(MultipleZeroRtt)) {
1505   ASSERT_TRUE(Initialize());
1506 
1507   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1508   QuicSpdyClientSession* client_session = GetClientSession();
1509   ASSERT_TRUE(client_session);
1510   EXPECT_FALSE(client_session->EarlyDataAccepted());
1511   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1512   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1513   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1514 
1515   client_->Disconnect();
1516 
1517   // The 0-RTT handshake should succeed.
1518   client_->Connect();
1519   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1520   ASSERT_TRUE(client_->client()->connected());
1521   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1522 
1523   client_session = GetClientSession();
1524   ASSERT_TRUE(client_session);
1525   EXPECT_TRUE(client_session->EarlyDataAccepted());
1526   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1527 
1528   client_->Disconnect();
1529 
1530   client_->Connect();
1531   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1532   ASSERT_TRUE(client_->client()->connected());
1533   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1534 
1535   client_session = GetClientSession();
1536   ASSERT_TRUE(client_session);
1537   EXPECT_TRUE(client_session->EarlyDataAccepted());
1538   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1539 
1540   client_->Disconnect();
1541 }
1542 
TEST_P(EndToEndTest,SynchronousRequestZeroRTTFailure)1543 TEST_P(EndToEndTest, SynchronousRequestZeroRTTFailure) {
1544   // Send a request and then disconnect. This prepares the client to attempt
1545   // a 0-RTT handshake for the next request.
1546   ASSERT_TRUE(Initialize());
1547 
1548   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1549   QuicSpdyClientSession* client_session = GetClientSession();
1550   ASSERT_TRUE(client_session);
1551   EXPECT_FALSE(client_session->EarlyDataAccepted());
1552   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1553   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1554   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1555 
1556   client_->Disconnect();
1557 
1558   // The 0-RTT handshake should succeed.
1559   client_->Connect();
1560   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1561   ASSERT_TRUE(client_->client()->connected());
1562   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1563 
1564   client_session = GetClientSession();
1565   ASSERT_TRUE(client_session);
1566   EXPECT_TRUE(client_session->EarlyDataAccepted());
1567   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1568 
1569   client_->Disconnect();
1570 
1571   // Restart the server so that the 0-RTT handshake will take 1 RTT.
1572   StopServer();
1573   server_writer_ = new PacketDroppingTestWriter();
1574   StartServer();
1575 
1576   client_->Connect();
1577   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1578   ASSERT_TRUE(client_->client()->connected());
1579   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1580 
1581   client_session = GetClientSession();
1582   ASSERT_TRUE(client_session);
1583   EXPECT_FALSE(client_session->EarlyDataAccepted());
1584   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1585   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1586   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1587 
1588   VerifyCleanConnection(false);
1589 }
1590 
TEST_P(EndToEndTest,LargePostSynchronousRequest)1591 TEST_P(EndToEndTest, LargePostSynchronousRequest) {
1592   // Send a request and then disconnect. This prepares the client to attempt
1593   // a 0-RTT handshake for the next request.
1594   ASSERT_TRUE(Initialize());
1595 
1596   std::string body(20480, 'a');
1597   SpdyHeaderBlock headers;
1598   headers[":method"] = "POST";
1599   headers[":path"] = "/foo";
1600   headers[":scheme"] = "https";
1601   headers[":authority"] = server_hostname_;
1602 
1603   EXPECT_EQ(kFooResponseBody,
1604             client_->SendCustomSynchronousRequest(headers, body));
1605   QuicSpdyClientSession* client_session = GetClientSession();
1606   ASSERT_TRUE(client_session);
1607   EXPECT_FALSE(client_session->EarlyDataAccepted());
1608   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1609   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1610   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1611 
1612   client_->Disconnect();
1613 
1614   // The 0-RTT handshake should succeed.
1615   client_->Connect();
1616   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1617   ASSERT_TRUE(client_->client()->connected());
1618   EXPECT_EQ(kFooResponseBody,
1619             client_->SendCustomSynchronousRequest(headers, body));
1620 
1621   client_session = GetClientSession();
1622   ASSERT_TRUE(client_session);
1623   EXPECT_TRUE(client_session->EarlyDataAccepted());
1624   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1625 
1626   client_->Disconnect();
1627 
1628   // Restart the server so that the 0-RTT handshake will take 1 RTT.
1629   StopServer();
1630   server_writer_ = new PacketDroppingTestWriter();
1631   StartServer();
1632 
1633   client_->Connect();
1634   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1635   ASSERT_TRUE(client_->client()->connected());
1636   EXPECT_EQ(kFooResponseBody,
1637             client_->SendCustomSynchronousRequest(headers, body));
1638 
1639   client_session = GetClientSession();
1640   ASSERT_TRUE(client_session);
1641   EXPECT_FALSE(client_session->EarlyDataAccepted());
1642   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1643   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1644   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1645 
1646   VerifyCleanConnection(false);
1647 }
1648 
1649 // This is a regression test for b/162595387
TEST_P(EndToEndTest,PostZeroRTTRequestDuringHandshake)1650 TEST_P(EndToEndTest, PostZeroRTTRequestDuringHandshake) {
1651   if (!version_.UsesTls()) {
1652     // This test is TLS specific.
1653     ASSERT_TRUE(Initialize());
1654     return;
1655   }
1656   // Send a request and then disconnect. This prepares the client to attempt
1657   // a 0-RTT handshake for the next request.
1658   NiceMock<MockQuicConnectionDebugVisitor> visitor;
1659   connection_debug_visitor_ = &visitor;
1660   ASSERT_TRUE(Initialize());
1661 
1662   SendSynchronousFooRequestAndCheckResponse();
1663   QuicSpdyClientSession* client_session = GetClientSession();
1664   ASSERT_TRUE(client_session);
1665   EXPECT_FALSE(client_session->EarlyDataAccepted());
1666   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1667   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1668   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1669 
1670   client_->Disconnect();
1671 
1672   // The 0-RTT handshake should succeed.
1673   ON_CALL(visitor, OnCryptoFrame(_))
1674       .WillByDefault(Invoke([this](const QuicCryptoFrame& frame) {
1675         if (frame.level != ENCRYPTION_HANDSHAKE) {
1676           return;
1677         }
1678         // At this point in the handshake, the client should have derived
1679         // ENCRYPTION_ZERO_RTT keys (thus set encryption_established). It
1680         // should also have set ENCRYPTION_HANDSHAKE keys after receiving
1681         // the server's ENCRYPTION_INITIAL flight.
1682         EXPECT_TRUE(
1683             GetClientSession()->GetCryptoStream()->encryption_established());
1684         EXPECT_TRUE(
1685             GetClientConnection()->framer().HasEncrypterOfEncryptionLevel(
1686                 ENCRYPTION_HANDSHAKE));
1687         SpdyHeaderBlock headers;
1688         headers[":method"] = "POST";
1689         headers[":path"] = "/foo";
1690         headers[":scheme"] = "https";
1691         headers[":authority"] = server_hostname_;
1692         EXPECT_GT(
1693             client_->SendMessage(headers, "", /*fin*/ true, /*flush*/ false),
1694             0);
1695       }));
1696   client_->Connect();
1697   ASSERT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1698   client_->WaitForWriteToFlush();
1699   client_->WaitForResponse();
1700   ASSERT_TRUE(client_->client()->connected());
1701   EXPECT_EQ(kFooResponseBody, client_->response_body());
1702 
1703   client_session = GetClientSession();
1704   ASSERT_TRUE(client_session);
1705   EXPECT_TRUE(client_session->EarlyDataAccepted());
1706   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1707 }
1708 
1709 // Regression test for b/166836136.
TEST_P(EndToEndTest,RetransmissionAfterZeroRTTRejectBeforeOneRtt)1710 TEST_P(EndToEndTest, RetransmissionAfterZeroRTTRejectBeforeOneRtt) {
1711   if (!version_.UsesTls()) {
1712     // This test is TLS specific.
1713     ASSERT_TRUE(Initialize());
1714     return;
1715   }
1716   // Send a request and then disconnect. This prepares the client to attempt
1717   // a 0-RTT handshake for the next request.
1718   NiceMock<MockQuicConnectionDebugVisitor> visitor;
1719   connection_debug_visitor_ = &visitor;
1720   ASSERT_TRUE(Initialize());
1721 
1722   SendSynchronousFooRequestAndCheckResponse();
1723   QuicSpdyClientSession* client_session = GetClientSession();
1724   ASSERT_TRUE(client_session);
1725   EXPECT_FALSE(client_session->EarlyDataAccepted());
1726   EXPECT_FALSE(client_session->ReceivedInchoateReject());
1727   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1728   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
1729 
1730   client_->Disconnect();
1731 
1732   client_->Connect();
1733   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1734   ASSERT_TRUE(client_->client()->connected());
1735   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
1736 
1737   client_session = GetClientSession();
1738   ASSERT_TRUE(client_session);
1739   EXPECT_TRUE(client_session->EarlyDataAccepted());
1740   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
1741 
1742   client_->Disconnect();
1743 
1744   // Restart the server so that the 0-RTT handshake will take 1 RTT.
1745   StopServer();
1746   server_writer_ = new PacketDroppingTestWriter();
1747   StartServer();
1748 
1749   ON_CALL(visitor, OnZeroRttRejected(_)).WillByDefault(Invoke([this]() {
1750     EXPECT_FALSE(GetClientSession()->IsEncryptionEstablished());
1751     // Trigger an OnCanWrite() to make sure no unencrypted data will be written.
1752     GetClientSession()->OnCanWrite();
1753   }));
1754 
1755   // The 0-RTT handshake should fail.
1756   client_->Connect();
1757   ASSERT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1758   client_->WaitForWriteToFlush();
1759   client_->WaitForResponse();
1760   ASSERT_TRUE(client_->client()->connected());
1761 
1762   client_session = GetClientSession();
1763   ASSERT_TRUE(client_session);
1764   EXPECT_FALSE(client_session->EarlyDataAccepted());
1765   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
1766 }
1767 
TEST_P(EndToEndTest,RejectWithPacketLoss)1768 TEST_P(EndToEndTest, RejectWithPacketLoss) {
1769   // In this test, we intentionally drop the first packet from the
1770   // server, which corresponds with the initial REJ response from
1771   // the server.
1772   server_writer_->set_fake_drop_first_n_packets(1);
1773   ASSERT_TRUE(Initialize());
1774 }
1775 
TEST_P(EndToEndTest,SetInitialReceivedConnectionOptions)1776 TEST_P(EndToEndTest, SetInitialReceivedConnectionOptions) {
1777   QuicTagVector initial_received_options;
1778   initial_received_options.push_back(kTBBR);
1779   initial_received_options.push_back(kIW10);
1780   initial_received_options.push_back(kPRST);
1781   EXPECT_TRUE(server_config_.SetInitialReceivedConnectionOptions(
1782       initial_received_options));
1783 
1784   ASSERT_TRUE(Initialize());
1785   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1786   server_thread_->WaitForCryptoHandshakeConfirmed();
1787 
1788   EXPECT_FALSE(server_config_.SetInitialReceivedConnectionOptions(
1789       initial_received_options));
1790 
1791   // Verify that server's configuration is correct.
1792   server_thread_->Pause();
1793   EXPECT_TRUE(server_config_.HasReceivedConnectionOptions());
1794   EXPECT_TRUE(
1795       ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kTBBR));
1796   EXPECT_TRUE(
1797       ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kIW10));
1798   EXPECT_TRUE(
1799       ContainsQuicTag(server_config_.ReceivedConnectionOptions(), kPRST));
1800 }
1801 
TEST_P(EndToEndTest,LargePostSmallBandwidthLargeBuffer)1802 TEST_P(EndToEndTest, LargePostSmallBandwidthLargeBuffer) {
1803   ASSERT_TRUE(Initialize());
1804   SetPacketSendDelay(QuicTime::Delta::FromMicroseconds(1));
1805   // 256KB per second with a 256KB buffer from server to client.  Wireless
1806   // clients commonly have larger buffers, but our max CWND is 200.
1807   server_writer_->set_max_bandwidth_and_buffer_size(
1808       QuicBandwidth::FromBytesPerSecond(256 * 1024), 256 * 1024);
1809 
1810   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1811 
1812   // 1 MB body.
1813   std::string body(1024 * 1024, 'a');
1814   SpdyHeaderBlock headers;
1815   headers[":method"] = "POST";
1816   headers[":path"] = "/foo";
1817   headers[":scheme"] = "https";
1818   headers[":authority"] = server_hostname_;
1819 
1820   EXPECT_EQ(kFooResponseBody,
1821             client_->SendCustomSynchronousRequest(headers, body));
1822   // This connection may drop packets, because the buffer is smaller than the
1823   // max CWND.
1824   VerifyCleanConnection(true);
1825 }
1826 
TEST_P(EndToEndTest,DoNotSetSendAlarmIfConnectionFlowControlBlocked)1827 TEST_P(EndToEndTest, DoNotSetSendAlarmIfConnectionFlowControlBlocked) {
1828   // Regression test for b/14677858.
1829   // Test that the resume write alarm is not set in QuicConnection::OnCanWrite
1830   // if currently connection level flow control blocked. If set, this results in
1831   // an infinite loop in the EpollServer, as the alarm fires and is immediately
1832   // rescheduled.
1833   ASSERT_TRUE(Initialize());
1834   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1835 
1836   // Ensure both stream and connection level are flow control blocked by setting
1837   // the send window offset to 0.
1838   const uint64_t flow_control_window =
1839       server_config_.GetInitialStreamFlowControlWindowToSend();
1840   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1841   QuicSession* session = GetClientSession();
1842   ASSERT_TRUE(session);
1843   QuicStreamPeer::SetSendWindowOffset(stream, 0);
1844   QuicFlowControllerPeer::SetSendWindowOffset(session->flow_controller(), 0);
1845   EXPECT_TRUE(stream->IsFlowControlBlocked());
1846   EXPECT_TRUE(session->flow_controller()->IsBlocked());
1847 
1848   // Make sure that the stream has data pending so that it will be marked as
1849   // write blocked when it receives a stream level WINDOW_UPDATE.
1850   stream->WriteOrBufferBody("hello", false);
1851 
1852   // The stream now attempts to write, fails because it is still connection
1853   // level flow control blocked, and is added to the write blocked list.
1854   QuicWindowUpdateFrame window_update(kInvalidControlFrameId, stream->id(),
1855                                       2 * flow_control_window);
1856   stream->OnWindowUpdateFrame(window_update);
1857 
1858   // Prior to fixing b/14677858 this call would result in an infinite loop in
1859   // Chromium. As a proxy for detecting this, we now check whether the
1860   // send alarm is set after OnCanWrite. It should not be, as the
1861   // connection is still flow control blocked.
1862   session->connection()->OnCanWrite();
1863 
1864   QuicAlarm* send_alarm =
1865       QuicConnectionPeer::GetSendAlarm(session->connection());
1866   EXPECT_FALSE(send_alarm->IsSet());
1867 }
1868 
TEST_P(EndToEndTest,InvalidStream)1869 TEST_P(EndToEndTest, InvalidStream) {
1870   ASSERT_TRUE(Initialize());
1871   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1872 
1873   std::string body(kMaxOutgoingPacketSize, 'a');
1874   SpdyHeaderBlock headers;
1875   headers[":method"] = "POST";
1876   headers[":path"] = "/foo";
1877   headers[":scheme"] = "https";
1878   headers[":authority"] = server_hostname_;
1879 
1880   // Force the client to write with a stream ID belonging to a nonexistent
1881   // server-side stream.
1882   QuicSpdySession* session = GetClientSession();
1883   ASSERT_TRUE(session);
1884   QuicSessionPeer::SetNextOutgoingBidirectionalStreamId(
1885       session, GetNthServerInitiatedBidirectionalId(0));
1886 
1887   client_->SendCustomSynchronousRequest(headers, body);
1888   EXPECT_THAT(client_->stream_error(),
1889               IsStreamError(QUIC_STREAM_CONNECTION_ERROR));
1890   EXPECT_THAT(client_->connection_error(), IsError(QUIC_INVALID_STREAM_ID));
1891 }
1892 
1893 // Test that the server resets the stream if the client sends a request
1894 // with overly large headers.
TEST_P(EndToEndTest,LargeHeaders)1895 TEST_P(EndToEndTest, LargeHeaders) {
1896   ASSERT_TRUE(Initialize());
1897   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1898 
1899   std::string body(kMaxOutgoingPacketSize, 'a');
1900   SpdyHeaderBlock headers;
1901   headers[":method"] = "POST";
1902   headers[":path"] = "/foo";
1903   headers[":scheme"] = "https";
1904   headers[":authority"] = server_hostname_;
1905   headers["key1"] = std::string(15 * 1024, 'a');
1906   headers["key2"] = std::string(15 * 1024, 'a');
1907   headers["key3"] = std::string(15 * 1024, 'a');
1908 
1909   client_->SendCustomSynchronousRequest(headers, body);
1910 
1911   if (version_.UsesHttp3()) {
1912     // QuicSpdyStream::OnHeadersTooLarge() resets the stream with
1913     // QUIC_HEADERS_TOO_LARGE.  This is sent as H3_EXCESSIVE_LOAD, the closest
1914     // HTTP/3 error code, and translated back to QUIC_STREAM_EXCESSIVE_LOAD on
1915     // the receiving side.
1916     EXPECT_THAT(client_->stream_error(),
1917                 IsStreamError(QUIC_STREAM_EXCESSIVE_LOAD));
1918   } else {
1919     EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_HEADERS_TOO_LARGE));
1920   }
1921   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
1922 }
1923 
TEST_P(EndToEndTest,EarlyResponseWithQuicStreamNoError)1924 TEST_P(EndToEndTest, EarlyResponseWithQuicStreamNoError) {
1925   ASSERT_TRUE(Initialize());
1926   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1927 
1928   std::string large_body(1024 * 1024, 'a');
1929   SpdyHeaderBlock headers;
1930   headers[":method"] = "POST";
1931   headers[":path"] = "/foo";
1932   headers[":scheme"] = "https";
1933   headers[":authority"] = server_hostname_;
1934   // Insert an invalid content_length field in request to trigger an early
1935   // response from server.
1936   headers["content-length"] = "-3";
1937 
1938   client_->SendCustomSynchronousRequest(headers, large_body);
1939   EXPECT_EQ("bad", client_->response_body());
1940   CheckResponseHeaders("500");
1941   EXPECT_THAT(client_->stream_error(), IsQuicStreamNoError());
1942   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
1943 }
1944 
1945 // TODO(rch): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (MultipleTermination))1946 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(MultipleTermination)) {
1947   ASSERT_TRUE(Initialize());
1948 
1949   // Set the offset so we won't frame.  Otherwise when we pick up termination
1950   // before HTTP framing is complete, we send an error and close the stream,
1951   // and the second write is picked up as writing on a closed stream.
1952   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
1953   ASSERT_TRUE(stream != nullptr);
1954   QuicStreamPeer::SetStreamBytesWritten(3, stream);
1955 
1956   client_->SendData("bar", true);
1957   client_->WaitForWriteToFlush();
1958 
1959   // By default the stream protects itself from writes after terminte is set.
1960   // Override this to test the server handling buggy clients.
1961   QuicStreamPeer::SetWriteSideClosed(false, client_->GetOrCreateStream());
1962 
1963   EXPECT_QUIC_BUG(client_->SendData("eep", true), "Fin already buffered");
1964 }
1965 
TEST_P(EndToEndTest,Timeout)1966 TEST_P(EndToEndTest, Timeout) {
1967   client_config_.SetIdleNetworkTimeout(QuicTime::Delta::FromMicroseconds(500));
1968   // Note: we do NOT ASSERT_TRUE: we may time out during initial handshake:
1969   // that's enough to validate timeout in this case.
1970   Initialize();
1971   while (client_->client()->connected()) {
1972     client_->client()->WaitForEvents();
1973   }
1974 }
1975 
TEST_P(EndToEndTest,MaxDynamicStreamsLimitRespected)1976 TEST_P(EndToEndTest, MaxDynamicStreamsLimitRespected) {
1977   // Set a limit on maximum number of incoming dynamic streams.
1978   // Make sure the limit is respected by the peer.
1979   const uint32_t kServerMaxDynamicStreams = 1;
1980   server_config_.SetMaxBidirectionalStreamsToSend(kServerMaxDynamicStreams);
1981   ASSERT_TRUE(Initialize());
1982   if (version_.HasIetfQuicFrames()) {
1983     // Do not run this test for /IETF QUIC. This test relies on the fact that
1984     // Google QUIC allows a small number of additional streams beyond the
1985     // negotiated limit, which is not supported in IETF QUIC. Note that the test
1986     // needs to be here, after calling Initialize(), because all tests end up
1987     // calling EndToEndTest::TearDown(), which asserts that Initialize has been
1988     // called and then proceeds to tear things down -- which fails if they are
1989     // not properly set up.
1990     return;
1991   }
1992   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
1993 
1994   // Make the client misbehave after negotiation.
1995   const int kServerMaxStreams = kMaxStreamsMinimumIncrement + 1;
1996   QuicSpdyClientSession* client_session = GetClientSession();
1997   ASSERT_TRUE(client_session);
1998   QuicSessionPeer::SetMaxOpenOutgoingStreams(client_session,
1999                                              kServerMaxStreams + 1);
2000 
2001   SpdyHeaderBlock headers;
2002   headers[":method"] = "POST";
2003   headers[":path"] = "/foo";
2004   headers[":scheme"] = "https";
2005   headers[":authority"] = server_hostname_;
2006   headers["content-length"] = "3";
2007 
2008   // The server supports a small number of additional streams beyond the
2009   // negotiated limit. Open enough streams to go beyond that limit.
2010   for (int i = 0; i < kServerMaxStreams + 1; ++i) {
2011     client_->SendMessage(headers, "", /*fin=*/false);
2012   }
2013   client_->WaitForResponse();
2014 
2015   EXPECT_TRUE(client_->connected());
2016   EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_REFUSED_STREAM));
2017   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2018 }
2019 
TEST_P(EndToEndTest,SetIndependentMaxDynamicStreamsLimits)2020 TEST_P(EndToEndTest, SetIndependentMaxDynamicStreamsLimits) {
2021   // Each endpoint can set max dynamic streams independently.
2022   const uint32_t kClientMaxDynamicStreams = 4;
2023   const uint32_t kServerMaxDynamicStreams = 3;
2024   client_config_.SetMaxBidirectionalStreamsToSend(kClientMaxDynamicStreams);
2025   server_config_.SetMaxBidirectionalStreamsToSend(kServerMaxDynamicStreams);
2026   client_config_.SetMaxUnidirectionalStreamsToSend(kClientMaxDynamicStreams);
2027   server_config_.SetMaxUnidirectionalStreamsToSend(kServerMaxDynamicStreams);
2028 
2029   ASSERT_TRUE(Initialize());
2030   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2031 
2032   // The client has received the server's limit and vice versa.
2033   QuicSpdyClientSession* client_session = GetClientSession();
2034   ASSERT_TRUE(client_session);
2035   // The value returned by max_allowed... includes the Crypto and Header
2036   // stream (created as a part of initialization). The config. values,
2037   // above, are treated as "number of requests/responses" - that is, they do
2038   // not include the static Crypto and Header streams. Reduce the value
2039   // returned by max_allowed... by 2 to remove the static streams from the
2040   // count.
2041   size_t client_max_open_outgoing_bidirectional_streams =
2042       version_.HasIetfQuicFrames()
2043           ? QuicSessionPeer::ietf_streamid_manager(client_session)
2044                 ->max_outgoing_bidirectional_streams()
2045           : QuicSessionPeer::GetStreamIdManager(client_session)
2046                 ->max_open_outgoing_streams();
2047   size_t client_max_open_outgoing_unidirectional_streams =
2048       version_.HasIetfQuicFrames()
2049           ? QuicSessionPeer::ietf_streamid_manager(client_session)
2050                     ->max_outgoing_unidirectional_streams() -
2051                 kHttp3StaticUnidirectionalStreamCount
2052           : QuicSessionPeer::GetStreamIdManager(client_session)
2053                 ->max_open_outgoing_streams();
2054   EXPECT_EQ(kServerMaxDynamicStreams,
2055             client_max_open_outgoing_bidirectional_streams);
2056   EXPECT_EQ(kServerMaxDynamicStreams,
2057             client_max_open_outgoing_unidirectional_streams);
2058   server_thread_->Pause();
2059   QuicSession* server_session = GetServerSession();
2060   if (server_session != nullptr) {
2061     size_t server_max_open_outgoing_bidirectional_streams =
2062         version_.HasIetfQuicFrames()
2063             ? QuicSessionPeer::ietf_streamid_manager(server_session)
2064                   ->max_outgoing_bidirectional_streams()
2065             : QuicSessionPeer::GetStreamIdManager(server_session)
2066                   ->max_open_outgoing_streams();
2067     size_t server_max_open_outgoing_unidirectional_streams =
2068         version_.HasIetfQuicFrames()
2069             ? QuicSessionPeer::ietf_streamid_manager(server_session)
2070                       ->max_outgoing_unidirectional_streams() -
2071                   kHttp3StaticUnidirectionalStreamCount
2072             : QuicSessionPeer::GetStreamIdManager(server_session)
2073                   ->max_open_outgoing_streams();
2074     EXPECT_EQ(kClientMaxDynamicStreams,
2075               server_max_open_outgoing_bidirectional_streams);
2076     EXPECT_EQ(kClientMaxDynamicStreams,
2077               server_max_open_outgoing_unidirectional_streams);
2078   } else {
2079     ADD_FAILURE() << "Missing server session";
2080   }
2081   server_thread_->Resume();
2082 }
2083 
TEST_P(EndToEndTest,NegotiateCongestionControl)2084 TEST_P(EndToEndTest, NegotiateCongestionControl) {
2085   ASSERT_TRUE(Initialize());
2086 
2087   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2088 
2089   CongestionControlType expected_congestion_control_type = kRenoBytes;
2090   switch (GetParam().congestion_control_tag) {
2091     case kRENO:
2092       expected_congestion_control_type = kRenoBytes;
2093       break;
2094     case kTBBR:
2095       expected_congestion_control_type = kBBR;
2096       break;
2097     case kQBIC:
2098       expected_congestion_control_type = kCubicBytes;
2099       break;
2100     case kB2ON:
2101       expected_congestion_control_type = kBBRv2;
2102       break;
2103     default:
2104       QUIC_DLOG(FATAL) << "Unexpected congestion control tag";
2105   }
2106 
2107   server_thread_->Pause();
2108   const QuicSentPacketManager* server_sent_packet_manager =
2109       GetSentPacketManagerFromFirstServerSession();
2110   if (server_sent_packet_manager != nullptr) {
2111     EXPECT_EQ(
2112         expected_congestion_control_type,
2113         QuicSentPacketManagerPeer::GetSendAlgorithm(*server_sent_packet_manager)
2114             ->GetCongestionControlType());
2115   } else {
2116     ADD_FAILURE() << "Missing server sent packet manager";
2117   }
2118   server_thread_->Resume();
2119 }
2120 
TEST_P(EndToEndTest,ClientSuggestsRTT)2121 TEST_P(EndToEndTest, ClientSuggestsRTT) {
2122   // Client suggests initial RTT, verify it is used.
2123   const QuicTime::Delta kInitialRTT = QuicTime::Delta::FromMicroseconds(20000);
2124   client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT.ToMicroseconds());
2125 
2126   ASSERT_TRUE(Initialize());
2127   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2128   ASSERT_TRUE(server_thread_);
2129   server_thread_->WaitForCryptoHandshakeConfirmed();
2130 
2131   // Pause the server so we can access the server's internals without races.
2132   server_thread_->Pause();
2133   const QuicSentPacketManager* client_sent_packet_manager =
2134       GetSentPacketManagerFromClientSession();
2135   const QuicSentPacketManager* server_sent_packet_manager =
2136       GetSentPacketManagerFromFirstServerSession();
2137   if (client_sent_packet_manager != nullptr &&
2138       server_sent_packet_manager != nullptr) {
2139     EXPECT_EQ(kInitialRTT,
2140               client_sent_packet_manager->GetRttStats()->initial_rtt());
2141     EXPECT_EQ(kInitialRTT,
2142               server_sent_packet_manager->GetRttStats()->initial_rtt());
2143   } else {
2144     ADD_FAILURE() << "Missing sent packet manager";
2145   }
2146   server_thread_->Resume();
2147 }
2148 
TEST_P(EndToEndTest,ClientSuggestsIgnoredRTT)2149 TEST_P(EndToEndTest, ClientSuggestsIgnoredRTT) {
2150   // Client suggests initial RTT, but also specifies NRTT, so it's not used.
2151   const QuicTime::Delta kInitialRTT = QuicTime::Delta::FromMicroseconds(20000);
2152   client_config_.SetInitialRoundTripTimeUsToSend(kInitialRTT.ToMicroseconds());
2153   QuicTagVector options;
2154   options.push_back(kNRTT);
2155   client_config_.SetConnectionOptionsToSend(options);
2156 
2157   ASSERT_TRUE(Initialize());
2158   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2159   ASSERT_TRUE(server_thread_);
2160   server_thread_->WaitForCryptoHandshakeConfirmed();
2161 
2162   // Pause the server so we can access the server's internals without races.
2163   server_thread_->Pause();
2164   const QuicSentPacketManager* client_sent_packet_manager =
2165       GetSentPacketManagerFromClientSession();
2166   const QuicSentPacketManager* server_sent_packet_manager =
2167       GetSentPacketManagerFromFirstServerSession();
2168   if (client_sent_packet_manager != nullptr &&
2169       server_sent_packet_manager != nullptr) {
2170     EXPECT_EQ(kInitialRTT,
2171               client_sent_packet_manager->GetRttStats()->initial_rtt());
2172     EXPECT_EQ(kInitialRTT,
2173               server_sent_packet_manager->GetRttStats()->initial_rtt());
2174   } else {
2175     ADD_FAILURE() << "Missing sent packet manager";
2176   }
2177   server_thread_->Resume();
2178 }
2179 
2180 // Regression test for b/171378845
TEST_P(EndToEndTest,ClientDisablesGQuicZeroRtt)2181 TEST_P(EndToEndTest, ClientDisablesGQuicZeroRtt) {
2182   if (version_.UsesTls()) {
2183     // This feature is gQUIC only.
2184     ASSERT_TRUE(Initialize());
2185     return;
2186   }
2187   QuicTagVector options;
2188   options.push_back(kQNZ2);
2189   client_config_.SetClientConnectionOptions(options);
2190 
2191   ASSERT_TRUE(Initialize());
2192 
2193   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2194   QuicSpdyClientSession* client_session = GetClientSession();
2195   ASSERT_TRUE(client_session);
2196   EXPECT_FALSE(client_session->EarlyDataAccepted());
2197   EXPECT_FALSE(client_session->ReceivedInchoateReject());
2198   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2199   EXPECT_FALSE(client_->client()->ReceivedInchoateReject());
2200 
2201   client_->Disconnect();
2202 
2203   // Make sure that the request succeeds but 0-RTT was not used.
2204   client_->Connect();
2205   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2206   ASSERT_TRUE(client_->client()->connected());
2207   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2208 
2209   client_session = GetClientSession();
2210   ASSERT_TRUE(client_session);
2211   EXPECT_FALSE(client_session->EarlyDataAccepted());
2212   EXPECT_FALSE(client_->client()->EarlyDataAccepted());
2213 }
2214 
TEST_P(EndToEndTest,MaxInitialRTT)2215 TEST_P(EndToEndTest, MaxInitialRTT) {
2216   // Client tries to suggest twice the server's max initial rtt and the server
2217   // uses the max.
2218   client_config_.SetInitialRoundTripTimeUsToSend(2 *
2219                                                  kMaxInitialRoundTripTimeUs);
2220 
2221   ASSERT_TRUE(Initialize());
2222   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2223   ASSERT_TRUE(server_thread_);
2224   server_thread_->WaitForCryptoHandshakeConfirmed();
2225 
2226   // Pause the server so we can access the server's internals without races.
2227   server_thread_->Pause();
2228   const QuicSentPacketManager* client_sent_packet_manager =
2229       GetSentPacketManagerFromClientSession();
2230   const QuicSentPacketManager* server_sent_packet_manager =
2231       GetSentPacketManagerFromFirstServerSession();
2232   if (client_sent_packet_manager != nullptr &&
2233       server_sent_packet_manager != nullptr) {
2234     // Now that acks have been exchanged, the RTT estimate has decreased on the
2235     // server and is not infinite on the client.
2236     EXPECT_FALSE(
2237         client_sent_packet_manager->GetRttStats()->smoothed_rtt().IsInfinite());
2238     const RttStats* server_rtt_stats =
2239         server_sent_packet_manager->GetRttStats();
2240     EXPECT_EQ(static_cast<int64_t>(kMaxInitialRoundTripTimeUs),
2241               server_rtt_stats->initial_rtt().ToMicroseconds());
2242     EXPECT_GE(static_cast<int64_t>(kMaxInitialRoundTripTimeUs),
2243               server_rtt_stats->smoothed_rtt().ToMicroseconds());
2244   } else {
2245     ADD_FAILURE() << "Missing sent packet manager";
2246   }
2247   server_thread_->Resume();
2248 }
2249 
TEST_P(EndToEndTest,MinInitialRTT)2250 TEST_P(EndToEndTest, MinInitialRTT) {
2251   // Client tries to suggest 0 and the server uses the default.
2252   client_config_.SetInitialRoundTripTimeUsToSend(0);
2253 
2254   ASSERT_TRUE(Initialize());
2255   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2256   server_thread_->WaitForCryptoHandshakeConfirmed();
2257 
2258   // Pause the server so we can access the server's internals without races.
2259   server_thread_->Pause();
2260   const QuicSentPacketManager* client_sent_packet_manager =
2261       GetSentPacketManagerFromClientSession();
2262   const QuicSentPacketManager* server_sent_packet_manager =
2263       GetSentPacketManagerFromFirstServerSession();
2264   if (client_sent_packet_manager != nullptr &&
2265       server_sent_packet_manager != nullptr) {
2266     // Now that acks have been exchanged, the RTT estimate has decreased on the
2267     // server and is not infinite on the client.
2268     EXPECT_FALSE(
2269         client_sent_packet_manager->GetRttStats()->smoothed_rtt().IsInfinite());
2270     // Expect the default rtt of 100ms.
2271     EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
2272               server_sent_packet_manager->GetRttStats()->initial_rtt());
2273     // Ensure the bandwidth is valid.
2274     client_sent_packet_manager->BandwidthEstimate();
2275     server_sent_packet_manager->BandwidthEstimate();
2276   } else {
2277     ADD_FAILURE() << "Missing sent packet manager";
2278   }
2279   server_thread_->Resume();
2280 }
2281 
2282 TEST_P(EndToEndTest, 0ByteConnectionId) {
2283   if (version_.HasIetfInvariantHeader()) {
2284     // SetBytesForConnectionIdToSend only applies to Google QUIC encoding.
2285     ASSERT_TRUE(Initialize());
2286     return;
2287   }
2288   client_config_.SetBytesForConnectionIdToSend(0);
2289   ASSERT_TRUE(Initialize());
2290 
2291   SendSynchronousFooRequestAndCheckResponse();
2292   QuicConnection* client_connection = GetClientConnection();
2293   ASSERT_TRUE(client_connection);
2294   QuicPacketHeader* header =
2295       QuicConnectionPeer::GetLastHeader(client_connection);
2296   EXPECT_EQ(CONNECTION_ID_ABSENT, header->source_connection_id_included);
2297 }
2298 
2299 TEST_P(EndToEndTest, 8ByteConnectionId) {
2300   if (version_.HasIetfInvariantHeader()) {
2301     // SetBytesForConnectionIdToSend only applies to Google QUIC encoding.
2302     ASSERT_TRUE(Initialize());
2303     return;
2304   }
2305   client_config_.SetBytesForConnectionIdToSend(8);
2306   ASSERT_TRUE(Initialize());
2307 
2308   SendSynchronousFooRequestAndCheckResponse();
2309   QuicConnection* client_connection = GetClientConnection();
2310   ASSERT_TRUE(client_connection);
2311   QuicPacketHeader* header =
2312       QuicConnectionPeer::GetLastHeader(client_connection);
2313   EXPECT_EQ(CONNECTION_ID_PRESENT, header->destination_connection_id_included);
2314 }
2315 
2316 TEST_P(EndToEndTest, 15ByteConnectionId) {
2317   if (version_.HasIetfInvariantHeader()) {
2318     // SetBytesForConnectionIdToSend only applies to Google QUIC encoding.
2319     ASSERT_TRUE(Initialize());
2320     return;
2321   }
2322   client_config_.SetBytesForConnectionIdToSend(15);
2323   ASSERT_TRUE(Initialize());
2324 
2325   // Our server is permissive and allows for out of bounds values.
2326   SendSynchronousFooRequestAndCheckResponse();
2327   QuicConnection* client_connection = GetClientConnection();
2328   ASSERT_TRUE(client_connection);
2329   QuicPacketHeader* header =
2330       QuicConnectionPeer::GetLastHeader(client_connection);
2331   EXPECT_EQ(CONNECTION_ID_PRESENT, header->destination_connection_id_included);
2332 }
2333 
TEST_P(EndToEndTest,ResetConnection)2334 TEST_P(EndToEndTest, ResetConnection) {
2335   ASSERT_TRUE(Initialize());
2336 
2337   SendSynchronousFooRequestAndCheckResponse();
2338   client_->ResetConnection();
2339   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2340   SendSynchronousBarRequestAndCheckResponse();
2341 }
2342 
TEST_P(EndToEndTest,MaxStreamsUberTest)2343 TEST_P(EndToEndTest, MaxStreamsUberTest) {
2344   // Connect with lower fake packet loss than we'd like to test.  Until
2345   // b/10126687 is fixed, losing handshake packets is pretty brutal.
2346   SetPacketLossPercentage(1);
2347   ASSERT_TRUE(Initialize());
2348   std::string large_body(10240, 'a');
2349   int max_streams = 100;
2350 
2351   AddToCache("/large_response", 200, large_body);
2352 
2353   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2354   SetPacketLossPercentage(10);
2355 
2356   for (int i = 0; i < max_streams; ++i) {
2357     EXPECT_LT(0, client_->SendRequest("/large_response"));
2358   }
2359 
2360   // WaitForEvents waits 50ms and returns true if there are outstanding
2361   // requests.
2362   while (client_->client()->WaitForEvents()) {
2363     ASSERT_TRUE(client_->connected());
2364   }
2365 }
2366 
TEST_P(EndToEndTest,StreamCancelErrorTest)2367 TEST_P(EndToEndTest, StreamCancelErrorTest) {
2368   ASSERT_TRUE(Initialize());
2369   std::string small_body(256, 'a');
2370 
2371   AddToCache("/small_response", 200, small_body);
2372 
2373   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2374 
2375   QuicSession* session = GetClientSession();
2376   ASSERT_TRUE(session);
2377   // Lose the request.
2378   SetPacketLossPercentage(100);
2379   EXPECT_LT(0, client_->SendRequest("/small_response"));
2380   client_->client()->WaitForEvents();
2381   // Transmit the cancel, and ensure the connection is torn down properly.
2382   SetPacketLossPercentage(0);
2383   QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
2384   QuicConnection* client_connection = GetClientConnection();
2385   ASSERT_TRUE(client_connection);
2386   const QuicPacketCount packets_sent_before =
2387       client_connection->GetStats().packets_sent;
2388   session->ResetStream(stream_id, QUIC_STREAM_CANCELLED);
2389   const QuicPacketCount packets_sent_now =
2390       client_connection->GetStats().packets_sent;
2391 
2392   if (version_.UsesHttp3() && GetQuicReloadableFlag(quic_split_up_send_rst_2)) {
2393     // Make sure 2 packets were sent, one for QPACK instructions, another for
2394     // RESET_STREAM and STOP_SENDING.
2395     EXPECT_EQ(packets_sent_before + 2, packets_sent_now);
2396   }
2397 
2398   // WaitForEvents waits 50ms and returns true if there are outstanding
2399   // requests.
2400   while (client_->client()->WaitForEvents()) {
2401     ASSERT_TRUE(client_->connected());
2402   }
2403   // It should be completely fine to RST a stream before any data has been
2404   // received for that stream.
2405   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
2406 }
2407 
TEST_P(EndToEndTest,ConnectionMigrationClientIPChanged)2408 TEST_P(EndToEndTest, ConnectionMigrationClientIPChanged) {
2409   ASSERT_TRUE(Initialize());
2410   SendSynchronousFooRequestAndCheckResponse();
2411 
2412   // Store the client IP address which was used to send the first request.
2413   QuicIpAddress old_host =
2414       client_->client()->network_helper()->GetLatestClientAddress().host();
2415 
2416   // Migrate socket to the new IP address.
2417   QuicIpAddress new_host = TestLoopback(2);
2418   EXPECT_NE(old_host, new_host);
2419   ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
2420 
2421   // Send a request using the new socket.
2422   SendSynchronousBarRequestAndCheckResponse();
2423 }
2424 
TEST_P(EndToEndTest,ConnectionMigrationClientPortChanged)2425 TEST_P(EndToEndTest, ConnectionMigrationClientPortChanged) {
2426   // Tests that the client's port can change during an established QUIC
2427   // connection, and that doing so does not result in the connection being
2428   // closed by the server.
2429   ASSERT_TRUE(Initialize());
2430 
2431   SendSynchronousFooRequestAndCheckResponse();
2432 
2433   // Store the client address which was used to send the first request.
2434   QuicSocketAddress old_address =
2435       client_->client()->network_helper()->GetLatestClientAddress();
2436   int old_fd = client_->client()->GetLatestFD();
2437 
2438   // Create a new socket before closing the old one, which will result in a new
2439   // ephemeral port.
2440   QuicClientPeer::CreateUDPSocketAndBind(client_->client());
2441 
2442   // Stop listening and close the old FD.
2443   QuicClientPeer::CleanUpUDPSocket(client_->client(), old_fd);
2444 
2445   // The packet writer needs to be updated to use the new FD.
2446   client_->client()->network_helper()->CreateQuicPacketWriter();
2447 
2448   // Change the internal state of the client and connection to use the new port,
2449   // this is done because in a real NAT rebinding the client wouldn't see any
2450   // port change, and so expects no change to incoming port.
2451   // This is kind of ugly, but needed as we are simply swapping out the client
2452   // FD rather than any more complex NAT rebinding simulation.
2453   int new_port =
2454       client_->client()->network_helper()->GetLatestClientAddress().port();
2455   QuicClientPeer::SetClientPort(client_->client(), new_port);
2456   QuicConnection* client_connection = GetClientConnection();
2457   ASSERT_TRUE(client_connection);
2458   QuicConnectionPeer::SetSelfAddress(
2459       client_connection,
2460       QuicSocketAddress(client_connection->self_address().host(), new_port));
2461 
2462   // Register the new FD for epoll events.
2463   int new_fd = client_->client()->GetLatestFD();
2464   QuicEpollServer* eps = client_->epoll_server();
2465   eps->RegisterFD(new_fd, client_->client()->epoll_network_helper(),
2466                   EPOLLIN | EPOLLOUT | EPOLLET);
2467 
2468   // Send a second request, using the new FD.
2469   SendSynchronousBarRequestAndCheckResponse();
2470 
2471   // Verify that the client's ephemeral port is different.
2472   QuicSocketAddress new_address =
2473       client_->client()->network_helper()->GetLatestClientAddress();
2474   EXPECT_EQ(old_address.host(), new_address.host());
2475   EXPECT_NE(old_address.port(), new_address.port());
2476 }
2477 
TEST_P(EndToEndTest,NegotiatedInitialCongestionWindow)2478 TEST_P(EndToEndTest, NegotiatedInitialCongestionWindow) {
2479   SetQuicReloadableFlag(quic_unified_iw_options, true);
2480   client_extra_copts_.push_back(kIW03);
2481 
2482   ASSERT_TRUE(Initialize());
2483 
2484   // Values are exchanged during crypto handshake, so wait for that to finish.
2485   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2486   server_thread_->WaitForCryptoHandshakeConfirmed();
2487   server_thread_->Pause();
2488   QuicConnection* server_connection = GetServerConnection();
2489   if (server_connection != nullptr) {
2490     QuicPacketCount cwnd =
2491         server_connection->sent_packet_manager().initial_congestion_window();
2492     EXPECT_EQ(3u, cwnd);
2493   } else {
2494     ADD_FAILURE() << "Missing server connection";
2495   }
2496   server_thread_->Resume();
2497 }
2498 
TEST_P(EndToEndTest,DifferentFlowControlWindows)2499 TEST_P(EndToEndTest, DifferentFlowControlWindows) {
2500   // Client and server can set different initial flow control receive windows.
2501   // These are sent in CHLO/SHLO. Tests that these values are exchanged properly
2502   // in the crypto handshake.
2503   const uint32_t kClientStreamIFCW = 123456;
2504   const uint32_t kClientSessionIFCW = 234567;
2505   set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
2506   set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
2507 
2508   uint32_t kServerStreamIFCW = 32 * 1024;
2509   uint32_t kServerSessionIFCW = 48 * 1024;
2510   set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
2511   set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
2512 
2513   ASSERT_TRUE(Initialize());
2514 
2515   // Values are exchanged during crypto handshake, so wait for that to finish.
2516   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2517   server_thread_->WaitForCryptoHandshakeConfirmed();
2518 
2519   // Open a data stream to make sure the stream level flow control is updated.
2520   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
2521   WriteHeadersOnStream(stream);
2522   stream->WriteOrBufferBody("hello", false);
2523 
2524   if (!version_.UsesTls()) {
2525     // IFWA only exists with QUIC_CRYPTO.
2526     // Client should have the right values for server's receive window.
2527     ASSERT_TRUE(client_->client()
2528                     ->client_session()
2529                     ->config()
2530                     ->HasReceivedInitialStreamFlowControlWindowBytes());
2531     EXPECT_EQ(kServerStreamIFCW,
2532               client_->client()
2533                   ->client_session()
2534                   ->config()
2535                   ->ReceivedInitialStreamFlowControlWindowBytes());
2536     ASSERT_TRUE(client_->client()
2537                     ->client_session()
2538                     ->config()
2539                     ->HasReceivedInitialSessionFlowControlWindowBytes());
2540     EXPECT_EQ(kServerSessionIFCW,
2541               client_->client()
2542                   ->client_session()
2543                   ->config()
2544                   ->ReceivedInitialSessionFlowControlWindowBytes());
2545   }
2546   EXPECT_EQ(kServerStreamIFCW, QuicStreamPeer::SendWindowOffset(stream));
2547   QuicSpdyClientSession* client_session = GetClientSession();
2548   ASSERT_TRUE(client_session);
2549   EXPECT_EQ(kServerSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
2550                                     client_session->flow_controller()));
2551 
2552   // Server should have the right values for client's receive window.
2553   server_thread_->Pause();
2554   QuicSpdySession* server_session = GetServerSession();
2555   if (server_session == nullptr) {
2556     ADD_FAILURE() << "Missing server session";
2557     server_thread_->Resume();
2558     return;
2559   }
2560   QuicConfig server_config = *server_session->config();
2561   EXPECT_EQ(kClientSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
2562                                     server_session->flow_controller()));
2563   server_thread_->Resume();
2564   if (version_.UsesTls()) {
2565     // IFWA only exists with QUIC_CRYPTO.
2566     return;
2567   }
2568   ASSERT_TRUE(server_config.HasReceivedInitialStreamFlowControlWindowBytes());
2569   EXPECT_EQ(kClientStreamIFCW,
2570             server_config.ReceivedInitialStreamFlowControlWindowBytes());
2571   ASSERT_TRUE(server_config.HasReceivedInitialSessionFlowControlWindowBytes());
2572   EXPECT_EQ(kClientSessionIFCW,
2573             server_config.ReceivedInitialSessionFlowControlWindowBytes());
2574 }
2575 
2576 // Test negotiation of IFWA connection option.
TEST_P(EndToEndTest,NegotiatedServerInitialFlowControlWindow)2577 TEST_P(EndToEndTest, NegotiatedServerInitialFlowControlWindow) {
2578   const uint32_t kClientStreamIFCW = 123456;
2579   const uint32_t kClientSessionIFCW = 234567;
2580   set_client_initial_stream_flow_control_receive_window(kClientStreamIFCW);
2581   set_client_initial_session_flow_control_receive_window(kClientSessionIFCW);
2582 
2583   uint32_t kServerStreamIFCW = 32 * 1024;
2584   uint32_t kServerSessionIFCW = 48 * 1024;
2585   set_server_initial_stream_flow_control_receive_window(kServerStreamIFCW);
2586   set_server_initial_session_flow_control_receive_window(kServerSessionIFCW);
2587 
2588   // Bump the window.
2589   const uint32_t kExpectedStreamIFCW = 1024 * 1024;
2590   const uint32_t kExpectedSessionIFCW = 1.5 * 1024 * 1024;
2591   client_extra_copts_.push_back(kIFWA);
2592 
2593   ASSERT_TRUE(Initialize());
2594 
2595   // Values are exchanged during crypto handshake, so wait for that to finish.
2596   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2597   server_thread_->WaitForCryptoHandshakeConfirmed();
2598 
2599   // Open a data stream to make sure the stream level flow control is updated.
2600   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
2601   WriteHeadersOnStream(stream);
2602   stream->WriteOrBufferBody("hello", false);
2603 
2604   QuicSpdyClientSession* client_session = GetClientSession();
2605   ASSERT_TRUE(client_session);
2606 
2607   if (!version_.UsesTls()) {
2608     // IFWA only exists with QUIC_CRYPTO.
2609     // Client should have the right values for server's receive window.
2610     ASSERT_TRUE(client_session->config()
2611                     ->HasReceivedInitialStreamFlowControlWindowBytes());
2612     EXPECT_EQ(kExpectedStreamIFCW,
2613               client_session->config()
2614                   ->ReceivedInitialStreamFlowControlWindowBytes());
2615     ASSERT_TRUE(client_session->config()
2616                     ->HasReceivedInitialSessionFlowControlWindowBytes());
2617     EXPECT_EQ(kExpectedSessionIFCW,
2618               client_session->config()
2619                   ->ReceivedInitialSessionFlowControlWindowBytes());
2620   }
2621   EXPECT_EQ(kExpectedStreamIFCW, QuicStreamPeer::SendWindowOffset(stream));
2622   EXPECT_EQ(kExpectedSessionIFCW, QuicFlowControllerPeer::SendWindowOffset(
2623                                       client_session->flow_controller()));
2624 }
2625 
TEST_P(EndToEndTest,HeadersAndCryptoStreamsNoConnectionFlowControl)2626 TEST_P(EndToEndTest, HeadersAndCryptoStreamsNoConnectionFlowControl) {
2627   // The special headers and crypto streams should be subject to per-stream flow
2628   // control limits, but should not be subject to connection level flow control
2629   const uint32_t kStreamIFCW = 32 * 1024;
2630   const uint32_t kSessionIFCW = 48 * 1024;
2631   set_client_initial_stream_flow_control_receive_window(kStreamIFCW);
2632   set_client_initial_session_flow_control_receive_window(kSessionIFCW);
2633   set_server_initial_stream_flow_control_receive_window(kStreamIFCW);
2634   set_server_initial_session_flow_control_receive_window(kSessionIFCW);
2635 
2636   ASSERT_TRUE(Initialize());
2637 
2638   // Wait for crypto handshake to finish. This should have contributed to the
2639   // crypto stream flow control window, but not affected the session flow
2640   // control window.
2641   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2642   server_thread_->WaitForCryptoHandshakeConfirmed();
2643 
2644   QuicSpdyClientSession* client_session = GetClientSession();
2645   ASSERT_TRUE(client_session);
2646   QuicCryptoStream* crypto_stream =
2647       QuicSessionPeer::GetMutableCryptoStream(client_session);
2648   ASSERT_TRUE(crypto_stream);
2649   // In v47 and later, the crypto handshake (sent in CRYPTO frames) is not
2650   // subject to flow control.
2651   if (!version_.UsesCryptoFrames()) {
2652     EXPECT_LT(QuicStreamPeer::SendWindowSize(crypto_stream), kStreamIFCW);
2653   }
2654   // When stream type is enabled, control streams will send settings and
2655   // contribute to flow control windows, so this expectation is no longer valid.
2656   if (!version_.UsesHttp3()) {
2657     EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
2658                                 client_session->flow_controller()));
2659   }
2660 
2661   // Send a request with no body, and verify that the connection level window
2662   // has not been affected.
2663   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
2664 
2665   // No headers stream in IETF QUIC.
2666   if (version_.UsesHttp3()) {
2667     return;
2668   }
2669 
2670   QuicHeadersStream* headers_stream =
2671       QuicSpdySessionPeer::GetHeadersStream(client_session);
2672   ASSERT_TRUE(headers_stream);
2673   EXPECT_LT(QuicStreamPeer::SendWindowSize(headers_stream), kStreamIFCW);
2674   EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::SendWindowSize(
2675                               client_session->flow_controller()));
2676 
2677   // Server should be in a similar state: connection flow control window should
2678   // not have any bytes marked as received.
2679   server_thread_->Pause();
2680   QuicSession* server_session = GetServerSession();
2681   if (server_session != nullptr) {
2682     QuicFlowController* server_connection_flow_controller =
2683         server_session->flow_controller();
2684     EXPECT_EQ(kSessionIFCW, QuicFlowControllerPeer::ReceiveWindowSize(
2685                                 server_connection_flow_controller));
2686   } else {
2687     ADD_FAILURE() << "Missing server session";
2688   }
2689   server_thread_->Resume();
2690 }
2691 
TEST_P(EndToEndTest,FlowControlsSynced)2692 TEST_P(EndToEndTest, FlowControlsSynced) {
2693   set_smaller_flow_control_receive_window();
2694 
2695   ASSERT_TRUE(Initialize());
2696 
2697   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2698   server_thread_->WaitForCryptoHandshakeConfirmed();
2699 
2700   QuicSpdySession* const client_session = GetClientSession();
2701   ASSERT_TRUE(client_session);
2702 
2703   if (version_.UsesHttp3()) {
2704     // Make sure that the client has received the initial SETTINGS frame, which
2705     // is sent in the first packet on the control stream.
2706     while (!QuicSpdySessionPeer::GetReceiveControlStream(client_session)) {
2707       client_->client()->WaitForEvents();
2708       ASSERT_TRUE(client_->connected());
2709     }
2710   }
2711 
2712   // Make sure that all data sent by the client has been received by the server
2713   // (and the ack received by the client).
2714   while (client_session->HasUnackedStreamData()) {
2715     client_->client()->WaitForEvents();
2716     ASSERT_TRUE(client_->connected());
2717   }
2718 
2719   server_thread_->Pause();
2720 
2721   QuicSpdySession* const server_session = GetServerSession();
2722   if (server_session == nullptr) {
2723     ADD_FAILURE() << "Missing server session";
2724     server_thread_->Resume();
2725     return;
2726   }
2727   ExpectFlowControlsSynced(client_session, server_session);
2728 
2729   // Check control streams.
2730   if (version_.UsesHttp3()) {
2731     ExpectFlowControlsSynced(
2732         QuicSpdySessionPeer::GetReceiveControlStream(client_session),
2733         QuicSpdySessionPeer::GetSendControlStream(server_session));
2734     ExpectFlowControlsSynced(
2735         QuicSpdySessionPeer::GetSendControlStream(client_session),
2736         QuicSpdySessionPeer::GetReceiveControlStream(server_session));
2737   }
2738 
2739   // Check crypto stream.
2740   if (!version_.UsesCryptoFrames()) {
2741     ExpectFlowControlsSynced(
2742         QuicSessionPeer::GetMutableCryptoStream(client_session),
2743         QuicSessionPeer::GetMutableCryptoStream(server_session));
2744   }
2745 
2746   // Check headers stream.
2747   if (!version_.UsesHttp3()) {
2748     SpdyFramer spdy_framer(SpdyFramer::ENABLE_COMPRESSION);
2749     SpdySettingsIR settings_frame;
2750     settings_frame.AddSetting(spdy::SETTINGS_MAX_HEADER_LIST_SIZE,
2751                               kDefaultMaxUncompressedHeaderSize);
2752     SpdySerializedFrame frame(spdy_framer.SerializeFrame(settings_frame));
2753 
2754     QuicHeadersStream* client_header_stream =
2755         QuicSpdySessionPeer::GetHeadersStream(client_session);
2756     QuicHeadersStream* server_header_stream =
2757         QuicSpdySessionPeer::GetHeadersStream(server_session);
2758     // Both client and server are sending this SETTINGS frame, and the send
2759     // window is consumed. But because of timing issue, the server may send or
2760     // not send the frame, and the client may send/ not send / receive / not
2761     // receive the frame.
2762     // TODO(fayang): Rewrite this part because it is hacky.
2763     QuicByteCount win_difference1 =
2764         QuicStreamPeer::ReceiveWindowSize(server_header_stream) -
2765         QuicStreamPeer::SendWindowSize(client_header_stream);
2766     if (win_difference1 != 0) {
2767       EXPECT_EQ(frame.size(), win_difference1);
2768     }
2769 
2770     QuicByteCount win_difference2 =
2771         QuicStreamPeer::ReceiveWindowSize(client_header_stream) -
2772         QuicStreamPeer::SendWindowSize(server_header_stream);
2773     if (win_difference2 != 0) {
2774       EXPECT_EQ(frame.size(), win_difference2);
2775     }
2776 
2777     // Client *may* have received the SETTINGs frame.
2778     // TODO(fayang): Rewrite this part because it is hacky.
2779     float ratio1 = static_cast<float>(QuicFlowControllerPeer::ReceiveWindowSize(
2780                        client_session->flow_controller())) /
2781                    QuicStreamPeer::ReceiveWindowSize(
2782                        QuicSpdySessionPeer::GetHeadersStream(client_session));
2783     float ratio2 = static_cast<float>(QuicFlowControllerPeer::ReceiveWindowSize(
2784                        client_session->flow_controller())) /
2785                    (QuicStreamPeer::ReceiveWindowSize(
2786                         QuicSpdySessionPeer::GetHeadersStream(client_session)) +
2787                     frame.size());
2788     EXPECT_TRUE(ratio1 == kSessionToStreamRatio ||
2789                 ratio2 == kSessionToStreamRatio);
2790   }
2791 
2792   server_thread_->Resume();
2793 }
2794 
TEST_P(EndToEndTest,RequestWithNoBodyWillNeverSendStreamFrameWithFIN)2795 TEST_P(EndToEndTest, RequestWithNoBodyWillNeverSendStreamFrameWithFIN) {
2796   // A stream created on receipt of a simple request with no body will never get
2797   // a stream frame with a FIN. Verify that we don't keep track of the stream in
2798   // the locally closed streams map: it will never be removed if so.
2799   ASSERT_TRUE(Initialize());
2800 
2801   // Send a simple headers only request, and receive response.
2802   SendSynchronousFooRequestAndCheckResponse();
2803 
2804   // Now verify that the server is not waiting for a final FIN or RST.
2805   server_thread_->Pause();
2806   QuicSession* server_session = GetServerSession();
2807   if (server_session != nullptr) {
2808     EXPECT_EQ(0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(
2809                       server_session)
2810                       .size());
2811   } else {
2812     ADD_FAILURE() << "Missing server session";
2813   }
2814   server_thread_->Resume();
2815 }
2816 
2817 // TestAckListener counts how many bytes are acked during its lifetime.
2818 class TestAckListener : public QuicAckListenerInterface {
2819  public:
TestAckListener()2820   TestAckListener() {}
2821 
OnPacketAcked(int acked_bytes,QuicTime::Delta)2822   void OnPacketAcked(int acked_bytes,
2823                      QuicTime::Delta /*delta_largest_observed*/) override {
2824     total_bytes_acked_ += acked_bytes;
2825   }
2826 
OnPacketRetransmitted(int)2827   void OnPacketRetransmitted(int /*retransmitted_bytes*/) override {}
2828 
total_bytes_acked() const2829   int total_bytes_acked() const { return total_bytes_acked_; }
2830 
2831  protected:
2832   // Object is ref counted.
~TestAckListener()2833   ~TestAckListener() override {}
2834 
2835  private:
2836   int total_bytes_acked_ = 0;
2837 };
2838 
2839 class TestResponseListener : public QuicSpdyClientBase::ResponseListener {
2840  public:
OnCompleteResponse(QuicStreamId id,const SpdyHeaderBlock & response_headers,const std::string & response_body)2841   void OnCompleteResponse(QuicStreamId id,
2842                           const SpdyHeaderBlock& response_headers,
2843                           const std::string& response_body) override {
2844     QUIC_DVLOG(1) << "response for stream " << id << " "
2845                   << response_headers.DebugString() << "\n"
2846                   << response_body;
2847   }
2848 };
2849 
TEST_P(EndToEndTest,AckNotifierWithPacketLossAndBlockedSocket)2850 TEST_P(EndToEndTest, AckNotifierWithPacketLossAndBlockedSocket) {
2851   // Verify that even in the presence of packet loss and occasionally blocked
2852   // socket, an AckNotifierDelegate will get informed that the data it is
2853   // interested in has been ACKed. This tests end-to-end ACK notification, and
2854   // demonstrates that retransmissions do not break this functionality.
2855   // Disable blackhole detection as this test is testing loss recovery.
2856   client_extra_copts_.push_back(kNBHD);
2857   SetPacketLossPercentage(5);
2858   ASSERT_TRUE(Initialize());
2859   // Wait for the server SHLO before upping the packet loss.
2860   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
2861   SetPacketLossPercentage(30);
2862   client_writer_->set_fake_blocked_socket_percentage(10);
2863 
2864   // Wait for SETTINGS frame from server that sets QPACK dynamic table capacity
2865   // to make sure request headers will be compressed using the dynamic table.
2866   if (version_.UsesHttp3()) {
2867     while (true) {
2868       // Waits for up to 50 ms.
2869       client_->client()->WaitForEvents();
2870       ASSERT_TRUE(client_->connected());
2871       QuicSpdyClientSession* client_session = GetClientSession();
2872       if (client_session == nullptr) {
2873         ADD_FAILURE() << "Missing client session";
2874         return;
2875       }
2876       QpackEncoder* qpack_encoder = client_session->qpack_encoder();
2877       if (qpack_encoder == nullptr) {
2878         ADD_FAILURE() << "Missing QPACK encoder";
2879         return;
2880       }
2881       QpackHeaderTable* header_table =
2882           QpackEncoderPeer::header_table(qpack_encoder);
2883       if (header_table == nullptr) {
2884         ADD_FAILURE() << "Missing header table";
2885         return;
2886       }
2887       if (QpackHeaderTablePeer::dynamic_table_capacity(header_table) > 0) {
2888         break;
2889       }
2890     }
2891   }
2892 
2893   // Create a POST request and send the headers only.
2894   SpdyHeaderBlock headers;
2895   headers[":method"] = "POST";
2896   headers[":path"] = "/foo";
2897   headers[":scheme"] = "https";
2898   headers[":authority"] = server_hostname_;
2899 
2900   client_->SendMessage(headers, "", /*fin=*/false);
2901 
2902   // Size of headers on the request stream. This is zero if headers are sent on
2903   // the header stream.
2904   size_t header_size = 0;
2905   if (version_.UsesHttp3()) {
2906     // Determine size of headers after QPACK compression.
2907     NoopDecoderStreamErrorDelegate decoder_stream_error_delegate;
2908     NoopQpackStreamSenderDelegate encoder_stream_sender_delegate;
2909     QpackEncoder qpack_encoder(&decoder_stream_error_delegate);
2910     qpack_encoder.set_qpack_stream_sender_delegate(
2911         &encoder_stream_sender_delegate);
2912 
2913     qpack_encoder.SetMaximumDynamicTableCapacity(
2914         kDefaultQpackMaxDynamicTableCapacity);
2915     qpack_encoder.SetDynamicTableCapacity(kDefaultQpackMaxDynamicTableCapacity);
2916     qpack_encoder.SetMaximumBlockedStreams(kDefaultMaximumBlockedStreams);
2917 
2918     std::string encoded_headers = qpack_encoder.EncodeHeaderList(
2919         /* stream_id = */ 0, headers, nullptr);
2920     header_size = encoded_headers.size();
2921   }
2922 
2923   // Test the AckNotifier's ability to track multiple packets by making the
2924   // request body exceed the size of a single packet.
2925   std::string request_string = "a request body bigger than one packet" +
2926                                std::string(kMaxOutgoingPacketSize, '.');
2927 
2928   const int expected_bytes_acked = header_size + request_string.length();
2929 
2930   // The TestAckListener will cause a failure if not notified.
2931   QuicReferenceCountedPointer<TestAckListener> ack_listener(
2932       new TestAckListener());
2933 
2934   // Send the request, and register the delegate for ACKs.
2935   client_->SendData(request_string, true, ack_listener);
2936   WaitForFooResponseAndCheckIt();
2937 
2938   // Send another request to flush out any pending ACKs on the server.
2939   SendSynchronousBarRequestAndCheckResponse();
2940 
2941   // Make sure the delegate does get the notification it expects.
2942   while (ack_listener->total_bytes_acked() < expected_bytes_acked) {
2943     // Waits for up to 50 ms.
2944     client_->client()->WaitForEvents();
2945     ASSERT_TRUE(client_->connected());
2946   }
2947   EXPECT_EQ(ack_listener->total_bytes_acked(), expected_bytes_acked)
2948       << " header_size " << header_size << " request length "
2949       << request_string.length();
2950 }
2951 
2952 // Send a public reset from the server.
TEST_P(EndToEndTest,ServerSendPublicReset)2953 TEST_P(EndToEndTest, ServerSendPublicReset) {
2954   ASSERT_TRUE(Initialize());
2955 
2956   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2957   QuicSpdySession* client_session = GetClientSession();
2958   ASSERT_TRUE(client_session);
2959   QuicConfig* config = client_session->config();
2960   ASSERT_TRUE(config);
2961   EXPECT_TRUE(config->HasReceivedStatelessResetToken());
2962   QuicUint128 stateless_reset_token = config->ReceivedStatelessResetToken();
2963 
2964   // Send the public reset.
2965   QuicConnection* client_connection = GetClientConnection();
2966   ASSERT_TRUE(client_connection);
2967   QuicConnectionId connection_id = client_connection->connection_id();
2968   QuicPublicResetPacket header;
2969   header.connection_id = connection_id;
2970   QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
2971                     Perspective::IS_SERVER, kQuicDefaultConnectionIdLength);
2972   std::unique_ptr<QuicEncryptedPacket> packet;
2973   if (version_.HasIetfInvariantHeader()) {
2974     packet = framer.BuildIetfStatelessResetPacket(connection_id,
2975                                                   stateless_reset_token);
2976   } else {
2977     packet = framer.BuildPublicResetPacket(header);
2978   }
2979   // We must pause the server's thread in order to call WritePacket without
2980   // race conditions.
2981   server_thread_->Pause();
2982   server_writer_->WritePacket(
2983       packet->data(), packet->length(), server_address_.host(),
2984       client_->client()->network_helper()->GetLatestClientAddress(), nullptr);
2985   server_thread_->Resume();
2986 
2987   // The request should fail.
2988   EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
2989   EXPECT_TRUE(client_->response_headers()->empty());
2990   EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
2991 }
2992 
2993 // Send a public reset from the server for a different connection ID.
2994 // It should be ignored.
TEST_P(EndToEndTest,ServerSendPublicResetWithDifferentConnectionId)2995 TEST_P(EndToEndTest, ServerSendPublicResetWithDifferentConnectionId) {
2996   ASSERT_TRUE(Initialize());
2997 
2998   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
2999   QuicSpdySession* client_session = GetClientSession();
3000   ASSERT_TRUE(client_session);
3001   QuicConfig* config = client_session->config();
3002   ASSERT_TRUE(config);
3003   EXPECT_TRUE(config->HasReceivedStatelessResetToken());
3004   QuicUint128 stateless_reset_token = config->ReceivedStatelessResetToken();
3005   // Send the public reset.
3006   QuicConnection* client_connection = GetClientConnection();
3007   ASSERT_TRUE(client_connection);
3008   QuicConnectionId incorrect_connection_id = TestConnectionId(
3009       TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
3010   QuicPublicResetPacket header;
3011   header.connection_id = incorrect_connection_id;
3012   QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
3013                     Perspective::IS_SERVER, kQuicDefaultConnectionIdLength);
3014   std::unique_ptr<QuicEncryptedPacket> packet;
3015   NiceMock<MockQuicConnectionDebugVisitor> visitor;
3016   client_connection->set_debug_visitor(&visitor);
3017   if (version_.HasIetfInvariantHeader()) {
3018     packet = framer.BuildIetfStatelessResetPacket(incorrect_connection_id,
3019                                                   stateless_reset_token);
3020     EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
3021         .Times(0);
3022   } else {
3023     packet = framer.BuildPublicResetPacket(header);
3024     EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
3025         .Times(1);
3026   }
3027   // We must pause the server's thread in order to call WritePacket without
3028   // race conditions.
3029   server_thread_->Pause();
3030   server_writer_->WritePacket(
3031       packet->data(), packet->length(), server_address_.host(),
3032       client_->client()->network_helper()->GetLatestClientAddress(), nullptr);
3033   server_thread_->Resume();
3034 
3035   if (version_.HasIetfInvariantHeader()) {
3036     // The request should fail. IETF stateless reset does not include connection
3037     // ID.
3038     EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
3039     EXPECT_TRUE(client_->response_headers()->empty());
3040     EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
3041   } else {
3042     // The connection should be unaffected.
3043     SendSynchronousFooRequestAndCheckResponse();
3044   }
3045 
3046   client_connection->set_debug_visitor(nullptr);
3047 }
3048 
3049 // Send a public reset from the client for a different connection ID.
3050 // It should be ignored.
TEST_P(EndToEndTest,ClientSendPublicResetWithDifferentConnectionId)3051 TEST_P(EndToEndTest, ClientSendPublicResetWithDifferentConnectionId) {
3052   ASSERT_TRUE(Initialize());
3053 
3054   // Send the public reset.
3055   QuicConnection* client_connection = GetClientConnection();
3056   ASSERT_TRUE(client_connection);
3057   QuicConnectionId incorrect_connection_id = TestConnectionId(
3058       TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
3059   QuicPublicResetPacket header;
3060   header.connection_id = incorrect_connection_id;
3061   QuicFramer framer(server_supported_versions_, QuicTime::Zero(),
3062                     Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength);
3063   std::unique_ptr<QuicEncryptedPacket> packet(
3064       framer.BuildPublicResetPacket(header));
3065   client_writer_->WritePacket(
3066       packet->data(), packet->length(),
3067       client_->client()->network_helper()->GetLatestClientAddress().host(),
3068       server_address_, nullptr);
3069 
3070   // The connection should be unaffected.
3071   SendSynchronousFooRequestAndCheckResponse();
3072 }
3073 
3074 // Send a version negotiation packet from the server for a different
3075 // connection ID.  It should be ignored.
TEST_P(EndToEndTest,ServerSendVersionNegotiationWithDifferentConnectionId)3076 TEST_P(EndToEndTest, ServerSendVersionNegotiationWithDifferentConnectionId) {
3077   ASSERT_TRUE(Initialize());
3078 
3079   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3080 
3081   // Send the version negotiation packet.
3082   QuicConnection* client_connection = GetClientConnection();
3083   ASSERT_TRUE(client_connection);
3084   QuicConnectionId incorrect_connection_id = TestConnectionId(
3085       TestConnectionIdToUInt64(client_connection->connection_id()) + 1);
3086   std::unique_ptr<QuicEncryptedPacket> packet(
3087       QuicFramer::BuildVersionNegotiationPacket(
3088           incorrect_connection_id, EmptyQuicConnectionId(),
3089           version_.HasIetfInvariantHeader(),
3090           version_.HasLengthPrefixedConnectionIds(),
3091           server_supported_versions_));
3092   NiceMock<MockQuicConnectionDebugVisitor> visitor;
3093   client_connection->set_debug_visitor(&visitor);
3094   EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id))
3095       .Times(1);
3096   // We must pause the server's thread in order to call WritePacket without
3097   // race conditions.
3098   server_thread_->Pause();
3099   server_writer_->WritePacket(
3100       packet->data(), packet->length(), server_address_.host(),
3101       client_->client()->network_helper()->GetLatestClientAddress(), nullptr);
3102   server_thread_->Resume();
3103 
3104   // The connection should be unaffected.
3105   SendSynchronousFooRequestAndCheckResponse();
3106 
3107   client_connection->set_debug_visitor(nullptr);
3108 }
3109 
3110 // A bad header shouldn't tear down the connection, because the receiver can't
3111 // tell the connection ID.
TEST_P(EndToEndTest,BadPacketHeaderTruncated)3112 TEST_P(EndToEndTest, BadPacketHeaderTruncated) {
3113   ASSERT_TRUE(Initialize());
3114 
3115   // Start the connection.
3116   SendSynchronousFooRequestAndCheckResponse();
3117 
3118   // Packet with invalid public flags.
3119   char packet[] = {// public flags (8 byte connection_id)
3120                    0x3C,
3121                    // truncated connection ID
3122                    0x11};
3123   client_writer_->WritePacket(
3124       &packet[0], sizeof(packet),
3125       client_->client()->network_helper()->GetLatestClientAddress().host(),
3126       server_address_, nullptr);
3127   EXPECT_TRUE(server_thread_->WaitUntil(
3128       [&] {
3129         return QuicDispatcherPeer::GetAndClearLastError(
3130                    QuicServerPeer::GetDispatcher(server_thread_->server())) ==
3131                QUIC_INVALID_PACKET_HEADER;
3132       },
3133       QuicTime::Delta::FromSeconds(5)));
3134 
3135   // The connection should not be terminated.
3136   SendSynchronousFooRequestAndCheckResponse();
3137 }
3138 
3139 // A bad header shouldn't tear down the connection, because the receiver can't
3140 // tell the connection ID.
TEST_P(EndToEndTest,BadPacketHeaderFlags)3141 TEST_P(EndToEndTest, BadPacketHeaderFlags) {
3142   ASSERT_TRUE(Initialize());
3143 
3144   // Start the connection.
3145   SendSynchronousFooRequestAndCheckResponse();
3146 
3147   // Packet with invalid public flags.
3148   char packet[] = {
3149       // invalid public flags
3150       0xFF,
3151       // connection_id
3152       0x10,
3153       0x32,
3154       0x54,
3155       0x76,
3156       0x98,
3157       0xBA,
3158       0xDC,
3159       0xFE,
3160       // packet sequence number
3161       0xBC,
3162       0x9A,
3163       0x78,
3164       0x56,
3165       0x34,
3166       0x12,
3167       // private flags
3168       0x00,
3169   };
3170   client_writer_->WritePacket(
3171       &packet[0], sizeof(packet),
3172       client_->client()->network_helper()->GetLatestClientAddress().host(),
3173       server_address_, nullptr);
3174 
3175   EXPECT_TRUE(server_thread_->WaitUntil(
3176       [&] {
3177         return QuicDispatcherPeer::GetAndClearLastError(
3178                    QuicServerPeer::GetDispatcher(server_thread_->server())) ==
3179                QUIC_INVALID_PACKET_HEADER;
3180       },
3181       QuicTime::Delta::FromSeconds(5)));
3182 
3183   // The connection should not be terminated.
3184   SendSynchronousFooRequestAndCheckResponse();
3185 }
3186 
3187 // Send a packet from the client with bad encrypted data.  The server should not
3188 // tear down the connection.
TEST_P(EndToEndTest,BadEncryptedData)3189 TEST_P(EndToEndTest, BadEncryptedData) {
3190   ASSERT_TRUE(Initialize());
3191 
3192   // Start the connection.
3193   SendSynchronousFooRequestAndCheckResponse();
3194 
3195   QuicConnection* client_connection = GetClientConnection();
3196   ASSERT_TRUE(client_connection);
3197   std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
3198       client_connection->connection_id(), EmptyQuicConnectionId(), false, false,
3199       1, "At least 20 characters.", CONNECTION_ID_PRESENT, CONNECTION_ID_ABSENT,
3200       PACKET_4BYTE_PACKET_NUMBER));
3201   // Damage the encrypted data.
3202   std::string damaged_packet(packet->data(), packet->length());
3203   damaged_packet[30] ^= 0x01;
3204   QUIC_DLOG(INFO) << "Sending bad packet.";
3205   client_writer_->WritePacket(
3206       damaged_packet.data(), damaged_packet.length(),
3207       client_->client()->network_helper()->GetLatestClientAddress().host(),
3208       server_address_, nullptr);
3209   // Give the server time to process the packet.
3210   QuicSleep(QuicTime::Delta::FromSeconds(1));
3211   // This error is sent to the connection's OnError (which ignores it), so the
3212   // dispatcher doesn't see it.
3213   // Pause the server so we can access the server's internals without races.
3214   server_thread_->Pause();
3215   QuicDispatcher* dispatcher =
3216       QuicServerPeer::GetDispatcher(server_thread_->server());
3217   if (dispatcher != nullptr) {
3218     EXPECT_THAT(QuicDispatcherPeer::GetAndClearLastError(dispatcher),
3219                 IsQuicNoError());
3220   } else {
3221     ADD_FAILURE() << "Missing dispatcher";
3222   }
3223   server_thread_->Resume();
3224 
3225   // The connection should not be terminated.
3226   SendSynchronousFooRequestAndCheckResponse();
3227 }
3228 
TEST_P(EndToEndTest,CanceledStreamDoesNotBecomeZombie)3229 TEST_P(EndToEndTest, CanceledStreamDoesNotBecomeZombie) {
3230   ASSERT_TRUE(Initialize());
3231   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3232   // Lose the request.
3233   SetPacketLossPercentage(100);
3234   SpdyHeaderBlock headers;
3235   headers[":method"] = "POST";
3236   headers[":path"] = "/foo";
3237   headers[":scheme"] = "https";
3238   headers[":authority"] = server_hostname_;
3239   client_->SendMessage(headers, "test_body", /*fin=*/false);
3240   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
3241 
3242   // Cancel the stream.
3243   stream->Reset(QUIC_STREAM_CANCELLED);
3244   QuicSession* session = GetClientSession();
3245   ASSERT_TRUE(session);
3246   // Verify canceled stream does not become zombie.
3247   EXPECT_EQ(1u, QuicSessionPeer::closed_streams(session).size());
3248 }
3249 
3250 // A test stream that gives |response_body_| as an error response body.
3251 class ServerStreamWithErrorResponseBody : public QuicSimpleServerStream {
3252  public:
ServerStreamWithErrorResponseBody(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend,std::string response_body)3253   ServerStreamWithErrorResponseBody(
3254       QuicStreamId id,
3255       QuicSpdySession* session,
3256       QuicSimpleServerBackend* quic_simple_server_backend,
3257       std::string response_body)
3258       : QuicSimpleServerStream(id,
3259                                session,
3260                                BIDIRECTIONAL,
3261                                quic_simple_server_backend),
3262         response_body_(std::move(response_body)) {}
3263 
3264   ~ServerStreamWithErrorResponseBody() override = default;
3265 
3266  protected:
SendErrorResponse()3267   void SendErrorResponse() override {
3268     QUIC_DLOG(INFO) << "Sending error response for stream " << id();
3269     SpdyHeaderBlock headers;
3270     headers[":status"] = "500";
3271     headers["content-length"] =
3272         quiche::QuicheTextUtils::Uint64ToString(response_body_.size());
3273     // This method must call CloseReadSide to cause the test case, StopReading
3274     // is not sufficient.
3275     QuicStreamPeer::CloseReadSide(this);
3276     SendHeadersAndBody(std::move(headers), response_body_);
3277   }
3278 
3279   std::string response_body_;
3280 };
3281 
3282 class StreamWithErrorFactory : public QuicTestServer::StreamFactory {
3283  public:
StreamWithErrorFactory(std::string response_body)3284   explicit StreamWithErrorFactory(std::string response_body)
3285       : response_body_(std::move(response_body)) {}
3286 
3287   ~StreamWithErrorFactory() override = default;
3288 
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)3289   QuicSimpleServerStream* CreateStream(
3290       QuicStreamId id,
3291       QuicSpdySession* session,
3292       QuicSimpleServerBackend* quic_simple_server_backend) override {
3293     return new ServerStreamWithErrorResponseBody(
3294         id, session, quic_simple_server_backend, response_body_);
3295   }
3296 
3297  private:
3298   std::string response_body_;
3299 };
3300 
3301 // A test server stream that drops all received body.
3302 class ServerStreamThatDropsBody : public QuicSimpleServerStream {
3303  public:
ServerStreamThatDropsBody(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)3304   ServerStreamThatDropsBody(QuicStreamId id,
3305                             QuicSpdySession* session,
3306                             QuicSimpleServerBackend* quic_simple_server_backend)
3307       : QuicSimpleServerStream(id,
3308                                session,
3309                                BIDIRECTIONAL,
3310                                quic_simple_server_backend) {}
3311 
3312   ~ServerStreamThatDropsBody() override = default;
3313 
3314  protected:
OnBodyAvailable()3315   void OnBodyAvailable() override {
3316     while (HasBytesToRead()) {
3317       struct iovec iov;
3318       if (GetReadableRegions(&iov, 1) == 0) {
3319         // No more data to read.
3320         break;
3321       }
3322       QUIC_DVLOG(1) << "Processed " << iov.iov_len << " bytes for stream "
3323                     << id();
3324       MarkConsumed(iov.iov_len);
3325     }
3326 
3327     if (!sequencer()->IsClosed()) {
3328       sequencer()->SetUnblocked();
3329       return;
3330     }
3331 
3332     // If the sequencer is closed, then all the body, including the fin, has
3333     // been consumed.
3334     OnFinRead();
3335 
3336     if (write_side_closed() || fin_buffered()) {
3337       return;
3338     }
3339 
3340     SendResponse();
3341   }
3342 };
3343 
3344 class ServerStreamThatDropsBodyFactory : public QuicTestServer::StreamFactory {
3345  public:
3346   ServerStreamThatDropsBodyFactory() = default;
3347 
3348   ~ServerStreamThatDropsBodyFactory() override = default;
3349 
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)3350   QuicSimpleServerStream* CreateStream(
3351       QuicStreamId id,
3352       QuicSpdySession* session,
3353       QuicSimpleServerBackend* quic_simple_server_backend) override {
3354     return new ServerStreamThatDropsBody(id, session,
3355                                          quic_simple_server_backend);
3356   }
3357 };
3358 
3359 // A test server stream that sends response with body size greater than 4GB.
3360 class ServerStreamThatSendsHugeResponse : public QuicSimpleServerStream {
3361  public:
ServerStreamThatSendsHugeResponse(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend,int64_t body_bytes)3362   ServerStreamThatSendsHugeResponse(
3363       QuicStreamId id,
3364       QuicSpdySession* session,
3365       QuicSimpleServerBackend* quic_simple_server_backend,
3366       int64_t body_bytes)
3367       : QuicSimpleServerStream(id,
3368                                session,
3369                                BIDIRECTIONAL,
3370                                quic_simple_server_backend),
3371         body_bytes_(body_bytes) {}
3372 
3373   ~ServerStreamThatSendsHugeResponse() override = default;
3374 
3375  protected:
SendResponse()3376   void SendResponse() override {
3377     QuicBackendResponse response;
3378     std::string body(body_bytes_, 'a');
3379     response.set_body(body);
3380     SendHeadersAndBodyAndTrailers(response.headers().Clone(), response.body(),
3381                                   response.trailers().Clone());
3382   }
3383 
3384  private:
3385   // Use a explicit int64_t rather than size_t to simulate a 64-bit server
3386   // talking to a 32-bit client.
3387   int64_t body_bytes_;
3388 };
3389 
3390 class ServerStreamThatSendsHugeResponseFactory
3391     : public QuicTestServer::StreamFactory {
3392  public:
ServerStreamThatSendsHugeResponseFactory(int64_t body_bytes)3393   explicit ServerStreamThatSendsHugeResponseFactory(int64_t body_bytes)
3394       : body_bytes_(body_bytes) {}
3395 
3396   ~ServerStreamThatSendsHugeResponseFactory() override = default;
3397 
CreateStream(QuicStreamId id,QuicSpdySession * session,QuicSimpleServerBackend * quic_simple_server_backend)3398   QuicSimpleServerStream* CreateStream(
3399       QuicStreamId id,
3400       QuicSpdySession* session,
3401       QuicSimpleServerBackend* quic_simple_server_backend) override {
3402     return new ServerStreamThatSendsHugeResponse(
3403         id, session, quic_simple_server_backend, body_bytes_);
3404   }
3405 
3406   int64_t body_bytes_;
3407 };
3408 
TEST_P(EndToEndTest,EarlyResponseFinRecording)3409 TEST_P(EndToEndTest, EarlyResponseFinRecording) {
3410   set_smaller_flow_control_receive_window();
3411 
3412   // Verify that an incoming FIN is recorded in a stream object even if the read
3413   // side has been closed.  This prevents an entry from being made in
3414   // locally_close_streams_highest_offset_ (which will never be deleted).
3415   // To set up the test condition, the server must do the following in order:
3416   // start sending the response and call CloseReadSide
3417   // receive the FIN of the request
3418   // send the FIN of the response
3419 
3420   // The response body must be larger than the flow control window so the server
3421   // must receive a window update from the client before it can finish sending
3422   // it.
3423   uint32_t response_body_size =
3424       2 * client_config_.GetInitialStreamFlowControlWindowToSend();
3425   std::string response_body(response_body_size, 'a');
3426 
3427   StreamWithErrorFactory stream_factory(response_body);
3428   SetSpdyStreamFactory(&stream_factory);
3429 
3430   ASSERT_TRUE(Initialize());
3431 
3432   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3433 
3434   // A POST that gets an early error response, after the headers are received
3435   // and before the body is received, due to invalid content-length.
3436   // Set an invalid content-length, so the request will receive an early 500
3437   // response.
3438   SpdyHeaderBlock headers;
3439   headers[":method"] = "POST";
3440   headers[":path"] = "/garbage";
3441   headers[":scheme"] = "https";
3442   headers[":authority"] = server_hostname_;
3443   headers["content-length"] = "-1";
3444 
3445   // The body must be large enough that the FIN will be in a different packet
3446   // than the end of the headers, but short enough to not require a flow control
3447   // update.  This allows headers processing to trigger the error response
3448   // before the request FIN is processed but receive the request FIN before the
3449   // response is sent completely.
3450   const uint32_t kRequestBodySize = kMaxOutgoingPacketSize + 10;
3451   std::string request_body(kRequestBodySize, 'a');
3452 
3453   // Send the request.
3454   client_->SendMessage(headers, request_body);
3455   client_->WaitForResponse();
3456   CheckResponseHeaders("500");
3457 
3458   // Pause the server so we can access the server's internals without races.
3459   server_thread_->Pause();
3460 
3461   QuicDispatcher* dispatcher =
3462       QuicServerPeer::GetDispatcher(server_thread_->server());
3463   QuicDispatcher::SessionMap const& map =
3464       QuicDispatcherPeer::session_map(dispatcher);
3465   auto it = map.begin();
3466   EXPECT_TRUE(it != map.end());
3467   QuicSession* server_session = it->second.get();
3468 
3469   // The stream is not waiting for the arrival of the peer's final offset.
3470   EXPECT_EQ(
3471       0u, QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(server_session)
3472               .size());
3473 
3474   server_thread_->Resume();
3475 }
3476 
TEST_P(EndToEndTest,Trailers)3477 TEST_P(EndToEndTest, Trailers) {
3478   // Test sending and receiving HTTP/2 Trailers (trailing HEADERS frames).
3479   ASSERT_TRUE(Initialize());
3480   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3481 
3482   // Set reordering to ensure that Trailers arriving before body is ok.
3483   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
3484   SetReorderPercentage(30);
3485 
3486   // Add a response with headers, body, and trailers.
3487   const std::string kBody = "body content";
3488 
3489   SpdyHeaderBlock headers;
3490   headers[":status"] = "200";
3491   headers["content-length"] =
3492       quiche::QuicheTextUtils::Uint64ToString(kBody.size());
3493 
3494   SpdyHeaderBlock trailers;
3495   trailers["some-trailing-header"] = "trailing-header-value";
3496 
3497   memory_cache_backend_.AddResponse(server_hostname_, "/trailer_url",
3498                                     std::move(headers), kBody,
3499                                     trailers.Clone());
3500 
3501   SendSynchronousRequestAndCheckResponse("/trailer_url", kBody);
3502   EXPECT_EQ(trailers, client_->response_trailers());
3503 }
3504 
3505 // TODO(b/151749109): Test server push for IETF QUIC.
3506 class EndToEndTestServerPush : public EndToEndTest {
3507  protected:
3508   const size_t kNumMaxStreams = 10;
3509 
EndToEndTestServerPush()3510   EndToEndTestServerPush() : EndToEndTest() {
3511     SetQuicFlag(FLAGS_quic_enable_http3_server_push, true);
3512     client_config_.SetMaxBidirectionalStreamsToSend(kNumMaxStreams);
3513     server_config_.SetMaxBidirectionalStreamsToSend(kNumMaxStreams);
3514     client_config_.SetMaxUnidirectionalStreamsToSend(kNumMaxStreams);
3515     server_config_.SetMaxUnidirectionalStreamsToSend(kNumMaxStreams);
3516   }
3517 
3518   // Add a request with its response and |num_resources| push resources into
3519   // cache.
3520   // If |resource_size| == 0, response body of push resources use default string
3521   // concatenating with resource url. Otherwise, generate a string of
3522   // |resource_size| as body.
AddRequestAndResponseWithServerPush(std::string host,std::string path,std::string response_body,std::string * push_urls,const size_t num_resources,const size_t resource_size)3523   void AddRequestAndResponseWithServerPush(std::string host,
3524                                            std::string path,
3525                                            std::string response_body,
3526                                            std::string* push_urls,
3527                                            const size_t num_resources,
3528                                            const size_t resource_size) {
3529     bool use_large_response = resource_size != 0;
3530     std::string large_resource;
3531     if (use_large_response) {
3532       // Generate a response common body larger than flow control window for
3533       // push response.
3534       large_resource = std::string(resource_size, 'a');
3535     }
3536     std::list<QuicBackendResponse::ServerPushInfo> push_resources;
3537     for (size_t i = 0; i < num_resources; ++i) {
3538       std::string url = push_urls[i];
3539       QuicUrl resource_url(url);
3540       std::string body =
3541           use_large_response
3542               ? large_resource
3543               : quiche::QuicheStrCat("This is server push response body for ",
3544                                      url);
3545       SpdyHeaderBlock response_headers;
3546       response_headers[":status"] = "200";
3547       response_headers["content-length"] =
3548           quiche::QuicheTextUtils::Uint64ToString(body.size());
3549       push_resources.push_back(QuicBackendResponse::ServerPushInfo(
3550           resource_url, std::move(response_headers), kV3LowestPriority, body));
3551     }
3552 
3553     memory_cache_backend_.AddSimpleResponseWithServerPushResources(
3554         host, path, 200, response_body, push_resources);
3555   }
3556 };
3557 
3558 // Run all server push end to end tests with all supported versions.
3559 INSTANTIATE_TEST_SUITE_P(EndToEndTestsServerPush,
3560                          EndToEndTestServerPush,
3561                          ::testing::ValuesIn(GetTestParams()),
3562                          ::testing::PrintToStringParamName());
3563 
TEST_P(EndToEndTestServerPush,ServerPush)3564 TEST_P(EndToEndTestServerPush, ServerPush) {
3565   ASSERT_TRUE(Initialize());
3566   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3567 
3568   // Set reordering to ensure that body arriving before PUSH_PROMISE is ok.
3569   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
3570   SetReorderPercentage(30);
3571 
3572   // Add a response with headers, body, and push resources.
3573   const std::string kBody = "body content";
3574   size_t kNumResources = 4;
3575   std::string push_urls[] = {"https://example.com/font.woff",
3576                              "https://example.com/script.js",
3577                              "https://fonts.example.com/font.woff",
3578                              "https://example.com/logo-hires.jpg"};
3579   AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody,
3580                                       push_urls, kNumResources, 0);
3581 
3582   client_->client()->set_response_listener(
3583       std::unique_ptr<QuicSpdyClientBase::ResponseListener>(
3584           new TestResponseListener));
3585 
3586   QUIC_DVLOG(1) << "send request for /push_example";
3587   EXPECT_EQ(kBody, client_->SendSynchronousRequest(
3588                        "https://example.com/push_example"));
3589   QuicStreamSequencer* sequencer = nullptr;
3590   if (!version_.UsesHttp3()) {
3591     QuicSpdyClientSession* client_session = GetClientSession();
3592     ASSERT_TRUE(client_session);
3593     QuicHeadersStream* headers_stream =
3594         QuicSpdySessionPeer::GetHeadersStream(client_session);
3595     ASSERT_TRUE(headers_stream);
3596     sequencer = QuicStreamPeer::sequencer(headers_stream);
3597     ASSERT_TRUE(sequencer);
3598     // Headers stream's sequencer buffer shouldn't be released because server
3599     // push hasn't finished yet.
3600     EXPECT_TRUE(
3601         QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer));
3602   }
3603 
3604   for (const std::string& url : push_urls) {
3605     QUIC_DVLOG(1) << "send request for pushed stream on url " << url;
3606     std::string expected_body =
3607         quiche::QuicheStrCat("This is server push response body for ", url);
3608     std::string response_body = client_->SendSynchronousRequest(url);
3609     QUIC_DVLOG(1) << "response body " << response_body;
3610     EXPECT_EQ(expected_body, response_body);
3611   }
3612   if (!version_.UsesHttp3()) {
3613     ASSERT_TRUE(sequencer);
3614     EXPECT_FALSE(
3615         QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer));
3616   }
3617 }
3618 
TEST_P(EndToEndTestServerPush,ServerPushUnderLimit)3619 TEST_P(EndToEndTestServerPush, ServerPushUnderLimit) {
3620   // Tests that sending a request which has 4 push resources will trigger server
3621   // to push those 4 resources and client can handle pushed resources and match
3622   // them with requests later.
3623   ASSERT_TRUE(Initialize());
3624 
3625   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3626   if (version_.UsesHttp3()) {
3627     static_cast<QuicSpdySession*>(client_->client()->session())
3628         ->SetMaxPushId(kMaxQuicStreamId);
3629   }
3630 
3631   // Set reordering to ensure that body arriving before PUSH_PROMISE is ok.
3632   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
3633   SetReorderPercentage(30);
3634 
3635   // Add a response with headers, body, and push resources.
3636   const std::string kBody = "body content";
3637   size_t const kNumResources = 4;
3638   std::string push_urls[] = {
3639       "https://example.com/font.woff",
3640       "https://example.com/script.js",
3641       "https://fonts.example.com/font.woff",
3642       "https://example.com/logo-hires.jpg",
3643   };
3644   AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody,
3645                                       push_urls, kNumResources, 0);
3646   client_->client()->set_response_listener(
3647       std::unique_ptr<QuicSpdyClientBase::ResponseListener>(
3648           new TestResponseListener));
3649 
3650   // Send the first request: this will trigger the server to send all the push
3651   // resources associated with this request, and these will be cached by the
3652   // client.
3653   EXPECT_EQ(kBody, client_->SendSynchronousRequest(
3654                        "https://example.com/push_example"));
3655 
3656   for (const std::string& url : push_urls) {
3657     // Sending subsequent requesets will not actually send anything on the wire,
3658     // as the responses are already in the client's cache.
3659     QUIC_DVLOG(1) << "send request for pushed stream on url " << url;
3660     std::string expected_body =
3661         quiche::QuicheStrCat("This is server push response body for ", url);
3662     std::string response_body = client_->SendSynchronousRequest(url);
3663     QUIC_DVLOG(1) << "response body " << response_body;
3664     EXPECT_EQ(expected_body, response_body);
3665   }
3666   // Expect only original request has been sent and push responses have been
3667   // received as normal response.
3668   EXPECT_EQ(1u, client_->num_requests());
3669   EXPECT_EQ(1u + kNumResources, client_->num_responses());
3670 }
3671 
TEST_P(EndToEndTestServerPush,ServerPushOverLimitNonBlocking)3672 TEST_P(EndToEndTestServerPush, ServerPushOverLimitNonBlocking) {
3673   if (version_.UsesHttp3()) {
3674     // TODO(b/142504641): Re-enable this test when we support push streams
3675     // arriving before the corresponding promises.
3676     ASSERT_TRUE(Initialize());
3677     return;
3678   }
3679   // Tests that when streams are not blocked by flow control or congestion
3680   // control, pushing even more resources than max number of open outgoing
3681   // streams should still work because all response streams get closed
3682   // immediately after pushing resources.
3683   ASSERT_TRUE(Initialize());
3684   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3685   if (version_.UsesHttp3()) {
3686     static_cast<QuicSpdySession*>(client_->client()->session())
3687         ->SetMaxPushId(kMaxQuicStreamId);
3688   }
3689 
3690   // Set reordering to ensure that body arriving before PUSH_PROMISE is ok.
3691   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
3692   SetReorderPercentage(30);
3693 
3694   // Add a response with headers, body, and push resources.
3695   const std::string kBody = "body content";
3696 
3697   // One more resource than max number of outgoing stream of this session.
3698   const size_t kNumResources = 1 + kNumMaxStreams;  // 11.
3699   std::string push_urls[11];
3700   for (size_t i = 0; i < kNumResources; ++i) {
3701     push_urls[i] =
3702         quiche::QuicheStrCat("https://example.com/push_resources", i);
3703   }
3704   AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody,
3705                                       push_urls, kNumResources, 0);
3706   client_->client()->set_response_listener(
3707       std::unique_ptr<QuicSpdyClientBase::ResponseListener>(
3708           new TestResponseListener));
3709 
3710   // Send the first request: this will trigger the server to send all the push
3711   // resources associated with this request, and these will be cached by the
3712   // client.
3713   EXPECT_EQ(kBody, client_->SendSynchronousRequest(
3714                        "https://example.com/push_example"));
3715 
3716   for (const std::string& url : push_urls) {
3717     // Sending subsequent requesets will not actually send anything on the wire,
3718     // as the responses are already in the client's cache.
3719     EXPECT_EQ(
3720         quiche::QuicheStrCat("This is server push response body for ", url),
3721         client_->SendSynchronousRequest(url));
3722   }
3723 
3724   // Only 1 request should have been sent.
3725   EXPECT_EQ(1u, client_->num_requests());
3726   // The responses to the original request and all the promised resources
3727   // should have been received.
3728   EXPECT_EQ(12u, client_->num_responses());
3729 }
3730 
TEST_P(EndToEndTestServerPush,ServerPushOverLimitWithBlocking)3731 TEST_P(EndToEndTestServerPush, ServerPushOverLimitWithBlocking) {
3732   // Tests that when server tries to send more large resources(large enough to
3733   // be blocked by flow control window or congestion control window) than max
3734   // open outgoing streams , server can open upto max number of outgoing
3735   // streams for them, and the rest will be queued up.
3736 
3737   // Reset flow control windows.
3738   size_t kFlowControlWnd = 20 * 1024;  // 20KB.
3739   // Response body is larger than 1 flow controlblock window.
3740   size_t kBodySize = kFlowControlWnd * 2;
3741   set_client_initial_stream_flow_control_receive_window(kFlowControlWnd);
3742   // Make sure conntection level flow control window is large enough not to
3743   // block data being sent out though they will be blocked by stream level one.
3744   set_client_initial_session_flow_control_receive_window(
3745       kBodySize * kNumMaxStreams + 1024);
3746 
3747   ASSERT_TRUE(Initialize());
3748   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3749   if (version_.UsesHttp3()) {
3750     static_cast<QuicSpdySession*>(client_->client()->session())
3751         ->SetMaxPushId(kMaxQuicStreamId);
3752   }
3753 
3754   // Set reordering to ensure that body arriving before PUSH_PROMISE is ok.
3755   SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2));
3756   SetReorderPercentage(30);
3757 
3758   // Add a response with headers, body, and push resources.
3759   const std::string kBody = "body content";
3760 
3761   const size_t kNumResources = kNumMaxStreams + 1;
3762   std::string push_urls[11];
3763   for (size_t i = 0; i < kNumResources; ++i) {
3764     push_urls[i] = quiche::QuicheStrCat("http://example.com/push_resources", i);
3765   }
3766   AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody,
3767                                       push_urls, kNumResources, kBodySize);
3768 
3769   client_->client()->set_response_listener(
3770       std::unique_ptr<QuicSpdyClientBase::ResponseListener>(
3771           new TestResponseListener));
3772 
3773   client_->SendRequest("https://example.com/push_example");
3774 
3775   // Pause after the first response arrives.
3776   while (!client_->response_complete()) {
3777     // Because of priority, the first response arrived should be to original
3778     // request.
3779     client_->WaitForResponse();
3780     ASSERT_TRUE(client_->connected());
3781   }
3782 
3783   // Check server session to see if it has max number of outgoing streams opened
3784   // though more resources need to be pushed.
3785   if (!version_.HasIetfQuicFrames()) {
3786     server_thread_->Pause();
3787     QuicSession* server_session = GetServerSession();
3788     if (server_session != nullptr) {
3789       EXPECT_EQ(kNumMaxStreams,
3790                 QuicSessionPeer::GetStreamIdManager(server_session)
3791                     ->num_open_outgoing_streams());
3792     } else {
3793       ADD_FAILURE() << "Missing server session";
3794     }
3795     server_thread_->Resume();
3796   }
3797 
3798   EXPECT_EQ(1u, client_->num_requests());
3799   EXPECT_EQ(1u, client_->num_responses());
3800   EXPECT_EQ(kBody, client_->response_body());
3801 
3802   // "Send" request for a promised resources will not really send out it because
3803   // its response is being pushed(but blocked). And the following ack and
3804   // flow control behavior of SendSynchronousRequests()
3805   // will unblock the stream to finish receiving response.
3806   client_->SendSynchronousRequest(push_urls[0]);
3807   EXPECT_EQ(1u, client_->num_requests());
3808   EXPECT_EQ(2u, client_->num_responses());
3809 
3810   // Do same thing for the rest 10 resources.
3811   for (size_t i = 1; i < kNumResources; ++i) {
3812     client_->SendSynchronousRequest(push_urls[i]);
3813   }
3814 
3815   // Because of server push, client gets all pushed resources without actually
3816   // sending requests for them.
3817   EXPECT_EQ(1u, client_->num_requests());
3818   // Including response to original request, 12 responses in total were
3819   // received.
3820   EXPECT_EQ(12u, client_->num_responses());
3821 }
3822 
3823 // TODO(fayang): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,DISABLED_TestHugePostWithPacketLoss)3824 TEST_P(EndToEndTest, DISABLED_TestHugePostWithPacketLoss) {
3825   // This test tests a huge post with introduced packet loss from client to
3826   // server and body size greater than 4GB, making sure QUIC code does not break
3827   // for 32-bit builds.
3828   ServerStreamThatDropsBodyFactory stream_factory;
3829   SetSpdyStreamFactory(&stream_factory);
3830   ASSERT_TRUE(Initialize());
3831   // Set client's epoll server's time out to 0 to make this test be finished
3832   // within a short time.
3833   client_->epoll_server()->set_timeout_in_us(0);
3834 
3835   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3836   SetPacketLossPercentage(1);
3837   // To avoid storing the whole request body in memory, use a loop to repeatedly
3838   // send body size of kSizeBytes until the whole request body size is reached.
3839   const int kSizeBytes = 128 * 1024;
3840   // Request body size is 4G plus one more kSizeBytes.
3841   int64_t request_body_size_bytes = pow(2, 32) + kSizeBytes;
3842   ASSERT_LT(INT64_C(4294967296), request_body_size_bytes);
3843   std::string body(kSizeBytes, 'a');
3844 
3845   SpdyHeaderBlock headers;
3846   headers[":method"] = "POST";
3847   headers[":path"] = "/foo";
3848   headers[":scheme"] = "https";
3849   headers[":authority"] = server_hostname_;
3850   headers["content-length"] =
3851       quiche::QuicheTextUtils::Uint64ToString(request_body_size_bytes);
3852 
3853   client_->SendMessage(headers, "", /*fin=*/false);
3854 
3855   for (int i = 0; i < request_body_size_bytes / kSizeBytes; ++i) {
3856     bool fin = (i == request_body_size_bytes - 1);
3857     client_->SendData(std::string(body.data(), kSizeBytes), fin);
3858     client_->client()->WaitForEvents();
3859   }
3860   VerifyCleanConnection(true);
3861 }
3862 
3863 // TODO(fayang): this test seems to cause net_unittests timeouts :|
TEST_P(EndToEndTest,DISABLED_TestHugeResponseWithPacketLoss)3864 TEST_P(EndToEndTest, DISABLED_TestHugeResponseWithPacketLoss) {
3865   // This test tests a huge response with introduced loss from server to client
3866   // and body size greater than 4GB, making sure QUIC code does not break for
3867   // 32-bit builds.
3868   const int kSizeBytes = 128 * 1024;
3869   int64_t response_body_size_bytes = pow(2, 32) + kSizeBytes;
3870   ASSERT_LT(4294967296, response_body_size_bytes);
3871   ServerStreamThatSendsHugeResponseFactory stream_factory(
3872       response_body_size_bytes);
3873   SetSpdyStreamFactory(&stream_factory);
3874 
3875   StartServer();
3876 
3877   // Use a quic client that drops received body.
3878   QuicTestClient* client =
3879       new QuicTestClient(server_address_, server_hostname_, client_config_,
3880                          client_supported_versions_);
3881   client->client()->set_drop_response_body(true);
3882   client->UseWriter(client_writer_);
3883   client->Connect();
3884   client_.reset(client);
3885   static QuicEpollEvent event(EPOLLOUT);
3886   QuicConnection* client_connection = GetClientConnection();
3887   ASSERT_TRUE(client_connection);
3888   client_writer_->Initialize(
3889       QuicConnectionPeer::GetHelper(client_connection),
3890       QuicConnectionPeer::GetAlarmFactory(client_connection),
3891       std::make_unique<ClientDelegate>(client_->client()));
3892   initialized_ = true;
3893   ASSERT_TRUE(client_->client()->connected());
3894 
3895   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3896   SetPacketLossPercentage(1);
3897   client_->SendRequest("/huge_response");
3898   client_->WaitForResponse();
3899   VerifyCleanConnection(true);
3900 }
3901 
3902 // Regression test for b/111515567
TEST_P(EndToEndTest,AgreeOnStopWaiting)3903 TEST_P(EndToEndTest, AgreeOnStopWaiting) {
3904   ASSERT_TRUE(Initialize());
3905   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3906 
3907   QuicConnection* client_connection = GetClientConnection();
3908   ASSERT_TRUE(client_connection);
3909   server_thread_->Pause();
3910   QuicConnection* server_connection = GetServerConnection();
3911   if (server_connection != nullptr) {
3912     // Verify client and server connections agree on the value of
3913     // no_stop_waiting_frames.
3914     EXPECT_EQ(QuicConnectionPeer::GetNoStopWaitingFrames(client_connection),
3915               QuicConnectionPeer::GetNoStopWaitingFrames(server_connection));
3916   } else {
3917     ADD_FAILURE() << "Missing server connection";
3918   }
3919   server_thread_->Resume();
3920 }
3921 
3922 // Regression test for b/111515567
TEST_P(EndToEndTest,AgreeOnStopWaitingWithNoStopWaitingOption)3923 TEST_P(EndToEndTest, AgreeOnStopWaitingWithNoStopWaitingOption) {
3924   QuicTagVector options;
3925   options.push_back(kNSTP);
3926   client_config_.SetConnectionOptionsToSend(options);
3927   ASSERT_TRUE(Initialize());
3928   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
3929 
3930   QuicConnection* client_connection = GetClientConnection();
3931   ASSERT_TRUE(client_connection);
3932   server_thread_->Pause();
3933   QuicConnection* server_connection = GetServerConnection();
3934   if (server_connection != nullptr) {
3935     // Verify client and server connections agree on the value of
3936     // no_stop_waiting_frames.
3937     EXPECT_EQ(QuicConnectionPeer::GetNoStopWaitingFrames(client_connection),
3938               QuicConnectionPeer::GetNoStopWaitingFrames(server_connection));
3939   } else {
3940     ADD_FAILURE() << "Missing server connection";
3941   }
3942   server_thread_->Resume();
3943 }
3944 
TEST_P(EndToEndTest,ReleaseHeadersStreamBufferWhenIdle)3945 TEST_P(EndToEndTest, ReleaseHeadersStreamBufferWhenIdle) {
3946   // Tests that when client side has no active request and no waiting
3947   // PUSH_PROMISE, its headers stream's sequencer buffer should be released.
3948   ASSERT_TRUE(Initialize());
3949   client_->SendSynchronousRequest("/foo");
3950   if (version_.UsesHttp3()) {
3951     return;
3952   }
3953   QuicSpdyClientSession* client_session = GetClientSession();
3954   ASSERT_TRUE(client_session);
3955   QuicHeadersStream* headers_stream =
3956       QuicSpdySessionPeer::GetHeadersStream(client_session);
3957   ASSERT_TRUE(headers_stream);
3958   QuicStreamSequencer* sequencer = QuicStreamPeer::sequencer(headers_stream);
3959   ASSERT_TRUE(sequencer);
3960   EXPECT_FALSE(QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer));
3961 }
3962 
3963 // A single large header value causes a different error than the total size of
3964 // headers exceeding a smaller limit, tested at EndToEndTest.LargeHeaders.
TEST_P(EndToEndTest,WayTooLongRequestHeaders)3965 TEST_P(EndToEndTest, WayTooLongRequestHeaders) {
3966   ASSERT_TRUE(Initialize());
3967 
3968   SpdyHeaderBlock headers;
3969   headers[":method"] = "GET";
3970   headers[":path"] = "/foo";
3971   headers[":scheme"] = "https";
3972   headers[":authority"] = server_hostname_;
3973   headers["key"] = std::string(2 * 1024 * 1024, 'a');
3974 
3975   client_->SendMessage(headers, "");
3976   client_->WaitForResponse();
3977   if (version_.UsesHttp3()) {
3978     EXPECT_THAT(client_->connection_error(),
3979                 IsError(QUIC_QPACK_DECOMPRESSION_FAILED));
3980   } else {
3981     EXPECT_THAT(client_->connection_error(),
3982                 IsError(QUIC_HPACK_VALUE_TOO_LONG));
3983   }
3984 }
3985 
3986 class WindowUpdateObserver : public QuicConnectionDebugVisitor {
3987  public:
WindowUpdateObserver()3988   WindowUpdateObserver() : num_window_update_frames_(0), num_ping_frames_(0) {}
3989 
num_window_update_frames() const3990   size_t num_window_update_frames() const { return num_window_update_frames_; }
3991 
num_ping_frames() const3992   size_t num_ping_frames() const { return num_ping_frames_; }
3993 
OnWindowUpdateFrame(const QuicWindowUpdateFrame &,const QuicTime &)3994   void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/,
3995                            const QuicTime& /*receive_time*/) override {
3996     ++num_window_update_frames_;
3997   }
3998 
OnPingFrame(const QuicPingFrame &,const QuicTime::Delta)3999   void OnPingFrame(const QuicPingFrame& /*frame*/,
4000                    const QuicTime::Delta /*ping_received_delay*/) override {
4001     ++num_ping_frames_;
4002   }
4003 
4004  private:
4005   size_t num_window_update_frames_;
4006   size_t num_ping_frames_;
4007 };
4008 
TEST_P(EndToEndTest,WindowUpdateInAck)4009 TEST_P(EndToEndTest, WindowUpdateInAck) {
4010   ASSERT_TRUE(Initialize());
4011   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4012   WindowUpdateObserver observer;
4013   QuicConnection* client_connection = GetClientConnection();
4014   ASSERT_TRUE(client_connection);
4015   client_connection->set_debug_visitor(&observer);
4016   // 100KB body.
4017   std::string body(100 * 1024, 'a');
4018   SpdyHeaderBlock headers;
4019   headers[":method"] = "POST";
4020   headers[":path"] = "/foo";
4021   headers[":scheme"] = "https";
4022   headers[":authority"] = server_hostname_;
4023 
4024   EXPECT_EQ(kFooResponseBody,
4025             client_->SendCustomSynchronousRequest(headers, body));
4026   client_->Disconnect();
4027   EXPECT_LT(0u, observer.num_window_update_frames());
4028   EXPECT_EQ(0u, observer.num_ping_frames());
4029   client_connection->set_debug_visitor(nullptr);
4030 }
4031 
TEST_P(EndToEndTest,SendStatelessResetTokenInShlo)4032 TEST_P(EndToEndTest, SendStatelessResetTokenInShlo) {
4033   ASSERT_TRUE(Initialize());
4034   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4035   QuicSpdyClientSession* client_session = GetClientSession();
4036   ASSERT_TRUE(client_session);
4037   QuicConfig* config = client_session->config();
4038   ASSERT_TRUE(config);
4039   EXPECT_TRUE(config->HasReceivedStatelessResetToken());
4040   QuicConnection* client_connection = client_session->connection();
4041   ASSERT_TRUE(client_connection);
4042   EXPECT_EQ(QuicUtils::GenerateStatelessResetToken(
4043                 client_connection->connection_id()),
4044             config->ReceivedStatelessResetToken());
4045   client_->Disconnect();
4046 }
4047 
4048 // Regression test for b/116200989.
TEST_P(EndToEndTest,SendStatelessResetIfServerConnectionClosedLocallyDuringHandshake)4049 TEST_P(EndToEndTest,
4050        SendStatelessResetIfServerConnectionClosedLocallyDuringHandshake) {
4051   connect_to_server_on_initialize_ = false;
4052   ASSERT_TRUE(Initialize());
4053 
4054   ASSERT_TRUE(server_thread_);
4055   server_thread_->Pause();
4056   QuicDispatcher* dispatcher =
4057       QuicServerPeer::GetDispatcher(server_thread_->server());
4058   if (dispatcher == nullptr) {
4059     ADD_FAILURE() << "Missing dispatcher";
4060     server_thread_->Resume();
4061     return;
4062   }
4063   if (!dispatcher->session_map().empty()) {
4064     ADD_FAILURE() << "Dispatcher session map not empty";
4065     server_thread_->Resume();
4066     return;
4067   }
4068   // Note: this writer will only used by the server connection, not the time
4069   // wait list.
4070   QuicDispatcherPeer::UseWriter(
4071       dispatcher,
4072       // This cause the first server-sent packet, a.k.a REJ, to fail.
4073       new BadPacketWriter(/*packet_causing_write_error=*/0, EPERM));
4074   server_thread_->Resume();
4075 
4076   client_.reset(CreateQuicClient(client_writer_));
4077   EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4078   EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_FAILED));
4079 }
4080 
4081 // Regression test for b/116200989.
TEST_P(EndToEndTest,SendStatelessResetIfServerConnectionClosedLocallyAfterHandshake)4082 TEST_P(EndToEndTest,
4083        SendStatelessResetIfServerConnectionClosedLocallyAfterHandshake) {
4084   // Prevent the connection from expiring in the time wait list.
4085   SetQuicFlag(FLAGS_quic_time_wait_list_seconds, 10000);
4086   connect_to_server_on_initialize_ = false;
4087   ASSERT_TRUE(Initialize());
4088 
4089   // big_response_body is 64K, which is about 48 full-sized packets.
4090   const size_t kBigResponseBodySize = 65536;
4091   QuicData big_response_body(new char[kBigResponseBodySize](),
4092                              kBigResponseBodySize, /*owns_buffer=*/true);
4093   AddToCache("/big_response", 200, big_response_body.AsStringPiece());
4094 
4095   ASSERT_TRUE(server_thread_);
4096   server_thread_->Pause();
4097   QuicDispatcher* dispatcher =
4098       QuicServerPeer::GetDispatcher(server_thread_->server());
4099   if (dispatcher == nullptr) {
4100     ADD_FAILURE() << "Missing dispatcher";
4101     server_thread_->Resume();
4102     return;
4103   }
4104   if (!dispatcher->session_map().empty()) {
4105     ADD_FAILURE() << "Dispatcher session map not empty";
4106     server_thread_->Resume();
4107     return;
4108   }
4109   QuicDispatcherPeer::UseWriter(
4110       dispatcher,
4111       // This will cause an server write error with EPERM, while sending the
4112       // response for /big_response.
4113       new BadPacketWriter(/*packet_causing_write_error=*/20, EPERM));
4114   server_thread_->Resume();
4115 
4116   client_.reset(CreateQuicClient(client_writer_));
4117 
4118   // First, a /foo request with small response should succeed.
4119   SendSynchronousFooRequestAndCheckResponse();
4120 
4121   // Second, a /big_response request with big response should fail.
4122   EXPECT_LT(client_->SendSynchronousRequest("/big_response").length(),
4123             kBigResponseBodySize);
4124   EXPECT_THAT(client_->connection_error(), IsError(QUIC_PUBLIC_RESET));
4125 }
4126 
4127 // Regression test of b/70782529.
TEST_P(EndToEndTest,DoNotCrashOnPacketWriteError)4128 TEST_P(EndToEndTest, DoNotCrashOnPacketWriteError) {
4129   ASSERT_TRUE(Initialize());
4130   BadPacketWriter* bad_writer =
4131       new BadPacketWriter(/*packet_causing_write_error=*/5,
4132                           /*error_code=*/90);
4133   std::unique_ptr<QuicTestClient> client(CreateQuicClient(bad_writer));
4134 
4135   // 1 MB body.
4136   std::string body(1024 * 1024, 'a');
4137   SpdyHeaderBlock headers;
4138   headers[":method"] = "POST";
4139   headers[":path"] = "/foo";
4140   headers[":scheme"] = "https";
4141   headers[":authority"] = server_hostname_;
4142 
4143   client->SendCustomSynchronousRequest(headers, body);
4144 }
4145 
4146 // Regression test for b/71711996. This test sends a connectivity probing packet
4147 // as its last sent packet, and makes sure the server's ACK of that packet does
4148 // not cause the client to fail.
TEST_P(EndToEndTest,LastPacketSentIsConnectivityProbing)4149 TEST_P(EndToEndTest, LastPacketSentIsConnectivityProbing) {
4150   ASSERT_TRUE(Initialize());
4151 
4152   SendSynchronousFooRequestAndCheckResponse();
4153 
4154   // Wait for the client's ACK (of the response) to be received by the server.
4155   client_->WaitForDelayedAcks();
4156 
4157   // We are sending a connectivity probing packet from an unchanged client
4158   // address, so the server will not respond to us with a connectivity probing
4159   // packet, however the server should send an ack-only packet to us.
4160   client_->SendConnectivityProbing();
4161 
4162   // Wait for the server's last ACK to be received by the client.
4163   client_->WaitForDelayedAcks();
4164 }
4165 
TEST_P(EndToEndTest,PreSharedKey)4166 TEST_P(EndToEndTest, PreSharedKey) {
4167   client_config_.set_max_time_before_crypto_handshake(
4168       QuicTime::Delta::FromSeconds(5));
4169   client_config_.set_max_idle_time_before_crypto_handshake(
4170       QuicTime::Delta::FromSeconds(5));
4171   pre_shared_key_client_ = "foobar";
4172   pre_shared_key_server_ = "foobar";
4173 
4174   if (version_.UsesTls()) {
4175     // TODO(b/154162689) add PSK support to QUIC+TLS.
4176     bool ok;
4177     EXPECT_QUIC_BUG(ok = Initialize(),
4178                     "QUIC client pre-shared keys not yet supported with TLS");
4179     EXPECT_FALSE(ok);
4180     return;
4181   }
4182 
4183   ASSERT_TRUE(Initialize());
4184 
4185   SendSynchronousFooRequestAndCheckResponse();
4186 }
4187 
4188 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyMismatch))4189 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyMismatch)) {
4190   client_config_.set_max_time_before_crypto_handshake(
4191       QuicTime::Delta::FromSeconds(1));
4192   client_config_.set_max_idle_time_before_crypto_handshake(
4193       QuicTime::Delta::FromSeconds(1));
4194   pre_shared_key_client_ = "foo";
4195   pre_shared_key_server_ = "bar";
4196 
4197   if (version_.UsesTls()) {
4198     // TODO(b/154162689) add PSK support to QUIC+TLS.
4199     bool ok;
4200     EXPECT_QUIC_BUG(ok = Initialize(),
4201                     "QUIC client pre-shared keys not yet supported with TLS");
4202     EXPECT_FALSE(ok);
4203     return;
4204   }
4205 
4206   // One of two things happens when Initialize() returns:
4207   // 1. Crypto handshake has completed, and it is unsuccessful. Initialize()
4208   //    returns false.
4209   // 2. Crypto handshake has not completed, Initialize() returns true. The call
4210   //    to WaitForCryptoHandshakeConfirmed() will wait for the handshake and
4211   //    return whether it is successful.
4212   ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
4213   EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
4214 }
4215 
4216 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyNoClient))4217 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyNoClient)) {
4218   client_config_.set_max_time_before_crypto_handshake(
4219       QuicTime::Delta::FromSeconds(1));
4220   client_config_.set_max_idle_time_before_crypto_handshake(
4221       QuicTime::Delta::FromSeconds(1));
4222   pre_shared_key_server_ = "foobar";
4223 
4224   if (version_.UsesTls()) {
4225     // TODO(b/154162689) add PSK support to QUIC+TLS.
4226     bool ok;
4227     EXPECT_QUIC_BUG(ok = Initialize(),
4228                     "QUIC server pre-shared keys not yet supported with TLS");
4229     EXPECT_FALSE(ok);
4230     return;
4231   }
4232 
4233   ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
4234   EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
4235 }
4236 
4237 // TODO: reenable once we have a way to make this run faster.
TEST_P(EndToEndTest,QUIC_TEST_DISABLED_IN_CHROME (PreSharedKeyNoServer))4238 TEST_P(EndToEndTest, QUIC_TEST_DISABLED_IN_CHROME(PreSharedKeyNoServer)) {
4239   client_config_.set_max_time_before_crypto_handshake(
4240       QuicTime::Delta::FromSeconds(1));
4241   client_config_.set_max_idle_time_before_crypto_handshake(
4242       QuicTime::Delta::FromSeconds(1));
4243   pre_shared_key_client_ = "foobar";
4244 
4245   if (version_.UsesTls()) {
4246     // TODO(b/154162689) add PSK support to QUIC+TLS.
4247     bool ok;
4248     EXPECT_QUIC_BUG(ok = Initialize(),
4249                     "QUIC client pre-shared keys not yet supported with TLS");
4250     EXPECT_FALSE(ok);
4251     return;
4252   }
4253 
4254   ASSERT_FALSE(Initialize() && client_->client()->WaitForOneRttKeysAvailable());
4255   EXPECT_THAT(client_->connection_error(), IsError(QUIC_HANDSHAKE_TIMEOUT));
4256 }
4257 
TEST_P(EndToEndTest,RequestAndStreamRstInOnePacket)4258 TEST_P(EndToEndTest, RequestAndStreamRstInOnePacket) {
4259   // Regression test for b/80234898.
4260   ASSERT_TRUE(Initialize());
4261 
4262   // INCOMPLETE_RESPONSE will cause the server to not to send the trailer
4263   // (and the FIN) after the response body.
4264   std::string response_body(1305, 'a');
4265   SpdyHeaderBlock response_headers;
4266   response_headers[":status"] = quiche::QuicheTextUtils::Uint64ToString(200);
4267   response_headers["content-length"] =
4268       quiche::QuicheTextUtils::Uint64ToString(response_body.length());
4269   memory_cache_backend_.AddSpecialResponse(
4270       server_hostname_, "/test_url", std::move(response_headers), response_body,
4271       QuicBackendResponse::INCOMPLETE_RESPONSE);
4272 
4273   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4274   client_->WaitForDelayedAcks();
4275 
4276   QuicConnection* client_connection = GetClientConnection();
4277   ASSERT_TRUE(client_connection);
4278   const QuicPacketCount packets_sent_before =
4279       client_connection->GetStats().packets_sent;
4280 
4281   client_->SendRequestAndRstTogether("/test_url");
4282 
4283   // Expect exactly one packet is sent from the block above.
4284   ASSERT_EQ(packets_sent_before + 1,
4285             client_connection->GetStats().packets_sent);
4286 
4287   // Wait for the connection to become idle.
4288   client_->WaitForDelayedAcks();
4289 
4290   // The real expectation is the test does not crash or timeout.
4291   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
4292 }
4293 
TEST_P(EndToEndTest,ResetStreamOnTtlExpires)4294 TEST_P(EndToEndTest, ResetStreamOnTtlExpires) {
4295   ASSERT_TRUE(Initialize());
4296   EXPECT_TRUE(client_->client()->WaitForHandshakeConfirmed());
4297   SetPacketLossPercentage(30);
4298 
4299   QuicSpdyClientStream* stream = client_->GetOrCreateStream();
4300   // Set a TTL which expires immediately.
4301   stream->MaybeSetTtl(QuicTime::Delta::FromMicroseconds(1));
4302 
4303   WriteHeadersOnStream(stream);
4304   // 1 MB body.
4305   std::string body(1024 * 1024, 'a');
4306   stream->WriteOrBufferBody(body, true);
4307   client_->WaitForResponse();
4308   EXPECT_THAT(client_->stream_error(), IsStreamError(QUIC_STREAM_TTL_EXPIRED));
4309 }
4310 
TEST_P(EndToEndTest,SendMessages)4311 TEST_P(EndToEndTest, SendMessages) {
4312   if (!version_.SupportsMessageFrames()) {
4313     Initialize();
4314     return;
4315   }
4316   ASSERT_TRUE(Initialize());
4317   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4318   QuicSession* client_session = GetClientSession();
4319   ASSERT_TRUE(client_session);
4320   QuicConnection* client_connection = client_session->connection();
4321   ASSERT_TRUE(client_connection);
4322 
4323   SetPacketLossPercentage(30);
4324   ASSERT_GT(kMaxOutgoingPacketSize,
4325             client_session->GetCurrentLargestMessagePayload());
4326   ASSERT_LT(0, client_session->GetCurrentLargestMessagePayload());
4327 
4328   std::string message_string(kMaxOutgoingPacketSize, 'a');
4329   absl::string_view message_buffer(message_string);
4330   QuicRandom* random =
4331       QuicConnectionPeer::GetHelper(client_connection)->GetRandomGenerator();
4332   QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
4333   {
4334     QuicConnection::ScopedPacketFlusher flusher(client_session->connection());
4335     // Verify the largest message gets successfully sent.
4336     EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1),
4337               client_session->SendMessage(MakeSpan(
4338                   client_connection->helper()->GetStreamSendBufferAllocator(),
4339                   absl::string_view(
4340                       message_buffer.data(),
4341                       client_session->GetCurrentLargestMessagePayload()),
4342                   &storage)));
4343     // Send more messages with size (0, largest_payload] until connection is
4344     // write blocked.
4345     const int kTestMaxNumberOfMessages = 100;
4346     for (size_t i = 2; i <= kTestMaxNumberOfMessages; ++i) {
4347       size_t message_length =
4348           random->RandUint64() %
4349               client_session->GetGuaranteedLargestMessagePayload() +
4350           1;
4351       MessageResult result = client_session->SendMessage(MakeSpan(
4352           client_connection->helper()->GetStreamSendBufferAllocator(),
4353           absl::string_view(message_buffer.data(), message_length), &storage));
4354       if (result.status == MESSAGE_STATUS_BLOCKED) {
4355         // Connection is write blocked.
4356         break;
4357       }
4358       EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, i), result);
4359     }
4360   }
4361 
4362   client_->WaitForDelayedAcks();
4363   EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
4364             client_session
4365                 ->SendMessage(MakeSpan(
4366                     client_connection->helper()->GetStreamSendBufferAllocator(),
4367                     absl::string_view(
4368                         message_buffer.data(),
4369                         client_session->GetCurrentLargestMessagePayload() + 1),
4370                     &storage))
4371                 .status);
4372   EXPECT_THAT(client_->connection_error(), IsQuicNoError());
4373 }
4374 
4375 class EndToEndPacketReorderingTest : public EndToEndTest {
4376  public:
CreateClientWithWriter()4377   void CreateClientWithWriter() override {
4378     QUIC_LOG(ERROR) << "create client with reorder_writer_";
4379     reorder_writer_ = new PacketReorderingWriter();
4380     client_.reset(EndToEndTest::CreateQuicClient(reorder_writer_));
4381   }
4382 
SetUp()4383   void SetUp() override {
4384     // Don't initialize client writer in base class.
4385     server_writer_ = new PacketDroppingTestWriter();
4386   }
4387 
4388  protected:
4389   PacketReorderingWriter* reorder_writer_;
4390 };
4391 
4392 INSTANTIATE_TEST_SUITE_P(EndToEndPacketReorderingTests,
4393                          EndToEndPacketReorderingTest,
4394                          ::testing::ValuesIn(GetTestParams()),
4395                          ::testing::PrintToStringParamName());
4396 
TEST_P(EndToEndPacketReorderingTest,ReorderedConnectivityProbing)4397 TEST_P(EndToEndPacketReorderingTest, ReorderedConnectivityProbing) {
4398   ASSERT_TRUE(Initialize());
4399   if (version_.HasIetfQuicFrames()) {
4400     // TODO(b/143909619): Reenable this test when supporting IETF connection
4401     // migration.
4402     return;
4403   }
4404 
4405   // Finish one request to make sure handshake established.
4406   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
4407 
4408   // Wait for the connection to become idle, to make sure the packet gets
4409   // delayed is the connectivity probing packet.
4410   client_->WaitForDelayedAcks();
4411 
4412   QuicSocketAddress old_addr =
4413       client_->client()->network_helper()->GetLatestClientAddress();
4414 
4415   // Migrate socket to the new IP address.
4416   QuicIpAddress new_host = TestLoopback(2);
4417   EXPECT_NE(old_addr.host(), new_host);
4418   ASSERT_TRUE(client_->client()->MigrateSocket(new_host));
4419 
4420   // Write a connectivity probing after the next /foo request.
4421   reorder_writer_->SetDelay(1);
4422   client_->SendConnectivityProbing();
4423 
4424   ASSERT_TRUE(client_->MigrateSocketWithSpecifiedPort(old_addr.host(),
4425                                                       old_addr.port()));
4426 
4427   // The (delayed) connectivity probing will be sent after this request.
4428   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
4429 
4430   // Send yet another request after the connectivity probing, when this request
4431   // returns, the probing is guaranteed to have been received by the server, and
4432   // the server's response to probing is guaranteed to have been received by the
4433   // client.
4434   EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo"));
4435 
4436   server_thread_->Pause();
4437   QuicConnection* server_connection = GetServerConnection();
4438   if (server_connection != nullptr) {
4439     EXPECT_EQ(1u,
4440               server_connection->GetStats().num_connectivity_probing_received);
4441   } else {
4442     ADD_FAILURE() << "Missing server connection";
4443   }
4444   server_thread_->Resume();
4445 
4446   // Server definitely responded to the connectivity probing. Sometime it also
4447   // sends a padded ping that is not a connectivity probing, which is recognized
4448   // as connectivity probing because client's self address is ANY.
4449   QuicConnection* client_connection = GetClientConnection();
4450   ASSERT_TRUE(client_connection);
4451   EXPECT_LE(1u,
4452             client_connection->GetStats().num_connectivity_probing_received);
4453 }
4454 
TEST_P(EndToEndPacketReorderingTest,Buffer0RttRequest)4455 TEST_P(EndToEndPacketReorderingTest, Buffer0RttRequest) {
4456   ASSERT_TRUE(Initialize());
4457   // Finish one request to make sure handshake established.
4458   client_->SendSynchronousRequest("/foo");
4459   // Disconnect for next 0-rtt request.
4460   client_->Disconnect();
4461 
4462   // Client get valid STK now. Do a 0-rtt request.
4463   // Buffer a CHLO till another packets sent out.
4464   reorder_writer_->SetDelay(1);
4465   // Only send out a CHLO.
4466   client_->client()->Initialize();
4467   client_->client()->StartConnect();
4468   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4469   ASSERT_TRUE(client_->client()->connected());
4470 
4471   // Send a request before handshake finishes.
4472   SpdyHeaderBlock headers;
4473   headers[":method"] = "POST";
4474   headers[":path"] = "/bar";
4475   headers[":scheme"] = "https";
4476   headers[":authority"] = server_hostname_;
4477 
4478   client_->SendMessage(headers, "");
4479   client_->WaitForResponse();
4480   EXPECT_EQ(kBarResponseBody, client_->response_body());
4481   QuicConnection* client_connection = GetClientConnection();
4482   ASSERT_TRUE(client_connection);
4483   QuicConnectionStats client_stats = client_connection->GetStats();
4484   // Client sends CHLO in packet 1 and retransmitted in packet 2. Because of
4485   // the delay, server processes packet 2 and later drops packet 1. ACK is
4486   // bundled with SHLO, such that 1 can be detected loss by time threshold.
4487   EXPECT_LE(0u, client_stats.packets_lost);
4488   EXPECT_TRUE(client_->client()->EarlyDataAccepted());
4489 }
4490 
TEST_P(EndToEndTest,SimpleStopSendingRstStreamTest)4491 TEST_P(EndToEndTest, SimpleStopSendingRstStreamTest) {
4492   ASSERT_TRUE(Initialize());
4493 
4494   // Send a request without a fin, to keep the stream open
4495   SpdyHeaderBlock headers;
4496   headers[":method"] = "POST";
4497   headers[":path"] = "/foo";
4498   headers[":scheme"] = "https";
4499   headers[":authority"] = server_hostname_;
4500   client_->SendMessage(headers, "", /*fin=*/false);
4501   // Stream should be open
4502   ASSERT_NE(nullptr, client_->latest_created_stream());
4503   EXPECT_FALSE(client_->latest_created_stream()->write_side_closed());
4504   EXPECT_FALSE(
4505       QuicStreamPeer::read_side_closed(client_->latest_created_stream()));
4506 
4507   // Send a RST_STREAM+STOP_SENDING on the stream
4508   // Code is not important.
4509   client_->latest_created_stream()->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
4510   client_->WaitForResponse();
4511 
4512   // Stream should be gone.
4513   ASSERT_EQ(nullptr, client_->latest_created_stream());
4514 }
4515 
4516 class BadShloPacketWriter : public QuicPacketWriterWrapper {
4517  public:
BadShloPacketWriter(ParsedQuicVersion version)4518   BadShloPacketWriter(ParsedQuicVersion version)
4519       : error_returned_(false), version_(version) {}
~BadShloPacketWriter()4520   ~BadShloPacketWriter() override {}
4521 
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,quic::PerPacketOptions * options)4522   WriteResult WritePacket(const char* buffer,
4523                           size_t buf_len,
4524                           const QuicIpAddress& self_address,
4525                           const QuicSocketAddress& peer_address,
4526                           quic::PerPacketOptions* options) override {
4527     const WriteResult result = QuicPacketWriterWrapper::WritePacket(
4528         buffer, buf_len, self_address, peer_address, options);
4529     const uint8_t type_byte = buffer[0];
4530     if (!error_returned_ && (type_byte & FLAGS_LONG_HEADER) &&
4531         TypeByteIsServerHello(type_byte)) {
4532       QUIC_DVLOG(1) << "Return write error for packet containing ServerHello";
4533       error_returned_ = true;
4534       return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
4535     }
4536     return result;
4537   }
4538 
TypeByteIsServerHello(uint8_t type_byte)4539   bool TypeByteIsServerHello(uint8_t type_byte) {
4540     if (version_.UsesQuicCrypto()) {
4541       // ENCRYPTION_ZERO_RTT packet.
4542       return ((type_byte & 0x30) >> 4) == 1;
4543     }
4544     // ENCRYPTION_HANDSHAKE packet.
4545     return ((type_byte & 0x30) >> 4) == 2;
4546   }
4547 
4548  private:
4549   bool error_returned_;
4550   ParsedQuicVersion version_;
4551 };
4552 
TEST_P(EndToEndTest,ConnectionCloseBeforeHandshakeComplete)4553 TEST_P(EndToEndTest, ConnectionCloseBeforeHandshakeComplete) {
4554   if (!version_.HasIetfInvariantHeader()) {
4555     // Only runs for IETF QUIC header.
4556     Initialize();
4557     return;
4558   }
4559   // This test ensures ZERO_RTT_PROTECTED connection close could close a client
4560   // which has switched to forward secure.
4561   connect_to_server_on_initialize_ = false;
4562   ASSERT_TRUE(Initialize());
4563   server_thread_->Pause();
4564   QuicDispatcher* dispatcher =
4565       QuicServerPeer::GetDispatcher(server_thread_->server());
4566   if (dispatcher == nullptr) {
4567     ADD_FAILURE() << "Missing dispatcher";
4568     server_thread_->Resume();
4569     return;
4570   }
4571   if (!dispatcher->session_map().empty()) {
4572     ADD_FAILURE() << "Dispatcher session map not empty";
4573     server_thread_->Resume();
4574     return;
4575   }
4576   // Note: this writer will only used by the server connection, not the time
4577   // wait list.
4578   QuicDispatcherPeer::UseWriter(
4579       dispatcher,
4580       // This causes the first server sent ZERO_RTT_PROTECTED packet (i.e.,
4581       // SHLO) to be sent, but WRITE_ERROR is returned. Such that a
4582       // ZERO_RTT_PROTECTED connection close would be sent to a client with
4583       // encryption level FORWARD_SECURE.
4584       new BadShloPacketWriter(version_));
4585   server_thread_->Resume();
4586 
4587   client_.reset(CreateQuicClient(client_writer_));
4588   EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4589   // Verify ZERO_RTT_PROTECTED connection close is successfully processed by
4590   // client which switches to FORWARD_SECURE.
4591   EXPECT_THAT(client_->connection_error(), IsError(QUIC_PACKET_WRITE_ERROR));
4592 }
4593 
4594 class BadShloPacketWriter2 : public QuicPacketWriterWrapper {
4595  public:
BadShloPacketWriter2()4596   BadShloPacketWriter2() : error_returned_(false) {}
~BadShloPacketWriter2()4597   ~BadShloPacketWriter2() override {}
4598 
WritePacket(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & peer_address,quic::PerPacketOptions * options)4599   WriteResult WritePacket(const char* buffer,
4600                           size_t buf_len,
4601                           const QuicIpAddress& self_address,
4602                           const QuicSocketAddress& peer_address,
4603                           quic::PerPacketOptions* options) override {
4604     const uint8_t type_byte = buffer[0];
4605     if ((type_byte & FLAGS_LONG_HEADER) &&
4606         (((type_byte & 0x30) >> 4) == 1 || (type_byte & 0x7F) == 0x7C)) {
4607       QUIC_DVLOG(1) << "Dropping ZERO_RTT_PACKET packet";
4608       return WriteResult(WRITE_STATUS_OK, buf_len);
4609     }
4610     if (!error_returned_ && !(type_byte & FLAGS_LONG_HEADER)) {
4611       QUIC_DVLOG(1) << "Return write error for short header packet";
4612       error_returned_ = true;
4613       return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
4614     }
4615     return QuicPacketWriterWrapper::WritePacket(buffer, buf_len, self_address,
4616                                                 peer_address, options);
4617   }
4618 
4619  private:
4620   bool error_returned_;
4621 };
4622 
TEST_P(EndToEndTest,ForwardSecureConnectionClose)4623 TEST_P(EndToEndTest, ForwardSecureConnectionClose) {
4624   // This test ensures ZERO_RTT_PROTECTED connection close is sent to a client
4625   // which has ZERO_RTT_PROTECTED encryption level.
4626   connect_to_server_on_initialize_ = !version_.HasIetfInvariantHeader();
4627   ASSERT_TRUE(Initialize());
4628   if (!version_.HasIetfInvariantHeader()) {
4629     // Only runs for IETF QUIC header.
4630     return;
4631   }
4632   server_thread_->Pause();
4633   QuicDispatcher* dispatcher =
4634       QuicServerPeer::GetDispatcher(server_thread_->server());
4635   if (dispatcher == nullptr) {
4636     ADD_FAILURE() << "Missing dispatcher";
4637     server_thread_->Resume();
4638     return;
4639   }
4640   if (!dispatcher->session_map().empty()) {
4641     ADD_FAILURE() << "Dispatcher session map not empty";
4642     server_thread_->Resume();
4643     return;
4644   }
4645   // Note: this writer will only used by the server connection, not the time
4646   // wait list.
4647   QuicDispatcherPeer::UseWriter(
4648       dispatcher,
4649       // This causes the all server sent ZERO_RTT_PROTECTED packets to be
4650       // dropped, and first short header packet causes write error.
4651       new BadShloPacketWriter2());
4652   server_thread_->Resume();
4653   client_.reset(CreateQuicClient(client_writer_));
4654   EXPECT_EQ("", client_->SendSynchronousRequest("/foo"));
4655   // Verify ZERO_RTT_PROTECTED connection close is successfully processed by
4656   // client.
4657   EXPECT_THAT(client_->connection_error(), IsError(QUIC_PACKET_WRITE_ERROR));
4658 }
4659 
4660 // Test that the stream id manager closes the connection if a stream
4661 // in excess of the allowed maximum.
TEST_P(EndToEndTest,TooBigStreamIdClosesConnection)4662 TEST_P(EndToEndTest, TooBigStreamIdClosesConnection) {
4663   // Has to be before version test, see EndToEndTest::TearDown()
4664   ASSERT_TRUE(Initialize());
4665   if (!version_.HasIetfQuicFrames()) {
4666     // Only runs for IETF QUIC.
4667     return;
4668   }
4669   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4670 
4671   std::string body(kMaxOutgoingPacketSize, 'a');
4672   SpdyHeaderBlock headers;
4673   headers[":method"] = "POST";
4674   headers[":path"] = "/foo";
4675   headers[":scheme"] = "https";
4676   headers[":authority"] = server_hostname_;
4677 
4678   // Force the client to write with a stream ID that exceeds the limit.
4679   QuicSpdySession* client_session = GetClientSession();
4680   ASSERT_TRUE(client_session);
4681   QuicStreamIdManager* stream_id_manager =
4682       QuicSessionPeer::ietf_bidirectional_stream_id_manager(client_session);
4683   ASSERT_TRUE(stream_id_manager);
4684   QuicStreamCount max_number_of_streams =
4685       stream_id_manager->outgoing_max_streams();
4686   QuicSessionPeer::SetNextOutgoingBidirectionalStreamId(
4687       client_session,
4688       GetNthClientInitiatedBidirectionalId(max_number_of_streams + 1));
4689   client_->SendCustomSynchronousRequest(headers, body);
4690   EXPECT_THAT(client_->stream_error(),
4691               IsStreamError(QUIC_STREAM_CONNECTION_ERROR));
4692   EXPECT_THAT(client_session->error(), IsError(QUIC_INVALID_STREAM_ID));
4693   EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE, client_session->close_type());
4694   EXPECT_TRUE(
4695       IS_IETF_STREAM_FRAME(client_session->transport_close_frame_type()));
4696 }
4697 
TEST_P(EndToEndTest,TestMaxPushId)4698 TEST_P(EndToEndTest, TestMaxPushId) {
4699   if (!version_.HasIetfQuicFrames()) {
4700     // MaxPushId is only implemented for IETF QUIC.
4701     Initialize();
4702     return;
4703   }
4704   SetQuicFlag(FLAGS_quic_enable_http3_server_push, true);
4705   ASSERT_TRUE(Initialize());
4706 
4707   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4708   QuicSpdyClientSession* client_session = GetClientSession();
4709   ASSERT_TRUE(client_session);
4710   client_session->SetMaxPushId(kMaxQuicStreamId);
4711 
4712   client_->SendSynchronousRequest("/foo");
4713 
4714   EXPECT_TRUE(client_session->CanCreatePushStreamWithId(kMaxQuicStreamId));
4715 
4716   server_thread_->Pause();
4717   QuicSpdySession* server_session = GetServerSession();
4718   if (server_session != nullptr) {
4719     EXPECT_TRUE(server_session->CanCreatePushStreamWithId(kMaxQuicStreamId));
4720   } else {
4721     ADD_FAILURE() << "Missing server session";
4722   }
4723   server_thread_->Resume();
4724 }
4725 
TEST_P(EndToEndTest,CustomTransportParameters)4726 TEST_P(EndToEndTest, CustomTransportParameters) {
4727   if (!version_.UsesTls()) {
4728     // Custom transport parameters are only supported with TLS.
4729     ASSERT_TRUE(Initialize());
4730     return;
4731   }
4732   constexpr auto kCustomParameter =
4733       static_cast<TransportParameters::TransportParameterId>(0xff34);
4734   client_config_.custom_transport_parameters_to_send()[kCustomParameter] =
4735       "test";
4736   NiceMock<MockQuicConnectionDebugVisitor> visitor;
4737   connection_debug_visitor_ = &visitor;
4738   EXPECT_CALL(visitor, OnTransportParametersSent(_))
4739       .WillOnce(Invoke([kCustomParameter](
4740                            const TransportParameters& transport_parameters) {
4741         ASSERT_NE(transport_parameters.custom_parameters.find(kCustomParameter),
4742                   transport_parameters.custom_parameters.end());
4743         EXPECT_EQ(transport_parameters.custom_parameters.at(kCustomParameter),
4744                   "test");
4745       }));
4746   EXPECT_CALL(visitor, OnTransportParametersReceived(_)).Times(1);
4747   ASSERT_TRUE(Initialize());
4748 
4749   EXPECT_TRUE(client_->client()->WaitForOneRttKeysAvailable());
4750 
4751   server_thread_->Pause();
4752   QuicSpdySession* server_session = GetServerSession();
4753   QuicConfig* server_config = nullptr;
4754   if (server_session != nullptr) {
4755     server_config = server_session->config();
4756     EXPECT_EQ(server_session->user_agent_id().value_or("MissingUserAgent"),
4757               kTestUserAgentId);
4758   } else {
4759     ADD_FAILURE() << "Missing server session";
4760   }
4761   if (server_config != nullptr) {
4762     if (server_config->received_custom_transport_parameters().find(
4763             kCustomParameter) !=
4764         server_config->received_custom_transport_parameters().end()) {
4765       EXPECT_EQ(server_config->received_custom_transport_parameters().at(
4766                     kCustomParameter),
4767                 "test");
4768     } else {
4769       ADD_FAILURE() << "Did not find custom parameter";
4770     }
4771   } else {
4772     ADD_FAILURE() << "Missing server config";
4773   }
4774   server_thread_->Resume();
4775 }
4776 
TEST_P(EndToEndTest,LegacyVersionEncapsulation)4777 TEST_P(EndToEndTest, LegacyVersionEncapsulation) {
4778   if (!version_.HasLongHeaderLengths()) {
4779     // Decapsulating Legacy Version Encapsulation packets from these versions
4780     // is not currently supported in QuicDispatcher.
4781     ASSERT_TRUE(Initialize());
4782     return;
4783   }
4784   client_config_.SetClientConnectionOptions(QuicTagVector{kQLVE});
4785   ASSERT_TRUE(Initialize());
4786   SendSynchronousFooRequestAndCheckResponse();
4787   QuicConnection* client_connection = GetClientConnection();
4788   ASSERT_TRUE(client_connection);
4789   EXPECT_GT(
4790       client_connection->GetStats().sent_legacy_version_encapsulated_packets,
4791       0u);
4792 }
4793 
TEST_P(EndToEndTest,LegacyVersionEncapsulationWithMultiPacketChlo)4794 TEST_P(EndToEndTest, LegacyVersionEncapsulationWithMultiPacketChlo) {
4795   if (!version_.HasLongHeaderLengths()) {
4796     // Decapsulating Legacy Version Encapsulation packets from these versions
4797     // is not currently supported in QuicDispatcher.
4798     ASSERT_TRUE(Initialize());
4799     return;
4800   }
4801   if (!version_.UsesTls()) {
4802     // This test uses custom transport parameters to increase the size of the
4803     // CHLO, and those are only supported with TLS.
4804     ASSERT_TRUE(Initialize());
4805     return;
4806   }
4807   client_config_.SetClientConnectionOptions(QuicTagVector{kQLVE});
4808   constexpr auto kCustomParameter =
4809       static_cast<TransportParameters::TransportParameterId>(0xff34);
4810   client_config_.custom_transport_parameters_to_send()[kCustomParameter] =
4811       std::string(2000, '?');
4812   ASSERT_TRUE(Initialize());
4813   SendSynchronousFooRequestAndCheckResponse();
4814   QuicConnection* client_connection = GetClientConnection();
4815   ASSERT_TRUE(client_connection);
4816   EXPECT_GT(
4817       client_connection->GetStats().sent_legacy_version_encapsulated_packets,
4818       0u);
4819 }
4820 
TEST_P(EndToEndTest,LegacyVersionEncapsulationWithVersionNegotiation)4821 TEST_P(EndToEndTest, LegacyVersionEncapsulationWithVersionNegotiation) {
4822   if (!version_.HasLongHeaderLengths()) {
4823     // Decapsulating Legacy Version Encapsulation packets from these versions
4824     // is not currently supported in QuicDispatcher.
4825     ASSERT_TRUE(Initialize());
4826     return;
4827   }
4828   client_supported_versions_.insert(client_supported_versions_.begin(),
4829                                     QuicVersionReservedForNegotiation());
4830   client_config_.SetClientConnectionOptions(QuicTagVector{kQLVE});
4831   ASSERT_TRUE(Initialize());
4832   SendSynchronousFooRequestAndCheckResponse();
4833   QuicConnection* client_connection = GetClientConnection();
4834   ASSERT_TRUE(client_connection);
4835   EXPECT_GT(
4836       client_connection->GetStats().sent_legacy_version_encapsulated_packets,
4837       0u);
4838 }
4839 
TEST_P(EndToEndTest,LegacyVersionEncapsulationWithLoss)4840 TEST_P(EndToEndTest, LegacyVersionEncapsulationWithLoss) {
4841   if (!version_.HasLongHeaderLengths()) {
4842     // Decapsulating Legacy Version Encapsulation packets from these versions
4843     // is not currently supported in QuicDispatcher.
4844     ASSERT_TRUE(Initialize());
4845     return;
4846   }
4847   SetPacketLossPercentage(30);
4848   client_config_.SetClientConnectionOptions(QuicTagVector{kQLVE});
4849   // Disable blackhole detection as this test is testing loss recovery.
4850   client_extra_copts_.push_back(kNBHD);
4851   ASSERT_TRUE(Initialize());
4852   SendSynchronousFooRequestAndCheckResponse();
4853   QuicConnection* client_connection = GetClientConnection();
4854   ASSERT_TRUE(client_connection);
4855   EXPECT_GT(
4856       client_connection->GetStats().sent_legacy_version_encapsulated_packets,
4857       0u);
4858 }
4859 
TEST_P(EndToEndTest,KeyUpdateInitiatedByClient)4860 TEST_P(EndToEndTest, KeyUpdateInitiatedByClient) {
4861   SetQuicReloadableFlag(quic_key_update_supported, true);
4862 
4863   if (!version_.UsesTls()) {
4864     // Key Update is only supported in TLS handshake.
4865     ASSERT_TRUE(Initialize());
4866     return;
4867   }
4868 
4869   ASSERT_TRUE(Initialize());
4870 
4871   SendSynchronousFooRequestAndCheckResponse();
4872   QuicConnection* client_connection = GetClientConnection();
4873   ASSERT_TRUE(client_connection);
4874   EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
4875 
4876   EXPECT_TRUE(
4877       client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
4878   SendSynchronousFooRequestAndCheckResponse();
4879   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
4880 
4881   SendSynchronousFooRequestAndCheckResponse();
4882   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
4883 
4884   EXPECT_TRUE(
4885       client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
4886   SendSynchronousFooRequestAndCheckResponse();
4887   EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
4888 
4889   server_thread_->Pause();
4890   QuicConnection* server_connection = GetServerConnection();
4891   if (server_connection) {
4892     QuicConnectionStats server_stats = server_connection->GetStats();
4893     EXPECT_EQ(2u, server_stats.key_update_count);
4894   } else {
4895     ADD_FAILURE() << "Missing server connection";
4896   }
4897   server_thread_->Resume();
4898 }
4899 
TEST_P(EndToEndTest,KeyUpdateInitiatedByServer)4900 TEST_P(EndToEndTest, KeyUpdateInitiatedByServer) {
4901   SetQuicReloadableFlag(quic_key_update_supported, true);
4902 
4903   if (!version_.UsesTls()) {
4904     // Key Update is only supported in TLS handshake.
4905     ASSERT_TRUE(Initialize());
4906     return;
4907   }
4908 
4909   ASSERT_TRUE(Initialize());
4910 
4911   SendSynchronousFooRequestAndCheckResponse();
4912   QuicConnection* client_connection = GetClientConnection();
4913   ASSERT_TRUE(client_connection);
4914   EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
4915 
4916   // Use WaitUntil to ensure the server had executed the key update predicate
4917   // before sending the Foo request, otherwise the test can be flaky if it
4918   // receives the Foo request before executing the key update.
4919   server_thread_->WaitUntil(
4920       [this]() {
4921         QuicConnection* server_connection = GetServerConnection();
4922         if (server_connection != nullptr) {
4923           if (!server_connection->IsKeyUpdateAllowed()) {
4924             // Server may not have received ack from client yet for the current
4925             // key phase, wait a bit and try again.
4926             return false;
4927           }
4928           EXPECT_TRUE(server_connection->InitiateKeyUpdate(
4929               KeyUpdateReason::kLocalForTests));
4930         } else {
4931           ADD_FAILURE() << "Missing server connection";
4932         }
4933         return true;
4934       },
4935       QuicTime::Delta::FromSeconds(5));
4936 
4937   SendSynchronousFooRequestAndCheckResponse();
4938   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
4939 
4940   SendSynchronousFooRequestAndCheckResponse();
4941   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
4942 
4943   server_thread_->WaitUntil(
4944       [this]() {
4945         QuicConnection* server_connection = GetServerConnection();
4946         if (server_connection != nullptr) {
4947           if (!server_connection->IsKeyUpdateAllowed()) {
4948             return false;
4949           }
4950           EXPECT_TRUE(server_connection->InitiateKeyUpdate(
4951               KeyUpdateReason::kLocalForTests));
4952         } else {
4953           ADD_FAILURE() << "Missing server connection";
4954         }
4955         return true;
4956       },
4957       QuicTime::Delta::FromSeconds(5));
4958 
4959   SendSynchronousFooRequestAndCheckResponse();
4960   EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
4961 
4962   server_thread_->Pause();
4963   QuicConnection* server_connection = GetServerConnection();
4964   if (server_connection) {
4965     QuicConnectionStats server_stats = server_connection->GetStats();
4966     EXPECT_EQ(2u, server_stats.key_update_count);
4967   } else {
4968     ADD_FAILURE() << "Missing server connection";
4969   }
4970   server_thread_->Resume();
4971 }
4972 
TEST_P(EndToEndTest,KeyUpdateInitiatedByBoth)4973 TEST_P(EndToEndTest, KeyUpdateInitiatedByBoth) {
4974   SetQuicReloadableFlag(quic_key_update_supported, true);
4975 
4976   if (!version_.UsesTls()) {
4977     // Key Update is only supported in TLS handshake.
4978     ASSERT_TRUE(Initialize());
4979     return;
4980   }
4981 
4982   ASSERT_TRUE(Initialize());
4983 
4984   SendSynchronousFooRequestAndCheckResponse();
4985 
4986   // Use WaitUntil to ensure the server had executed the key update predicate
4987   // before the client sends the Foo request, otherwise the Foo request from
4988   // the client could trigger the server key update before the server can
4989   // initiate the key update locally. That would mean the test is no longer
4990   // hitting the intended test state of both sides locally initiating a key
4991   // update before receiving a packet in the new key phase from the other side.
4992   // Additionally the test would fail since InitiateKeyUpdate() would not allow
4993   // to do another key update yet and return false.
4994   server_thread_->WaitUntil(
4995       [this]() {
4996         QuicConnection* server_connection = GetServerConnection();
4997         if (server_connection != nullptr) {
4998           if (!server_connection->IsKeyUpdateAllowed()) {
4999             // Server may not have received ack from client yet for the current
5000             // key phase, wait a bit and try again.
5001             return false;
5002           }
5003           EXPECT_TRUE(server_connection->InitiateKeyUpdate(
5004               KeyUpdateReason::kLocalForTests));
5005         } else {
5006           ADD_FAILURE() << "Missing server connection";
5007         }
5008         return true;
5009       },
5010       QuicTime::Delta::FromSeconds(5));
5011   QuicConnection* client_connection = GetClientConnection();
5012   ASSERT_TRUE(client_connection);
5013   EXPECT_TRUE(
5014       client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
5015 
5016   SendSynchronousFooRequestAndCheckResponse();
5017   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
5018 
5019   SendSynchronousFooRequestAndCheckResponse();
5020   EXPECT_EQ(1u, client_connection->GetStats().key_update_count);
5021 
5022   server_thread_->WaitUntil(
5023       [this]() {
5024         QuicConnection* server_connection = GetServerConnection();
5025         if (server_connection != nullptr) {
5026           if (!server_connection->IsKeyUpdateAllowed()) {
5027             return false;
5028           }
5029           EXPECT_TRUE(server_connection->InitiateKeyUpdate(
5030               KeyUpdateReason::kLocalForTests));
5031         } else {
5032           ADD_FAILURE() << "Missing server connection";
5033         }
5034         return true;
5035       },
5036       QuicTime::Delta::FromSeconds(5));
5037   EXPECT_TRUE(
5038       client_connection->InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
5039 
5040   SendSynchronousFooRequestAndCheckResponse();
5041   EXPECT_EQ(2u, client_connection->GetStats().key_update_count);
5042 
5043   server_thread_->Pause();
5044   QuicConnection* server_connection = GetServerConnection();
5045   if (server_connection) {
5046     QuicConnectionStats server_stats = server_connection->GetStats();
5047     EXPECT_EQ(2u, server_stats.key_update_count);
5048   } else {
5049     ADD_FAILURE() << "Missing server connection";
5050   }
5051   server_thread_->Resume();
5052 }
5053 
TEST_P(EndToEndTest,KeyUpdateInitiatedByConfidentialityLimit)5054 TEST_P(EndToEndTest, KeyUpdateInitiatedByConfidentialityLimit) {
5055   SetQuicReloadableFlag(quic_enable_aead_limits, true);
5056   SetQuicReloadableFlag(quic_key_update_supported, true);
5057   SetQuicFlag(FLAGS_quic_key_update_confidentiality_limit, 4U);
5058 
5059   if (!version_.UsesTls()) {
5060     // Key Update is only supported in TLS handshake.
5061     ASSERT_TRUE(Initialize());
5062     return;
5063   }
5064 
5065   ASSERT_TRUE(Initialize());
5066 
5067   QuicConnection* client_connection = GetClientConnection();
5068   ASSERT_TRUE(client_connection);
5069   EXPECT_EQ(0u, client_connection->GetStats().key_update_count);
5070 
5071   server_thread_->WaitUntil(
5072       [this]() {
5073         QuicConnection* server_connection = GetServerConnection();
5074         if (server_connection != nullptr) {
5075           EXPECT_EQ(0u, server_connection->GetStats().key_update_count);
5076         } else {
5077           ADD_FAILURE() << "Missing server connection";
5078         }
5079         return true;
5080       },
5081       QuicTime::Delta::FromSeconds(5));
5082 
5083   SendSynchronousFooRequestAndCheckResponse();
5084   SendSynchronousFooRequestAndCheckResponse();
5085   SendSynchronousFooRequestAndCheckResponse();
5086   // Don't know exactly how many packets will be sent in each request/response,
5087   // so just test that at least one key update occurred.
5088   EXPECT_LE(1u, client_connection->GetStats().key_update_count);
5089 
5090   server_thread_->Pause();
5091   QuicConnection* server_connection = GetServerConnection();
5092   if (server_connection) {
5093     QuicConnectionStats server_stats = server_connection->GetStats();
5094     EXPECT_LE(1u, server_stats.key_update_count);
5095   } else {
5096     ADD_FAILURE() << "Missing server connection";
5097   }
5098   server_thread_->Resume();
5099 }
5100 
TEST_P(EndToEndTest,TlsResumptionEnabledOnTheFly)5101 TEST_P(EndToEndTest, TlsResumptionEnabledOnTheFly) {
5102   SetQuicFlag(FLAGS_quic_disable_server_tls_resumption, true);
5103   ASSERT_TRUE(Initialize());
5104 
5105   if (!version_.UsesTls()) {
5106     // This test is TLS specific.
5107     return;
5108   }
5109 
5110   // Send the first request. Client should not have a resumption ticket.
5111   SendSynchronousFooRequestAndCheckResponse();
5112   QuicSpdyClientSession* client_session = GetClientSession();
5113   ASSERT_TRUE(client_session);
5114   EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
5115             ssl_early_data_no_session_offered);
5116   EXPECT_FALSE(client_session->EarlyDataAccepted());
5117   client_->Disconnect();
5118 
5119   SetQuicFlag(FLAGS_quic_disable_server_tls_resumption, false);
5120 
5121   // Send the second request. Client should still have no resumption ticket, but
5122   // it will receive one which can be used by the next request.
5123   client_->Connect();
5124   SendSynchronousFooRequestAndCheckResponse();
5125 
5126   client_session = GetClientSession();
5127   ASSERT_TRUE(client_session);
5128   EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
5129             ssl_early_data_no_session_offered);
5130   EXPECT_FALSE(client_session->EarlyDataAccepted());
5131   client_->Disconnect();
5132 
5133   // Send the third request in 0RTT.
5134   client_->Connect();
5135   SendSynchronousFooRequestAndCheckResponse();
5136 
5137   client_session = GetClientSession();
5138   ASSERT_TRUE(client_session);
5139   EXPECT_TRUE(client_session->EarlyDataAccepted());
5140   client_->Disconnect();
5141 }
5142 
TEST_P(EndToEndTest,TlsResumptionDisabledOnTheFly)5143 TEST_P(EndToEndTest, TlsResumptionDisabledOnTheFly) {
5144   SetQuicFlag(FLAGS_quic_disable_server_tls_resumption, false);
5145   ASSERT_TRUE(Initialize());
5146 
5147   if (!version_.UsesTls()) {
5148     // This test is TLS specific.
5149     return;
5150   }
5151 
5152   // Send the first request and then disconnect.
5153   SendSynchronousFooRequestAndCheckResponse();
5154   QuicSpdyClientSession* client_session = GetClientSession();
5155   ASSERT_TRUE(client_session);
5156   EXPECT_FALSE(client_session->EarlyDataAccepted());
5157   client_->Disconnect();
5158 
5159   // Send the second request in 0RTT.
5160   client_->Connect();
5161   SendSynchronousFooRequestAndCheckResponse();
5162 
5163   client_session = GetClientSession();
5164   ASSERT_TRUE(client_session);
5165   EXPECT_TRUE(client_session->EarlyDataAccepted());
5166   client_->Disconnect();
5167 
5168   SetQuicFlag(FLAGS_quic_disable_server_tls_resumption, true);
5169 
5170   // Send the third request. The client should try resumption but server should
5171   // decline it.
5172   client_->Connect();
5173   SendSynchronousFooRequestAndCheckResponse();
5174 
5175   client_session = GetClientSession();
5176   ASSERT_TRUE(client_session);
5177   EXPECT_FALSE(client_session->EarlyDataAccepted());
5178   EXPECT_EQ(client_session->GetCryptoStream()->EarlyDataReason(),
5179             ssl_early_data_session_not_resumed);
5180   client_->Disconnect();
5181 
5182   // Keep sending until the client runs out of resumption tickets.
5183   for (int i = 0; i < 10; ++i) {
5184     client_->Connect();
5185     SendSynchronousFooRequestAndCheckResponse();
5186 
5187     client_session = GetClientSession();
5188     ASSERT_TRUE(client_session);
5189     EXPECT_FALSE(client_session->EarlyDataAccepted());
5190     const auto early_data_reason =
5191         client_session->GetCryptoStream()->EarlyDataReason();
5192     client_->Disconnect();
5193 
5194     if (early_data_reason != ssl_early_data_session_not_resumed) {
5195       EXPECT_EQ(early_data_reason, ssl_early_data_no_session_offered);
5196       return;
5197     }
5198   }
5199 
5200   ADD_FAILURE() << "Client should not have 10 resumption tickets.";
5201 }
5202 
5203 }  // namespace
5204 }  // namespace test
5205 }  // namespace quic
5206