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