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