1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "quiche/quic/core/quic_session.h"
6
7 #include <cstdint>
8 #include <optional>
9 #include <set>
10 #include <string>
11 #include <utility>
12
13 #include "absl/base/macros.h"
14 #include "absl/memory/memory.h"
15 #include "absl/strings/str_cat.h"
16 #include "absl/strings/string_view.h"
17 #include "quiche/quic/core/crypto/crypto_protocol.h"
18 #include "quiche/quic/core/crypto/null_decrypter.h"
19 #include "quiche/quic/core/crypto/null_encrypter.h"
20 #include "quiche/quic/core/crypto/transport_parameters.h"
21 #include "quiche/quic/core/frames/quic_max_streams_frame.h"
22 #include "quiche/quic/core/quic_crypto_stream.h"
23 #include "quiche/quic/core/quic_data_writer.h"
24 #include "quiche/quic/core/quic_packets.h"
25 #include "quiche/quic/core/quic_stream.h"
26 #include "quiche/quic/core/quic_types.h"
27 #include "quiche/quic/core/quic_utils.h"
28 #include "quiche/quic/core/quic_versions.h"
29 #include "quiche/quic/platform/api/quic_expect_bug.h"
30 #include "quiche/quic/platform/api/quic_flags.h"
31 #include "quiche/quic/platform/api/quic_test.h"
32 #include "quiche/quic/test_tools/mock_quic_session_visitor.h"
33 #include "quiche/quic/test_tools/quic_config_peer.h"
34 #include "quiche/quic/test_tools/quic_connection_peer.h"
35 #include "quiche/quic/test_tools/quic_flow_controller_peer.h"
36 #include "quiche/quic/test_tools/quic_session_peer.h"
37 #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h"
38 #include "quiche/quic/test_tools/quic_stream_peer.h"
39 #include "quiche/quic/test_tools/quic_stream_send_buffer_peer.h"
40 #include "quiche/quic/test_tools/quic_test_utils.h"
41 #include "quiche/common/platform/api/quiche_logging.h"
42 #include "quiche/common/quiche_mem_slice_storage.h"
43
44 using spdy::kV3HighestPriority;
45 using spdy::SpdyPriority;
46 using ::testing::_;
47 using ::testing::AnyNumber;
48 using ::testing::AtLeast;
49 using ::testing::InSequence;
50 using ::testing::Invoke;
51 using ::testing::NiceMock;
52 using ::testing::Return;
53 using ::testing::StrictMock;
54 using ::testing::WithArg;
55
56 namespace quic {
57 namespace test {
58 namespace {
59
60 class TestCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker {
61 public:
TestCryptoStream(QuicSession * session)62 explicit TestCryptoStream(QuicSession* session)
63 : QuicCryptoStream(session),
64 QuicCryptoHandshaker(this, session),
65 encryption_established_(false),
66 one_rtt_keys_available_(false),
67 params_(new QuicCryptoNegotiatedParameters) {
68 // Simulate a negotiated cipher_suite with a fake value.
69 params_->cipher_suite = 1;
70 }
71
EstablishZeroRttEncryption()72 void EstablishZeroRttEncryption() {
73 encryption_established_ = true;
74 session()->connection()->SetEncrypter(
75 ENCRYPTION_ZERO_RTT,
76 std::make_unique<NullEncrypter>(session()->perspective()));
77 }
78
OnHandshakeMessage(const CryptoHandshakeMessage &)79 void OnHandshakeMessage(const CryptoHandshakeMessage& /*message*/) override {
80 encryption_established_ = true;
81 one_rtt_keys_available_ = true;
82 QuicErrorCode error;
83 std::string error_details;
84 session()->config()->SetInitialStreamFlowControlWindowToSend(
85 kInitialStreamFlowControlWindowForTest);
86 session()->config()->SetInitialSessionFlowControlWindowToSend(
87 kInitialSessionFlowControlWindowForTest);
88 if (session()->version().UsesTls()) {
89 if (session()->perspective() == Perspective::IS_CLIENT) {
90 session()->config()->SetOriginalConnectionIdToSend(
91 session()->connection()->connection_id());
92 session()->config()->SetInitialSourceConnectionIdToSend(
93 session()->connection()->connection_id());
94 } else {
95 session()->config()->SetInitialSourceConnectionIdToSend(
96 session()->connection()->client_connection_id());
97 }
98 TransportParameters transport_parameters;
99 EXPECT_TRUE(
100 session()->config()->FillTransportParameters(&transport_parameters));
101 error = session()->config()->ProcessTransportParameters(
102 transport_parameters, /* is_resumption = */ false, &error_details);
103 } else {
104 CryptoHandshakeMessage msg;
105 session()->config()->ToHandshakeMessage(&msg, transport_version());
106 error =
107 session()->config()->ProcessPeerHello(msg, CLIENT, &error_details);
108 }
109 EXPECT_THAT(error, IsQuicNoError());
110 session()->OnNewEncryptionKeyAvailable(
111 ENCRYPTION_FORWARD_SECURE,
112 std::make_unique<NullEncrypter>(session()->perspective()));
113 session()->OnConfigNegotiated();
114 if (session()->connection()->version().handshake_protocol ==
115 PROTOCOL_TLS1_3) {
116 session()->OnTlsHandshakeComplete();
117 } else {
118 session()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
119 }
120 session()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL);
121 }
122
123 // QuicCryptoStream implementation
EarlyDataReason() const124 ssl_early_data_reason_t EarlyDataReason() const override {
125 return ssl_early_data_unknown;
126 }
encryption_established() const127 bool encryption_established() const override {
128 return encryption_established_;
129 }
one_rtt_keys_available() const130 bool one_rtt_keys_available() const override {
131 return one_rtt_keys_available_;
132 }
crypto_negotiated_params() const133 const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
134 const override {
135 return *params_;
136 }
crypto_message_parser()137 CryptoMessageParser* crypto_message_parser() override {
138 return QuicCryptoHandshaker::crypto_message_parser();
139 }
OnPacketDecrypted(EncryptionLevel)140 void OnPacketDecrypted(EncryptionLevel /*level*/) override {}
OnOneRttPacketAcknowledged()141 void OnOneRttPacketAcknowledged() override {}
OnHandshakePacketSent()142 void OnHandshakePacketSent() override {}
OnHandshakeDoneReceived()143 void OnHandshakeDoneReceived() override {}
OnNewTokenReceived(absl::string_view)144 void OnNewTokenReceived(absl::string_view /*token*/) override {}
GetAddressToken(const CachedNetworkParameters *) const145 std::string GetAddressToken(
146 const CachedNetworkParameters* /*cached_network_parameters*/)
147 const override {
148 return "";
149 }
ValidateAddressToken(absl::string_view) const150 bool ValidateAddressToken(absl::string_view /*token*/) const override {
151 return true;
152 }
PreviousCachedNetworkParams() const153 const CachedNetworkParameters* PreviousCachedNetworkParams() const override {
154 return nullptr;
155 }
SetPreviousCachedNetworkParams(CachedNetworkParameters)156 void SetPreviousCachedNetworkParams(
157 CachedNetworkParameters /*cached_network_params*/) override {}
GetHandshakeState() const158 HandshakeState GetHandshakeState() const override {
159 return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START;
160 }
SetServerApplicationStateForResumption(std::unique_ptr<ApplicationState>)161 void SetServerApplicationStateForResumption(
162 std::unique_ptr<ApplicationState> /*application_state*/) override {}
163 MOCK_METHOD(std::unique_ptr<QuicDecrypter>,
164 AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override));
165 MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (),
166 (override));
167
168 MOCK_METHOD(void, OnCanWrite, (), (override));
HasPendingCryptoRetransmission() const169 bool HasPendingCryptoRetransmission() const override { return false; }
170
171 MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override));
172
OnConnectionClosed(QuicErrorCode,ConnectionCloseSource)173 void OnConnectionClosed(QuicErrorCode /*error*/,
174 ConnectionCloseSource /*source*/) override {}
175
ExportKeyingMaterial(absl::string_view,absl::string_view,size_t,std::string *)176 bool ExportKeyingMaterial(absl::string_view /*label*/,
177 absl::string_view /*context*/,
178 size_t /*result_len*/,
179 std::string* /*result*/) override {
180 return false;
181 }
182
GetSsl() const183 SSL* GetSsl() const override { return nullptr; }
184
IsCryptoFrameExpectedForEncryptionLevel(EncryptionLevel level) const185 bool IsCryptoFrameExpectedForEncryptionLevel(
186 EncryptionLevel level) const override {
187 return level != ENCRYPTION_ZERO_RTT;
188 }
189
GetEncryptionLevelToSendCryptoDataOfSpace(PacketNumberSpace space) const190 EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
191 PacketNumberSpace space) const override {
192 switch (space) {
193 case INITIAL_DATA:
194 return ENCRYPTION_INITIAL;
195 case HANDSHAKE_DATA:
196 return ENCRYPTION_HANDSHAKE;
197 case APPLICATION_DATA:
198 return ENCRYPTION_FORWARD_SECURE;
199 default:
200 QUICHE_DCHECK(false);
201 return NUM_ENCRYPTION_LEVELS;
202 }
203 }
204
205 private:
206 using QuicCryptoStream::session;
207
208 bool encryption_established_;
209 bool one_rtt_keys_available_;
210 quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
211 };
212
213 class TestStream : public QuicStream {
214 public:
TestStream(QuicStreamId id,QuicSession * session,StreamType type)215 TestStream(QuicStreamId id, QuicSession* session, StreamType type)
216 : TestStream(id, session, /*is_static=*/false, type) {}
217
TestStream(QuicStreamId id,QuicSession * session,bool is_static,StreamType type)218 TestStream(QuicStreamId id, QuicSession* session, bool is_static,
219 StreamType type)
220 : QuicStream(id, session, is_static, type) {}
221
TestStream(PendingStream * pending,QuicSession * session)222 TestStream(PendingStream* pending, QuicSession* session)
223 : QuicStream(pending, session, /*is_static=*/false) {}
224
225 using QuicStream::CloseWriteSide;
226 using QuicStream::WriteMemSlices;
227
OnDataAvailable()228 void OnDataAvailable() override {}
229
230 MOCK_METHOD(void, OnCanWrite, (), (override));
231 MOCK_METHOD(bool, RetransmitStreamData,
232 (QuicStreamOffset, QuicByteCount, bool, TransmissionType),
233 (override));
234
235 MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override));
236 };
237
238 class TestSession : public QuicSession {
239 public:
TestSession(QuicConnection * connection,MockQuicSessionVisitor * session_visitor)240 explicit TestSession(QuicConnection* connection,
241 MockQuicSessionVisitor* session_visitor)
242 : QuicSession(connection, session_visitor, DefaultQuicConfig(),
243 CurrentSupportedVersions(),
244 /*num_expected_unidirectional_static_streams = */ 0),
245 crypto_stream_(this),
246 writev_consumes_all_data_(false),
247 uses_pending_streams_(false),
248 num_incoming_streams_created_(0) {
249 set_max_streams_accepted_per_loop(5);
250 Initialize();
251 this->connection()->SetEncrypter(
252 ENCRYPTION_FORWARD_SECURE,
253 std::make_unique<NullEncrypter>(connection->perspective()));
254 if (this->connection()->version().SupportsAntiAmplificationLimit()) {
255 QuicConnectionPeer::SetAddressValidated(this->connection());
256 }
257 }
258
~TestSession()259 ~TestSession() override { DeleteConnection(); }
260
GetMutableCryptoStream()261 TestCryptoStream* GetMutableCryptoStream() override {
262 return &crypto_stream_;
263 }
264
GetCryptoStream() const265 const TestCryptoStream* GetCryptoStream() const override {
266 return &crypto_stream_;
267 }
268
CreateOutgoingBidirectionalStream()269 TestStream* CreateOutgoingBidirectionalStream() {
270 QuicStreamId id = GetNextOutgoingBidirectionalStreamId();
271 if (id ==
272 QuicUtils::GetInvalidStreamId(connection()->transport_version())) {
273 return nullptr;
274 }
275 TestStream* stream = new TestStream(id, this, BIDIRECTIONAL);
276 ActivateStream(absl::WrapUnique(stream));
277 return stream;
278 }
279
CreateOutgoingUnidirectionalStream()280 TestStream* CreateOutgoingUnidirectionalStream() {
281 TestStream* stream = new TestStream(GetNextOutgoingUnidirectionalStreamId(),
282 this, WRITE_UNIDIRECTIONAL);
283 ActivateStream(absl::WrapUnique(stream));
284 return stream;
285 }
286
CreateIncomingStream(QuicStreamId id)287 TestStream* CreateIncomingStream(QuicStreamId id) override {
288 // Enforce the limit on the number of open streams.
289 if (!VersionHasIetfQuicFrames(connection()->transport_version()) &&
290 stream_id_manager().num_open_incoming_streams() + 1 >
291 max_open_incoming_bidirectional_streams()) {
292 // No need to do this test for version 99; it's done by
293 // QuicSession::GetOrCreateStream.
294 connection()->CloseConnection(
295 QUIC_TOO_MANY_OPEN_STREAMS, "Too many streams!",
296 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
297 return nullptr;
298 }
299
300 TestStream* stream = new TestStream(
301 id, this,
302 DetermineStreamType(id, connection()->version(), perspective(),
303 /*is_incoming=*/true, BIDIRECTIONAL));
304 ActivateStream(absl::WrapUnique(stream));
305 ++num_incoming_streams_created_;
306 return stream;
307 }
308
CreateIncomingStream(PendingStream * pending)309 TestStream* CreateIncomingStream(PendingStream* pending) override {
310 TestStream* stream = new TestStream(pending, this);
311 ActivateStream(absl::WrapUnique(stream));
312 ++num_incoming_streams_created_;
313 return stream;
314 }
315
316 // QuicSession doesn't do anything in these methods. So they are overridden
317 // here to test that the session handles pending streams correctly in terms of
318 // receiving stream frames.
ProcessBidirectionalPendingStream(PendingStream * pending)319 QuicStream* ProcessBidirectionalPendingStream(
320 PendingStream* pending) override {
321 return CreateIncomingStream(pending);
322 }
ProcessReadUnidirectionalPendingStream(PendingStream * pending)323 QuicStream* ProcessReadUnidirectionalPendingStream(
324 PendingStream* pending) override {
325 struct iovec iov;
326 if (pending->sequencer()->GetReadableRegion(&iov)) {
327 // Create TestStream once the first byte is received.
328 return CreateIncomingStream(pending);
329 }
330 return nullptr;
331 }
332
IsClosedStream(QuicStreamId id)333 bool IsClosedStream(QuicStreamId id) {
334 return QuicSession::IsClosedStream(id);
335 }
336
GetOrCreateStream(QuicStreamId stream_id)337 QuicStream* GetOrCreateStream(QuicStreamId stream_id) {
338 return QuicSession::GetOrCreateStream(stream_id);
339 }
340
ShouldKeepConnectionAlive() const341 bool ShouldKeepConnectionAlive() const override {
342 return GetNumActiveStreams() > 0;
343 }
344
WritevData(QuicStreamId id,size_t write_length,QuicStreamOffset offset,StreamSendingState state,TransmissionType type,EncryptionLevel level)345 QuicConsumedData WritevData(QuicStreamId id, size_t write_length,
346 QuicStreamOffset offset, StreamSendingState state,
347 TransmissionType type,
348 EncryptionLevel level) override {
349 bool fin = state != NO_FIN;
350 QuicConsumedData consumed(write_length, fin);
351 if (!writev_consumes_all_data_) {
352 consumed =
353 QuicSession::WritevData(id, write_length, offset, state, type, level);
354 }
355 QuicSessionPeer::GetWriteBlockedStreams(this)->UpdateBytesForStream(
356 id, consumed.bytes_consumed);
357 return consumed;
358 }
359
360 MOCK_METHOD(void, OnCanCreateNewOutgoingStream, (bool unidirectional),
361 (override));
362
set_writev_consumes_all_data(bool val)363 void set_writev_consumes_all_data(bool val) {
364 writev_consumes_all_data_ = val;
365 }
366
SendStreamData(QuicStream * stream)367 QuicConsumedData SendStreamData(QuicStream* stream) {
368 if (!QuicUtils::IsCryptoStreamId(connection()->transport_version(),
369 stream->id()) &&
370 this->connection()->encryption_level() != ENCRYPTION_FORWARD_SECURE) {
371 this->connection()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
372 }
373 QuicStreamPeer::SendBuffer(stream).SaveStreamData("not empty");
374 QuicConsumedData consumed =
375 WritevData(stream->id(), 9, 0, FIN, NOT_RETRANSMISSION,
376 GetEncryptionLevelToSendApplicationData());
377 QuicStreamPeer::SendBuffer(stream).OnStreamDataConsumed(
378 consumed.bytes_consumed);
379 return consumed;
380 }
381
save_frame()382 const QuicFrame& save_frame() { return save_frame_; }
383
SaveFrame(const QuicFrame & frame)384 bool SaveFrame(const QuicFrame& frame) {
385 save_frame_ = frame;
386 DeleteFrame(&const_cast<QuicFrame&>(frame));
387 return true;
388 }
389
SendLargeFakeData(QuicStream * stream,int bytes)390 QuicConsumedData SendLargeFakeData(QuicStream* stream, int bytes) {
391 QUICHE_DCHECK(writev_consumes_all_data_);
392 return WritevData(stream->id(), bytes, 0, FIN, NOT_RETRANSMISSION,
393 GetEncryptionLevelToSendApplicationData());
394 }
395
UsesPendingStreamForFrame(QuicFrameType type,QuicStreamId stream_id) const396 bool UsesPendingStreamForFrame(QuicFrameType type,
397 QuicStreamId stream_id) const override {
398 if (!uses_pending_streams_) {
399 return false;
400 }
401 // Uses pending stream for STREAM/RST_STREAM frames with unidirectional read
402 // stream and uses pending stream for
403 // STREAM/RST_STREAM/STOP_SENDING/WINDOW_UPDATE frames with bidirectional
404 // stream.
405 bool is_incoming_stream = IsIncomingStream(stream_id);
406 StreamType stream_type = QuicUtils::GetStreamType(
407 stream_id, perspective(), is_incoming_stream, version());
408 switch (type) {
409 case STREAM_FRAME:
410 ABSL_FALLTHROUGH_INTENDED;
411 case RST_STREAM_FRAME:
412 return is_incoming_stream;
413 case STOP_SENDING_FRAME:
414 ABSL_FALLTHROUGH_INTENDED;
415 case WINDOW_UPDATE_FRAME:
416 return stream_type == BIDIRECTIONAL;
417 default:
418 return false;
419 }
420 }
421
set_uses_pending_streams(bool uses_pending_streams)422 void set_uses_pending_streams(bool uses_pending_streams) {
423 uses_pending_streams_ = uses_pending_streams;
424 }
425
num_incoming_streams_created() const426 int num_incoming_streams_created() const {
427 return num_incoming_streams_created_;
428 }
429
430 using QuicSession::ActivateStream;
431 using QuicSession::CanOpenNextOutgoingBidirectionalStream;
432 using QuicSession::CanOpenNextOutgoingUnidirectionalStream;
433 using QuicSession::closed_streams;
434 using QuicSession::GetNextOutgoingBidirectionalStreamId;
435 using QuicSession::GetNextOutgoingUnidirectionalStreamId;
436
437 private:
438 StrictMock<TestCryptoStream> crypto_stream_;
439
440 bool writev_consumes_all_data_;
441 bool uses_pending_streams_;
442 QuicFrame save_frame_;
443 int num_incoming_streams_created_;
444 };
445
446 MATCHER_P(IsFrame, type, "") { return arg.type == type; }
447
448 class QuicSessionTestBase : public QuicTestWithParam<ParsedQuicVersion> {
449 protected:
QuicSessionTestBase(Perspective perspective,bool configure_session)450 QuicSessionTestBase(Perspective perspective, bool configure_session)
451 : connection_(new StrictMock<MockQuicConnection>(
452 &helper_, &alarm_factory_, perspective,
453 SupportedVersions(GetParam()))),
454 session_(connection_, &session_visitor_),
455 configure_session_(configure_session) {
456 session_.config()->SetInitialStreamFlowControlWindowToSend(
457 kInitialStreamFlowControlWindowForTest);
458 session_.config()->SetInitialSessionFlowControlWindowToSend(
459 kInitialSessionFlowControlWindowForTest);
460
461 if (configure_session) {
462 if (VersionHasIetfQuicFrames(transport_version())) {
463 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
464 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(true)).Times(1);
465 }
466 QuicConfigPeer::SetReceivedMaxBidirectionalStreams(
467 session_.config(), kDefaultMaxStreamsPerConnection);
468 QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(
469 session_.config(), kDefaultMaxStreamsPerConnection);
470 QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional(
471 session_.config(), kMinimumFlowControlSendWindow);
472 QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional(
473 session_.config(), kMinimumFlowControlSendWindow);
474 QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
475 session_.config(), kMinimumFlowControlSendWindow);
476 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
477 session_.config(), kMinimumFlowControlSendWindow);
478 connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
479 session_.OnConfigNegotiated();
480 }
481 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
482 EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
483 .Times(testing::AnyNumber());
484 testing::Mock::VerifyAndClearExpectations(&session_);
485 }
486
~QuicSessionTestBase()487 ~QuicSessionTestBase() {
488 if (configure_session_) {
489 EXPECT_TRUE(session_.is_configured());
490 }
491 }
492
CheckClosedStreams()493 void CheckClosedStreams() {
494 QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId(
495 connection_->transport_version(), Perspective::IS_CLIENT);
496 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
497 first_stream_id =
498 QuicUtils::GetCryptoStreamId(connection_->transport_version());
499 }
500 for (QuicStreamId i = first_stream_id; i < 100; i++) {
501 if (closed_streams_.find(i) == closed_streams_.end()) {
502 EXPECT_FALSE(session_.IsClosedStream(i)) << " stream id: " << i;
503 } else {
504 EXPECT_TRUE(session_.IsClosedStream(i)) << " stream id: " << i;
505 }
506 }
507 }
508
CloseStream(QuicStreamId id)509 void CloseStream(QuicStreamId id) {
510 if (VersionHasIetfQuicFrames(transport_version())) {
511 if (QuicUtils::GetStreamType(
512 id, session_.perspective(), session_.IsIncomingStream(id),
513 connection_->version()) == READ_UNIDIRECTIONAL) {
514 // Verify STOP_SENDING but no RST_STREAM is sent for
515 // READ_UNIDIRECTIONAL streams.
516 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME)))
517 .Times(1)
518 .WillOnce(Invoke(&ClearControlFrame));
519 EXPECT_CALL(*connection_, OnStreamReset(id, _)).Times(1);
520 } else if (QuicUtils::GetStreamType(
521 id, session_.perspective(), session_.IsIncomingStream(id),
522 connection_->version()) == WRITE_UNIDIRECTIONAL) {
523 // Verify RST_STREAM but not STOP_SENDING is sent for write-only
524 // stream.
525 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME)))
526 .Times(1)
527 .WillOnce(Invoke(&ClearControlFrame));
528 EXPECT_CALL(*connection_, OnStreamReset(id, _));
529 } else {
530 // Verify RST_STREAM and STOP_SENDING are sent for BIDIRECTIONAL
531 // streams.
532 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME)))
533 .WillRepeatedly(Invoke(&ClearControlFrame));
534 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME)))
535 .WillRepeatedly(Invoke(&ClearControlFrame));
536 EXPECT_CALL(*connection_, OnStreamReset(id, _));
537 }
538 } else {
539 EXPECT_CALL(*connection_, SendControlFrame(_))
540 .WillOnce(Invoke(&ClearControlFrame));
541 EXPECT_CALL(*connection_, OnStreamReset(id, _));
542 }
543 session_.ResetStream(id, QUIC_STREAM_CANCELLED);
544 closed_streams_.insert(id);
545 }
546
CompleteHandshake()547 void CompleteHandshake() {
548 CryptoHandshakeMessage msg;
549 if (connection_->version().UsesTls() &&
550 connection_->perspective() == Perspective::IS_SERVER) {
551 // HANDSHAKE_DONE frame.
552 EXPECT_CALL(*connection_, SendControlFrame(_))
553 .WillOnce(Invoke(&ClearControlFrame));
554 }
555 session_.GetMutableCryptoStream()->OnHandshakeMessage(msg);
556 }
557
transport_version() const558 QuicTransportVersion transport_version() const {
559 return connection_->transport_version();
560 }
561
GetNthClientInitiatedBidirectionalId(int n)562 QuicStreamId GetNthClientInitiatedBidirectionalId(int n) {
563 return QuicUtils::GetFirstBidirectionalStreamId(
564 connection_->transport_version(), Perspective::IS_CLIENT) +
565 QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
566 }
567
GetNthClientInitiatedUnidirectionalId(int n)568 QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) {
569 return QuicUtils::GetFirstUnidirectionalStreamId(
570 connection_->transport_version(), Perspective::IS_CLIENT) +
571 QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
572 }
573
GetNthServerInitiatedBidirectionalId(int n)574 QuicStreamId GetNthServerInitiatedBidirectionalId(int n) {
575 return QuicUtils::GetFirstBidirectionalStreamId(
576 connection_->transport_version(), Perspective::IS_SERVER) +
577 QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
578 }
579
GetNthServerInitiatedUnidirectionalId(int n)580 QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) {
581 return QuicUtils::GetFirstUnidirectionalStreamId(
582 connection_->transport_version(), Perspective::IS_SERVER) +
583 QuicUtils::StreamIdDelta(connection_->transport_version()) * n;
584 }
585
StreamCountToId(QuicStreamCount stream_count,Perspective perspective,bool bidirectional)586 QuicStreamId StreamCountToId(QuicStreamCount stream_count,
587 Perspective perspective, bool bidirectional) {
588 // Calculate and build up stream ID rather than use
589 // GetFirst... because tests that rely on this method
590 // needs to do the stream count where #1 is 0/1/2/3, and not
591 // take into account that stream 0 is special.
592 QuicStreamId id =
593 ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version()));
594 if (!bidirectional) {
595 id |= 0x2;
596 }
597 if (perspective == Perspective::IS_SERVER) {
598 id |= 0x1;
599 }
600 return id;
601 }
602
603 MockQuicConnectionHelper helper_;
604 MockAlarmFactory alarm_factory_;
605 NiceMock<MockQuicSessionVisitor> session_visitor_;
606 StrictMock<MockQuicConnection>* connection_;
607 TestSession session_;
608 std::set<QuicStreamId> closed_streams_;
609 bool configure_session_;
610 };
611
612 class QuicSessionTestServer : public QuicSessionTestBase {
613 public:
614 // CheckMultiPathResponse validates that a written packet
615 // contains both expected path responses.
CheckMultiPathResponse(const char * buffer,size_t buf_len,const QuicIpAddress &,const QuicSocketAddress &,PerPacketOptions *)616 WriteResult CheckMultiPathResponse(const char* buffer, size_t buf_len,
617 const QuicIpAddress& /*self_address*/,
618 const QuicSocketAddress& /*peer_address*/,
619 PerPacketOptions* /*options*/) {
620 QuicEncryptedPacket packet(buffer, buf_len);
621 {
622 InSequence s;
623 EXPECT_CALL(framer_visitor_, OnPacket());
624 EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_));
625 EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_));
626 EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _));
627 EXPECT_CALL(framer_visitor_, OnPacketHeader(_));
628 EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_))
629 .WillOnce(
630 WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) {
631 EXPECT_EQ(path_frame_buffer1_, frame.data_buffer);
632 return true;
633 })));
634 EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_))
635 .WillOnce(
636 WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) {
637 EXPECT_EQ(path_frame_buffer2_, frame.data_buffer);
638 return true;
639 })));
640 EXPECT_CALL(framer_visitor_, OnPacketComplete());
641 }
642 client_framer_.ProcessPacket(packet);
643 return WriteResult(WRITE_STATUS_OK, 0);
644 }
645
646 protected:
QuicSessionTestServer()647 QuicSessionTestServer()
648 : QuicSessionTestBase(Perspective::IS_SERVER, /*configure_session=*/true),
649 path_frame_buffer1_({0, 1, 2, 3, 4, 5, 6, 7}),
650 path_frame_buffer2_({8, 9, 10, 11, 12, 13, 14, 15}),
651 client_framer_(SupportedVersions(GetParam()), QuicTime::Zero(),
652 Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength) {
653 client_framer_.set_visitor(&framer_visitor_);
654 client_framer_.SetInitialObfuscators(TestConnectionId());
655 if (client_framer_.version().KnowsWhichDecrypterToUse()) {
656 client_framer_.InstallDecrypter(
657 ENCRYPTION_FORWARD_SECURE,
658 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
659 }
660 }
661
662 QuicPathFrameBuffer path_frame_buffer1_;
663 QuicPathFrameBuffer path_frame_buffer2_;
664 StrictMock<MockFramerVisitor> framer_visitor_;
665 // Framer used to process packets sent by server.
666 QuicFramer client_framer_;
667 };
668
669 INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestServer,
670 ::testing::ValuesIn(AllSupportedVersions()),
671 ::testing::PrintToStringParamName());
672
TEST_P(QuicSessionTestServer,PeerAddress)673 TEST_P(QuicSessionTestServer, PeerAddress) {
674 EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort),
675 session_.peer_address());
676 }
677
TEST_P(QuicSessionTestServer,SelfAddress)678 TEST_P(QuicSessionTestServer, SelfAddress) {
679 EXPECT_TRUE(session_.self_address().IsInitialized());
680 }
681
TEST_P(QuicSessionTestServer,DontCallOnWriteBlockedForDisconnectedConnection)682 TEST_P(QuicSessionTestServer, DontCallOnWriteBlockedForDisconnectedConnection) {
683 EXPECT_CALL(*connection_, CloseConnection(_, _, _))
684 .WillOnce(
685 Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
686 connection_->CloseConnection(QUIC_NO_ERROR, "Everything is fine.",
687 ConnectionCloseBehavior::SILENT_CLOSE);
688 ASSERT_FALSE(connection_->connected());
689
690 EXPECT_CALL(session_visitor_, OnWriteBlocked(_)).Times(0);
691 session_.OnWriteBlocked();
692 }
693
TEST_P(QuicSessionTestServer,OneRttKeysAvailable)694 TEST_P(QuicSessionTestServer, OneRttKeysAvailable) {
695 EXPECT_FALSE(session_.OneRttKeysAvailable());
696 CompleteHandshake();
697 EXPECT_TRUE(session_.OneRttKeysAvailable());
698 }
699
TEST_P(QuicSessionTestServer,IsClosedStreamDefault)700 TEST_P(QuicSessionTestServer, IsClosedStreamDefault) {
701 // Ensure that no streams are initially closed.
702 QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId(
703 connection_->transport_version(), Perspective::IS_CLIENT);
704 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
705 first_stream_id =
706 QuicUtils::GetCryptoStreamId(connection_->transport_version());
707 }
708 for (QuicStreamId i = first_stream_id; i < 100; i++) {
709 EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i;
710 }
711 }
712
TEST_P(QuicSessionTestServer,AvailableBidirectionalStreams)713 TEST_P(QuicSessionTestServer, AvailableBidirectionalStreams) {
714 ASSERT_TRUE(session_.GetOrCreateStream(
715 GetNthClientInitiatedBidirectionalId(3)) != nullptr);
716 // Smaller bidirectional streams should be available.
717 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
718 &session_, GetNthClientInitiatedBidirectionalId(1)));
719 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
720 &session_, GetNthClientInitiatedBidirectionalId(2)));
721 ASSERT_TRUE(session_.GetOrCreateStream(
722 GetNthClientInitiatedBidirectionalId(2)) != nullptr);
723 ASSERT_TRUE(session_.GetOrCreateStream(
724 GetNthClientInitiatedBidirectionalId(1)) != nullptr);
725 }
726
TEST_P(QuicSessionTestServer,AvailableUnidirectionalStreams)727 TEST_P(QuicSessionTestServer, AvailableUnidirectionalStreams) {
728 ASSERT_TRUE(session_.GetOrCreateStream(
729 GetNthClientInitiatedUnidirectionalId(3)) != nullptr);
730 // Smaller unidirectional streams should be available.
731 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
732 &session_, GetNthClientInitiatedUnidirectionalId(1)));
733 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
734 &session_, GetNthClientInitiatedUnidirectionalId(2)));
735 ASSERT_TRUE(session_.GetOrCreateStream(
736 GetNthClientInitiatedUnidirectionalId(2)) != nullptr);
737 ASSERT_TRUE(session_.GetOrCreateStream(
738 GetNthClientInitiatedUnidirectionalId(1)) != nullptr);
739 }
740
TEST_P(QuicSessionTestServer,MaxAvailableBidirectionalStreams)741 TEST_P(QuicSessionTestServer, MaxAvailableBidirectionalStreams) {
742 if (VersionHasIetfQuicFrames(transport_version())) {
743 EXPECT_EQ(session_.max_open_incoming_bidirectional_streams(),
744 session_.MaxAvailableBidirectionalStreams());
745 } else {
746 // The protocol specification requires that there can be at least 10 times
747 // as many available streams as the connection's maximum open streams.
748 EXPECT_EQ(session_.max_open_incoming_bidirectional_streams() *
749 kMaxAvailableStreamsMultiplier,
750 session_.MaxAvailableBidirectionalStreams());
751 }
752 }
753
TEST_P(QuicSessionTestServer,MaxAvailableUnidirectionalStreams)754 TEST_P(QuicSessionTestServer, MaxAvailableUnidirectionalStreams) {
755 if (VersionHasIetfQuicFrames(transport_version())) {
756 EXPECT_EQ(session_.max_open_incoming_unidirectional_streams(),
757 session_.MaxAvailableUnidirectionalStreams());
758 } else {
759 // The protocol specification requires that there can be at least 10 times
760 // as many available streams as the connection's maximum open streams.
761 EXPECT_EQ(session_.max_open_incoming_unidirectional_streams() *
762 kMaxAvailableStreamsMultiplier,
763 session_.MaxAvailableUnidirectionalStreams());
764 }
765 }
766
TEST_P(QuicSessionTestServer,IsClosedBidirectionalStreamLocallyCreated)767 TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamLocallyCreated) {
768 CompleteHandshake();
769 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
770 EXPECT_EQ(GetNthServerInitiatedBidirectionalId(0), stream2->id());
771 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
772 EXPECT_EQ(GetNthServerInitiatedBidirectionalId(1), stream4->id());
773
774 CheckClosedStreams();
775 CloseStream(GetNthServerInitiatedBidirectionalId(0));
776 CheckClosedStreams();
777 CloseStream(GetNthServerInitiatedBidirectionalId(1));
778 CheckClosedStreams();
779 }
780
TEST_P(QuicSessionTestServer,IsClosedUnidirectionalStreamLocallyCreated)781 TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamLocallyCreated) {
782 CompleteHandshake();
783 TestStream* stream2 = session_.CreateOutgoingUnidirectionalStream();
784 EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(0), stream2->id());
785 TestStream* stream4 = session_.CreateOutgoingUnidirectionalStream();
786 EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(1), stream4->id());
787
788 CheckClosedStreams();
789 CloseStream(GetNthServerInitiatedUnidirectionalId(0));
790 CheckClosedStreams();
791 CloseStream(GetNthServerInitiatedUnidirectionalId(1));
792 CheckClosedStreams();
793 }
794
TEST_P(QuicSessionTestServer,IsClosedBidirectionalStreamPeerCreated)795 TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamPeerCreated) {
796 CompleteHandshake();
797 QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0);
798 QuicStreamId stream_id2 = GetNthClientInitiatedBidirectionalId(1);
799 session_.GetOrCreateStream(stream_id1);
800 session_.GetOrCreateStream(stream_id2);
801
802 CheckClosedStreams();
803 CloseStream(stream_id1);
804 CheckClosedStreams();
805 CloseStream(stream_id2);
806 // Create a stream, and make another available.
807 QuicStream* stream3 = session_.GetOrCreateStream(
808 stream_id2 +
809 2 * QuicUtils::StreamIdDelta(connection_->transport_version()));
810 CheckClosedStreams();
811 // Close one, but make sure the other is still not closed
812 CloseStream(stream3->id());
813 CheckClosedStreams();
814 }
815
TEST_P(QuicSessionTestServer,IsClosedUnidirectionalStreamPeerCreated)816 TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamPeerCreated) {
817 CompleteHandshake();
818 QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0);
819 QuicStreamId stream_id2 = GetNthClientInitiatedUnidirectionalId(1);
820 session_.GetOrCreateStream(stream_id1);
821 session_.GetOrCreateStream(stream_id2);
822
823 CheckClosedStreams();
824 CloseStream(stream_id1);
825 CheckClosedStreams();
826 CloseStream(stream_id2);
827 // Create a stream, and make another available.
828 QuicStream* stream3 = session_.GetOrCreateStream(
829 stream_id2 +
830 2 * QuicUtils::StreamIdDelta(connection_->transport_version()));
831 CheckClosedStreams();
832 // Close one, but make sure the other is still not closed
833 CloseStream(stream3->id());
834 CheckClosedStreams();
835 }
836
TEST_P(QuicSessionTestServer,MaximumAvailableOpenedBidirectionalStreams)837 TEST_P(QuicSessionTestServer, MaximumAvailableOpenedBidirectionalStreams) {
838 QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
839 session_.GetOrCreateStream(stream_id);
840 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
841 EXPECT_NE(nullptr,
842 session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(
843 session_.max_open_incoming_bidirectional_streams() - 1)));
844 }
845
TEST_P(QuicSessionTestServer,MaximumAvailableOpenedUnidirectionalStreams)846 TEST_P(QuicSessionTestServer, MaximumAvailableOpenedUnidirectionalStreams) {
847 QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0);
848 session_.GetOrCreateStream(stream_id);
849 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
850 EXPECT_NE(nullptr,
851 session_.GetOrCreateStream(GetNthClientInitiatedUnidirectionalId(
852 session_.max_open_incoming_unidirectional_streams() - 1)));
853 }
854
TEST_P(QuicSessionTestServer,TooManyAvailableBidirectionalStreams)855 TEST_P(QuicSessionTestServer, TooManyAvailableBidirectionalStreams) {
856 QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0);
857 QuicStreamId stream_id2;
858 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1));
859 // A stream ID which is too large to create.
860 stream_id2 = GetNthClientInitiatedBidirectionalId(
861 session_.MaxAvailableBidirectionalStreams() + 2);
862 if (VersionHasIetfQuicFrames(transport_version())) {
863 // IETF QUIC terminates the connection with invalid stream id
864 EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
865 } else {
866 // other versions terminate the connection with
867 // QUIC_TOO_MANY_AVAILABLE_STREAMS.
868 EXPECT_CALL(*connection_,
869 CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _));
870 }
871 EXPECT_EQ(nullptr, session_.GetOrCreateStream(stream_id2));
872 }
873
TEST_P(QuicSessionTestServer,TooManyAvailableUnidirectionalStreams)874 TEST_P(QuicSessionTestServer, TooManyAvailableUnidirectionalStreams) {
875 QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0);
876 QuicStreamId stream_id2;
877 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1));
878 // A stream ID which is too large to create.
879 stream_id2 = GetNthClientInitiatedUnidirectionalId(
880 session_.MaxAvailableUnidirectionalStreams() + 2);
881 if (VersionHasIetfQuicFrames(transport_version())) {
882 // IETF QUIC terminates the connection with invalid stream id
883 EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
884 } else {
885 // other versions terminate the connection with
886 // QUIC_TOO_MANY_AVAILABLE_STREAMS.
887 EXPECT_CALL(*connection_,
888 CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _));
889 }
890 EXPECT_EQ(nullptr, session_.GetOrCreateStream(stream_id2));
891 }
892
TEST_P(QuicSessionTestServer,ManyAvailableBidirectionalStreams)893 TEST_P(QuicSessionTestServer, ManyAvailableBidirectionalStreams) {
894 // When max_open_streams_ is 200, should be able to create 200 streams
895 // out-of-order, that is, creating the one with the largest stream ID first.
896 if (VersionHasIetfQuicFrames(transport_version())) {
897 QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 200);
898 // Smaller limit on unidirectional streams to help detect crossed wires.
899 QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 50);
900 } else {
901 QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200);
902 }
903 // Create a stream at the start of the range.
904 QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
905 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
906
907 // Create the largest stream ID of a threatened total of 200 streams.
908 // GetNth... starts at 0, so for 200 streams, get the 199th.
909 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
910 EXPECT_NE(nullptr, session_.GetOrCreateStream(
911 GetNthClientInitiatedBidirectionalId(199)));
912
913 if (VersionHasIetfQuicFrames(transport_version())) {
914 // If IETF QUIC, check to make sure that creating bidirectional
915 // streams does not mess up the unidirectional streams.
916 stream_id = GetNthClientInitiatedUnidirectionalId(0);
917 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
918 // Now try to get the last possible unidirectional stream.
919 EXPECT_NE(nullptr, session_.GetOrCreateStream(
920 GetNthClientInitiatedUnidirectionalId(49)));
921 // and this should fail because it exceeds the unidirectional limit
922 // (but not the bi-)
923 EXPECT_CALL(
924 *connection_,
925 CloseConnection(QUIC_INVALID_STREAM_ID,
926 "Stream id 798 would exceed stream count limit 50",
927 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
928 .Times(1);
929 EXPECT_EQ(nullptr, session_.GetOrCreateStream(
930 GetNthClientInitiatedUnidirectionalId(199)));
931 }
932 }
933
TEST_P(QuicSessionTestServer,ManyAvailableUnidirectionalStreams)934 TEST_P(QuicSessionTestServer, ManyAvailableUnidirectionalStreams) {
935 // When max_open_streams_ is 200, should be able to create 200 streams
936 // out-of-order, that is, creating the one with the largest stream ID first.
937 if (VersionHasIetfQuicFrames(transport_version())) {
938 QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 200);
939 // Smaller limit on unidirectional streams to help detect crossed wires.
940 QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 50);
941 } else {
942 QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200);
943 }
944 // Create one stream.
945 QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0);
946 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
947
948 // Create the largest stream ID of a threatened total of 200 streams.
949 // GetNth... starts at 0, so for 200 streams, get the 199th.
950 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
951 EXPECT_NE(nullptr, session_.GetOrCreateStream(
952 GetNthClientInitiatedUnidirectionalId(199)));
953 if (VersionHasIetfQuicFrames(transport_version())) {
954 // If IETF QUIC, check to make sure that creating unidirectional
955 // streams does not mess up the bidirectional streams.
956 stream_id = GetNthClientInitiatedBidirectionalId(0);
957 EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id));
958 // Now try to get the last possible bidirectional stream.
959 EXPECT_NE(nullptr, session_.GetOrCreateStream(
960 GetNthClientInitiatedBidirectionalId(49)));
961 // and this should fail because it exceeds the bnidirectional limit
962 // (but not the uni-)
963 std::string error_detail;
964 if (QuicVersionUsesCryptoFrames(transport_version())) {
965 error_detail = "Stream id 796 would exceed stream count limit 50";
966 } else {
967 error_detail = "Stream id 800 would exceed stream count limit 50";
968 }
969 EXPECT_CALL(
970 *connection_,
971 CloseConnection(QUIC_INVALID_STREAM_ID, error_detail,
972 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
973 .Times(1);
974 EXPECT_EQ(nullptr, session_.GetOrCreateStream(
975 GetNthClientInitiatedBidirectionalId(199)));
976 }
977 }
978
TEST_P(QuicSessionTestServer,DebugDFatalIfMarkingClosedStreamWriteBlocked)979 TEST_P(QuicSessionTestServer, DebugDFatalIfMarkingClosedStreamWriteBlocked) {
980 CompleteHandshake();
981 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
982 QuicStreamId closed_stream_id = stream2->id();
983 // Close the stream.
984 EXPECT_CALL(*connection_, SendControlFrame(_));
985 EXPECT_CALL(*connection_, OnStreamReset(closed_stream_id, _));
986 stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
987 std::string msg =
988 absl::StrCat("Marking unknown stream ", closed_stream_id, " blocked.");
989 EXPECT_QUIC_BUG(session_.MarkConnectionLevelWriteBlocked(closed_stream_id),
990 msg);
991 }
992
993 // SpdySession::OnCanWrite() queries QuicWriteBlockedList for the number of
994 // streams that are marked as connection level write blocked, then queries
995 // QuicWriteBlockedList that many times for what stream to write data on. This
996 // can result in some streams writing multiple times in a single
997 // SpdySession::OnCanWrite() call while other streams not getting a turn.
TEST_P(QuicSessionTestServer,OnCanWrite)998 TEST_P(QuicSessionTestServer, OnCanWrite) {
999 CompleteHandshake();
1000 session_.set_writev_consumes_all_data(true);
1001 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1002 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1003 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1004
1005 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1006 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1007 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1008
1009 InSequence s;
1010
1011 // Reregister, to test the loop limit.
1012 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1013 session_.SendStreamData(stream2);
1014 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1015 }));
1016
1017 if (!GetQuicReloadableFlag(quic_disable_batch_write) ||
1018 GetQuicReloadableFlag(quic_priority_respect_incremental)) {
1019 // If batched writes are enabled, stream 2 will write again. Also, streams
1020 // are non-incremental by default, so if the incremental flag is respected,
1021 // then stream 2 will write again. (If it is not respected, then every
1022 // stream is treated as incremental.)
1023 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1024 session_.SendStreamData(stream2);
1025 }));
1026 EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1027 session_.SendStreamData(stream6);
1028 }));
1029 } else {
1030 EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1031 session_.SendStreamData(stream6);
1032 }));
1033 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1034 session_.SendStreamData(stream4);
1035 }));
1036 }
1037
1038 // Stream 4 will not get called, as we exceeded the loop limit.
1039 session_.OnCanWrite();
1040 EXPECT_TRUE(session_.WillingAndAbleToWrite());
1041 }
1042
TEST_P(QuicSessionTestServer,TestBatchedWrites)1043 TEST_P(QuicSessionTestServer, TestBatchedWrites) {
1044 session_.set_writev_consumes_all_data(true);
1045 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1046 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1047 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1048
1049 const QuicStreamPriority priority(
1050 HttpStreamPriority{HttpStreamPriority::kDefaultUrgency,
1051 /* incremental = */ true});
1052 stream2->SetPriority(priority);
1053 stream4->SetPriority(priority);
1054 stream6->SetPriority(priority);
1055
1056 session_.set_writev_consumes_all_data(true);
1057 // Tell the session that stream2 and stream4 have data to write.
1058 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1059 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1060
1061 // With two sessions blocked, we should get two write calls.
1062 InSequence s;
1063 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1064 session_.SendLargeFakeData(stream2, 6000);
1065 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1066 }));
1067 if (GetQuicReloadableFlag(quic_disable_batch_write)) {
1068 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1069 session_.SendLargeFakeData(stream4, 6000);
1070 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1071 }));
1072 } else {
1073 // Since stream2 only wrote 6 kB and marked itself blocked again,
1074 // the second write happens on the same stream.
1075 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1076 session_.SendLargeFakeData(stream2, 6000);
1077 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1078 }));
1079 }
1080 session_.OnCanWrite();
1081
1082 // If batched write is enabled, stream2 can write a third time in a row.
1083 // If batched write is disabled, stream2 has a turn again after stream4.
1084 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1085 session_.SendLargeFakeData(stream2, 6000);
1086 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1087 }));
1088 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1089 session_.SendLargeFakeData(stream4, 6000);
1090 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1091 }));
1092 session_.OnCanWrite();
1093
1094 // The next write adds a block for stream 6.
1095 stream6->SetPriority(QuicStreamPriority(HttpStreamPriority{
1096 kV3HighestPriority, HttpStreamPriority::kDefaultIncremental}));
1097 if (GetQuicReloadableFlag(quic_disable_batch_write)) {
1098 EXPECT_CALL(*stream2, OnCanWrite())
1099 .WillOnce(Invoke([this, stream2, stream6]() {
1100 session_.SendLargeFakeData(stream2, 6000);
1101 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1102 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1103 }));
1104 } else {
1105 EXPECT_CALL(*stream4, OnCanWrite())
1106 .WillOnce(Invoke([this, stream4, stream6]() {
1107 session_.SendLargeFakeData(stream4, 6000);
1108 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1109 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1110 }));
1111 }
1112 // Stream 6 will write next, because it has higher priority.
1113 // It does not mark itself as blocked.
1114 EXPECT_CALL(*stream6, OnCanWrite())
1115 .WillOnce(Invoke([this, stream4, stream6]() {
1116 session_.SendStreamData(stream6);
1117 session_.SendLargeFakeData(stream4, 6000);
1118 }));
1119 session_.OnCanWrite();
1120
1121 // If batched write is enabled, stream4 can continue to write, but will
1122 // exhaust its write limit, so the last write is on stream2.
1123 // If batched write is disabled, stream4 has a turn again, then stream2.
1124 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1125 session_.SendLargeFakeData(stream4, 12000);
1126 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1127 }));
1128 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1129 session_.SendLargeFakeData(stream2, 6000);
1130 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1131 }));
1132 session_.OnCanWrite();
1133 }
1134
TEST_P(QuicSessionTestServer,OnCanWriteBundlesStreams)1135 TEST_P(QuicSessionTestServer, OnCanWriteBundlesStreams) {
1136 // Encryption needs to be established before data can be sent.
1137 CompleteHandshake();
1138 MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1139 QuicConnectionPeer::GetWriter(session_.connection()));
1140
1141 // Drive congestion control manually.
1142 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1143 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1144
1145 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1146 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1147 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1148
1149 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1150 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1151 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1152
1153 EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1154 EXPECT_CALL(*send_algorithm, GetCongestionWindow())
1155 .WillRepeatedly(Return(kMaxOutgoingPacketSize * 10));
1156 EXPECT_CALL(*send_algorithm, InRecovery()).WillRepeatedly(Return(false));
1157 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1158 session_.SendStreamData(stream2);
1159 }));
1160 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1161 session_.SendStreamData(stream4);
1162 }));
1163 EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1164 session_.SendStreamData(stream6);
1165 }));
1166
1167 // Expect that we only send one packet, the writes from different streams
1168 // should be bundled together.
1169 EXPECT_CALL(*writer, WritePacket(_, _, _, _, _, _))
1170 .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1171 EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _));
1172 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1173 session_.OnCanWrite();
1174 EXPECT_FALSE(session_.WillingAndAbleToWrite());
1175 }
1176
TEST_P(QuicSessionTestServer,OnCanWriteCongestionControlBlocks)1177 TEST_P(QuicSessionTestServer, OnCanWriteCongestionControlBlocks) {
1178 CompleteHandshake();
1179 session_.set_writev_consumes_all_data(true);
1180 InSequence s;
1181
1182 // Drive congestion control manually.
1183 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1184 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1185
1186 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1187 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1188 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1189
1190 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1191 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1192 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1193
1194 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1195 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1196 session_.SendStreamData(stream2);
1197 }));
1198 EXPECT_CALL(*send_algorithm, GetCongestionWindow()).Times(AnyNumber());
1199 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1200 EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
1201 session_.SendStreamData(stream6);
1202 }));
1203 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
1204 // stream4->OnCanWrite is not called.
1205
1206 session_.OnCanWrite();
1207 EXPECT_TRUE(session_.WillingAndAbleToWrite());
1208
1209 // Still congestion-control blocked.
1210 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
1211 session_.OnCanWrite();
1212 EXPECT_TRUE(session_.WillingAndAbleToWrite());
1213
1214 // stream4->OnCanWrite is called once the connection stops being
1215 // congestion-control blocked.
1216 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
1217 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1218 session_.SendStreamData(stream4);
1219 }));
1220 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1221 session_.OnCanWrite();
1222 EXPECT_FALSE(session_.WillingAndAbleToWrite());
1223 }
1224
TEST_P(QuicSessionTestServer,OnCanWriteWriterBlocks)1225 TEST_P(QuicSessionTestServer, OnCanWriteWriterBlocks) {
1226 CompleteHandshake();
1227 // Drive congestion control manually in order to ensure that
1228 // application-limited signaling is handled correctly.
1229 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1230 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1231 EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1232
1233 // Drive packet writer manually.
1234 MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1235 QuicConnectionPeer::GetWriter(session_.connection()));
1236 EXPECT_CALL(*writer, IsWriteBlocked()).WillRepeatedly(Return(true));
1237 EXPECT_CALL(*writer, WritePacket(_, _, _, _, _, _)).Times(0);
1238
1239 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1240
1241 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1242
1243 EXPECT_CALL(*stream2, OnCanWrite()).Times(0);
1244 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_)).Times(0);
1245
1246 session_.OnCanWrite();
1247 EXPECT_TRUE(session_.WillingAndAbleToWrite());
1248 }
1249
TEST_P(QuicSessionTestServer,SendStreamsBlocked)1250 TEST_P(QuicSessionTestServer, SendStreamsBlocked) {
1251 if (!VersionHasIetfQuicFrames(transport_version())) {
1252 return;
1253 }
1254 CompleteHandshake();
1255 for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) {
1256 ASSERT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
1257 session_.GetNextOutgoingBidirectionalStreamId();
1258 }
1259 // Next checking causes STREAMS_BLOCKED to be sent.
1260 EXPECT_CALL(*connection_, SendControlFrame(_))
1261 .WillOnce(Invoke([](const QuicFrame& frame) {
1262 EXPECT_FALSE(frame.streams_blocked_frame.unidirectional);
1263 EXPECT_EQ(kDefaultMaxStreamsPerConnection,
1264 frame.streams_blocked_frame.stream_count);
1265 ClearControlFrame(frame);
1266 return true;
1267 }));
1268 EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream());
1269
1270 for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) {
1271 ASSERT_TRUE(session_.CanOpenNextOutgoingUnidirectionalStream());
1272 session_.GetNextOutgoingUnidirectionalStreamId();
1273 }
1274 // Next checking causes STREAM_BLOCKED to be sent.
1275 EXPECT_CALL(*connection_, SendControlFrame(_))
1276 .WillOnce(Invoke([](const QuicFrame& frame) {
1277 EXPECT_TRUE(frame.streams_blocked_frame.unidirectional);
1278 EXPECT_EQ(kDefaultMaxStreamsPerConnection,
1279 frame.streams_blocked_frame.stream_count);
1280 ClearControlFrame(frame);
1281 return true;
1282 }));
1283 EXPECT_FALSE(session_.CanOpenNextOutgoingUnidirectionalStream());
1284 }
1285
TEST_P(QuicSessionTestServer,LimitMaxStreams)1286 TEST_P(QuicSessionTestServer, LimitMaxStreams) {
1287 if (!VersionHasIetfQuicFrames(transport_version())) {
1288 return;
1289 }
1290 CompleteHandshake();
1291
1292 const QuicStreamId kMaxStreams = 4;
1293 QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_,
1294 kMaxStreams);
1295 EXPECT_EQ(kMaxStreams, QuicSessionPeer::ietf_streamid_manager(&session_)
1296 ->advertised_max_incoming_bidirectional_streams());
1297
1298 // Open and close the entire max streams window which will result
1299 // in two MAX_STREAMS frames being sent.
1300 std::vector<QuicMaxStreamsFrame> max_stream_frames;
1301 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(MAX_STREAMS_FRAME)))
1302 .Times(2)
1303 .WillRepeatedly(Invoke([&max_stream_frames](const QuicFrame& frame) {
1304 max_stream_frames.push_back(frame.max_streams_frame);
1305 ClearControlFrame(frame);
1306 return true;
1307 }));
1308 for (size_t i = 0; i < kMaxStreams; ++i) {
1309 QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(i);
1310 QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT"));
1311 session_.OnStreamFrame(data1);
1312
1313 CloseStream(stream_id);
1314 }
1315 EXPECT_EQ(2 * kMaxStreams,
1316 QuicSessionPeer::ietf_streamid_manager(&session_)
1317 ->advertised_max_incoming_bidirectional_streams());
1318
1319 // Opening and closing the next max streams window should NOT result
1320 // in any MAX_STREAMS frames being sent.
1321 QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_);
1322 if (alarm->IsSet()) {
1323 alarm_factory_.FireAlarm(alarm);
1324 }
1325 for (size_t i = 0; i < kMaxStreams; ++i) {
1326 QuicStreamId stream_id =
1327 GetNthClientInitiatedBidirectionalId(i + kMaxStreams);
1328 QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT"));
1329 session_.OnStreamFrame(data1);
1330
1331 CloseStream(stream_id);
1332 }
1333
1334 // Now when the outstanding MAX_STREAMS frame is ACK'd a new one will be sent.
1335 EXPECT_CALL(*connection_, SendControlFrame(IsFrame(MAX_STREAMS_FRAME)))
1336 .WillOnce(Invoke(&ClearControlFrame));
1337 session_.OnFrameAcked(QuicFrame(max_stream_frames[0]),
1338 QuicTime::Delta::Zero(), QuicTime::Zero());
1339 EXPECT_EQ(3 * kMaxStreams,
1340 QuicSessionPeer::ietf_streamid_manager(&session_)
1341 ->advertised_max_incoming_bidirectional_streams());
1342
1343 // Open (but do not close) all available streams to consume the full window.
1344 if (alarm->IsSet()) {
1345 alarm_factory_.FireAlarm(alarm);
1346 }
1347 for (size_t i = 0; i < kMaxStreams; ++i) {
1348 QuicStreamId stream_id =
1349 GetNthClientInitiatedBidirectionalId(i + 2 * kMaxStreams);
1350 QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT"));
1351 session_.OnStreamFrame(data1);
1352 }
1353
1354 // When the remaining outstanding MAX_STREAMS frame is ACK'd no new one
1355 // will be sent because the correct limit has already been advertised.
1356 session_.OnFrameAcked(QuicFrame(max_stream_frames[1]),
1357 QuicTime::Delta::Zero(), QuicTime::Zero());
1358 }
1359
TEST_P(QuicSessionTestServer,BufferedHandshake)1360 TEST_P(QuicSessionTestServer, BufferedHandshake) {
1361 // This test is testing behavior of crypto stream flow control, but when
1362 // CRYPTO frames are used, there is no flow control for the crypto handshake.
1363 if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1364 return;
1365 }
1366 session_.set_writev_consumes_all_data(true);
1367 EXPECT_FALSE(session_.HasPendingHandshake()); // Default value.
1368
1369 // Test that blocking other streams does not change our status.
1370 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1371 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1372 EXPECT_FALSE(session_.HasPendingHandshake());
1373
1374 TestStream* stream3 = session_.CreateOutgoingBidirectionalStream();
1375 session_.MarkConnectionLevelWriteBlocked(stream3->id());
1376 EXPECT_FALSE(session_.HasPendingHandshake());
1377
1378 // Blocking (due to buffering of) the Crypto stream is detected.
1379 session_.MarkConnectionLevelWriteBlocked(
1380 QuicUtils::GetCryptoStreamId(connection_->transport_version()));
1381 EXPECT_TRUE(session_.HasPendingHandshake());
1382
1383 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1384 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1385 EXPECT_TRUE(session_.HasPendingHandshake());
1386
1387 InSequence s;
1388 // Force most streams to re-register, which is common scenario when we block
1389 // the Crypto stream, and only the crypto stream can "really" write.
1390
1391 // Due to prioritization, we *should* be asked to write the crypto stream
1392 // first.
1393 // Don't re-register the crypto stream (which signals complete writing).
1394 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
1395 EXPECT_CALL(*crypto_stream, OnCanWrite());
1396
1397 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1398 session_.SendStreamData(stream2);
1399 }));
1400 EXPECT_CALL(*stream3, OnCanWrite()).WillOnce(Invoke([this, stream3]() {
1401 session_.SendStreamData(stream3);
1402 }));
1403 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1404 session_.SendStreamData(stream4);
1405 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1406 }));
1407
1408 session_.OnCanWrite();
1409 EXPECT_TRUE(session_.WillingAndAbleToWrite());
1410 EXPECT_FALSE(session_.HasPendingHandshake()); // Crypto stream wrote.
1411 }
1412
TEST_P(QuicSessionTestServer,OnCanWriteWithClosedStream)1413 TEST_P(QuicSessionTestServer, OnCanWriteWithClosedStream) {
1414 CompleteHandshake();
1415 session_.set_writev_consumes_all_data(true);
1416 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1417 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
1418 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
1419
1420 session_.MarkConnectionLevelWriteBlocked(stream2->id());
1421 session_.MarkConnectionLevelWriteBlocked(stream6->id());
1422 session_.MarkConnectionLevelWriteBlocked(stream4->id());
1423 CloseStream(stream6->id());
1424
1425 InSequence s;
1426 EXPECT_CALL(*connection_, SendControlFrame(_))
1427 .WillRepeatedly(Invoke(&ClearControlFrame));
1428 EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
1429 session_.SendStreamData(stream2);
1430 }));
1431 EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
1432 session_.SendStreamData(stream4);
1433 }));
1434 session_.OnCanWrite();
1435 EXPECT_FALSE(session_.WillingAndAbleToWrite());
1436 }
1437
TEST_P(QuicSessionTestServer,OnCanWriteLimitsNumWritesIfFlowControlBlocked)1438 TEST_P(QuicSessionTestServer, OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
1439 // Drive congestion control manually in order to ensure that
1440 // application-limited signaling is handled correctly.
1441 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
1442 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
1443 EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
1444
1445 // Ensure connection level flow control blockage.
1446 QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(), 0);
1447 EXPECT_TRUE(session_.flow_controller()->IsBlocked());
1448 EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
1449 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1450
1451 // Mark the crypto and headers streams as write blocked, we expect them to be
1452 // allowed to write later.
1453 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1454 session_.MarkConnectionLevelWriteBlocked(
1455 QuicUtils::GetCryptoStreamId(connection_->transport_version()));
1456 }
1457
1458 // Create a data stream, and although it is write blocked we never expect it
1459 // to be allowed to write as we are connection level flow control blocked.
1460 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1461 session_.MarkConnectionLevelWriteBlocked(stream->id());
1462 EXPECT_CALL(*stream, OnCanWrite()).Times(0);
1463
1464 // The crypto and headers streams should be called even though we are
1465 // connection flow control blocked.
1466 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
1467 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
1468 EXPECT_CALL(*crypto_stream, OnCanWrite());
1469 }
1470
1471 // After the crypto and header streams perform a write, the connection will be
1472 // blocked by the flow control, hence it should become application-limited.
1473 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
1474
1475 session_.OnCanWrite();
1476 EXPECT_FALSE(session_.WillingAndAbleToWrite());
1477 }
1478
TEST_P(QuicSessionTestServer,SendGoAway)1479 TEST_P(QuicSessionTestServer, SendGoAway) {
1480 if (VersionHasIetfQuicFrames(transport_version())) {
1481 // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1482 return;
1483 }
1484 CompleteHandshake();
1485 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1486 MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1487 QuicConnectionPeer::GetWriter(session_.connection()));
1488 EXPECT_CALL(*writer, WritePacket(_, _, _, _, _, _))
1489 .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1490
1491 EXPECT_CALL(*connection_, SendControlFrame(_))
1492 .WillOnce(
1493 Invoke(connection_, &MockQuicConnection::ReallySendControlFrame));
1494 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1495 EXPECT_TRUE(session_.transport_goaway_sent());
1496
1497 const QuicStreamId kTestStreamId = 5u;
1498 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
1499 EXPECT_CALL(*connection_,
1500 OnStreamReset(kTestStreamId, QUIC_STREAM_PEER_GOING_AWAY))
1501 .Times(0);
1502 EXPECT_TRUE(session_.GetOrCreateStream(kTestStreamId));
1503 }
1504
TEST_P(QuicSessionTestServer,DoNotSendGoAwayTwice)1505 TEST_P(QuicSessionTestServer, DoNotSendGoAwayTwice) {
1506 CompleteHandshake();
1507 if (VersionHasIetfQuicFrames(transport_version())) {
1508 // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1509 return;
1510 }
1511 EXPECT_CALL(*connection_, SendControlFrame(_))
1512 .WillOnce(Invoke(&ClearControlFrame));
1513 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1514 EXPECT_TRUE(session_.transport_goaway_sent());
1515 session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
1516 }
1517
TEST_P(QuicSessionTestServer,InvalidGoAway)1518 TEST_P(QuicSessionTestServer, InvalidGoAway) {
1519 if (VersionHasIetfQuicFrames(transport_version())) {
1520 // In IETF QUIC, GOAWAY lives up in the HTTP layer.
1521 return;
1522 }
1523 QuicGoAwayFrame go_away(kInvalidControlFrameId, QUIC_PEER_GOING_AWAY,
1524 session_.next_outgoing_bidirectional_stream_id(), "");
1525 session_.OnGoAway(go_away);
1526 }
1527
1528 // Test that server session will send a connectivity probe in response to a
1529 // connectivity probe on the same path.
TEST_P(QuicSessionTestServer,ServerReplyToConnectivityProbe)1530 TEST_P(QuicSessionTestServer, ServerReplyToConnectivityProbe) {
1531 if (VersionHasIetfQuicFrames(transport_version()) ||
1532 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
1533 return;
1534 }
1535 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1536 QuicSocketAddress old_peer_address =
1537 QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort);
1538 EXPECT_EQ(old_peer_address, session_.peer_address());
1539
1540 QuicSocketAddress new_peer_address =
1541 QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 1);
1542
1543 MockPacketWriter* writer = static_cast<MockPacketWriter*>(
1544 QuicConnectionPeer::GetWriter(session_.connection()));
1545 EXPECT_CALL(*writer, WritePacket(_, _, _, new_peer_address, _, _))
1546 .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
1547
1548 EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _))
1549 .WillOnce(
1550 Invoke(connection_,
1551 &MockQuicConnection::ReallySendConnectivityProbingPacket));
1552 session_.OnPacketReceived(session_.self_address(), new_peer_address,
1553 /*is_connectivity_probe=*/true);
1554 EXPECT_EQ(old_peer_address, session_.peer_address());
1555 }
1556
TEST_P(QuicSessionTestServer,IncreasedTimeoutAfterCryptoHandshake)1557 TEST_P(QuicSessionTestServer, IncreasedTimeoutAfterCryptoHandshake) {
1558 EXPECT_EQ(kInitialIdleTimeoutSecs + 3,
1559 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
1560 CompleteHandshake();
1561 EXPECT_EQ(kMaximumIdleTimeoutSecs + 3,
1562 QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
1563 }
1564
TEST_P(QuicSessionTestServer,OnStreamFrameFinStaticStreamId)1565 TEST_P(QuicSessionTestServer, OnStreamFrameFinStaticStreamId) {
1566 if (VersionUsesHttp3(connection_->transport_version())) {
1567 // The test relies on headers stream, which no longer exists in IETF QUIC.
1568 return;
1569 }
1570 QuicStreamId headers_stream_id =
1571 QuicUtils::GetHeadersStreamId(connection_->transport_version());
1572 std::unique_ptr<TestStream> fake_headers_stream =
1573 std::make_unique<TestStream>(headers_stream_id, &session_,
1574 /*is_static*/ true, BIDIRECTIONAL);
1575 QuicSessionPeer::ActivateStream(&session_, std::move(fake_headers_stream));
1576 // Send two bytes of payload.
1577 QuicStreamFrame data1(headers_stream_id, true, 0, absl::string_view("HT"));
1578 EXPECT_CALL(*connection_,
1579 CloseConnection(
1580 QUIC_INVALID_STREAM_ID, "Attempt to close a static stream",
1581 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1582 session_.OnStreamFrame(data1);
1583 }
1584
TEST_P(QuicSessionTestServer,OnStreamFrameInvalidStreamId)1585 TEST_P(QuicSessionTestServer, OnStreamFrameInvalidStreamId) {
1586 // Send two bytes of payload.
1587 QuicStreamFrame data1(
1588 QuicUtils::GetInvalidStreamId(connection_->transport_version()), true, 0,
1589 absl::string_view("HT"));
1590 EXPECT_CALL(*connection_,
1591 CloseConnection(
1592 QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
1593 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1594 session_.OnStreamFrame(data1);
1595 }
1596
TEST_P(QuicSessionTestServer,OnRstStreamInvalidStreamId)1597 TEST_P(QuicSessionTestServer, OnRstStreamInvalidStreamId) {
1598 // Send two bytes of payload.
1599 QuicRstStreamFrame rst1(
1600 kInvalidControlFrameId,
1601 QuicUtils::GetInvalidStreamId(connection_->transport_version()),
1602 QUIC_ERROR_PROCESSING_STREAM, 0);
1603 EXPECT_CALL(*connection_,
1604 CloseConnection(
1605 QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
1606 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
1607 session_.OnRstStream(rst1);
1608 }
1609
TEST_P(QuicSessionTestServer,HandshakeUnblocksFlowControlBlockedStream)1610 TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedStream) {
1611 if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3) {
1612 // This test requires Google QUIC crypto because it assumes streams start
1613 // off unblocked.
1614 return;
1615 }
1616 // Test that if a stream is flow control blocked, then on receipt of the SHLO
1617 // containing a suitable send window offset, the stream becomes unblocked.
1618
1619 // Ensure that Writev consumes all the data it is given (simulate no socket
1620 // blocking).
1621 session_.set_writev_consumes_all_data(true);
1622 session_.GetMutableCryptoStream()->EstablishZeroRttEncryption();
1623
1624 // Create a stream, and send enough data to make it flow control blocked.
1625 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
1626 std::string body(kMinimumFlowControlSendWindow, '.');
1627 EXPECT_FALSE(stream2->IsFlowControlBlocked());
1628 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1629 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1630 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(AtLeast(1));
1631 stream2->WriteOrBufferData(body, false, nullptr);
1632 EXPECT_TRUE(stream2->IsFlowControlBlocked());
1633 EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
1634 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
1635
1636 // Now complete the crypto handshake, resulting in an increased flow control
1637 // send window.
1638 CompleteHandshake();
1639 EXPECT_TRUE(QuicSessionPeer::IsStreamWriteBlocked(&session_, stream2->id()));
1640 // Stream is now unblocked.
1641 EXPECT_FALSE(stream2->IsFlowControlBlocked());
1642 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
1643 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
1644 }
1645
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingRstOutOfOrder)1646 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstOutOfOrder) {
1647 CompleteHandshake();
1648 // Test that when we receive an out of order stream RST we correctly adjust
1649 // our connection level flow control receive window.
1650 // On close, the stream should mark as consumed all bytes between the highest
1651 // byte consumed so far and the final byte offset from the RST frame.
1652 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1653
1654 const QuicStreamOffset kByteOffset =
1655 1 + kInitialSessionFlowControlWindowForTest / 2;
1656
1657 EXPECT_CALL(*connection_, SendControlFrame(_))
1658 .Times(2)
1659 .WillRepeatedly(Invoke(&ClearControlFrame));
1660 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1661
1662 QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1663 QUIC_STREAM_CANCELLED, kByteOffset);
1664 session_.OnRstStream(rst_frame);
1665 if (VersionHasIetfQuicFrames(transport_version())) {
1666 // The test requires the stream to be fully closed in both directions. For
1667 // IETF QUIC, the RST_STREAM only closes one side.
1668 QuicStopSendingFrame frame(kInvalidControlFrameId, stream->id(),
1669 QUIC_STREAM_CANCELLED);
1670 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
1671 session_.OnStopSendingFrame(frame);
1672 }
1673 EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed());
1674 }
1675
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingFinAndLocalReset)1676 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAndLocalReset) {
1677 CompleteHandshake();
1678 // Test the situation where we receive a FIN on a stream, and before we fully
1679 // consume all the data from the sequencer buffer we locally RST the stream.
1680 // The bytes between highest consumed byte, and the final byte offset that we
1681 // determined when the FIN arrived, should be marked as consumed at the
1682 // connection level flow controller when the stream is reset.
1683 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1684
1685 const QuicStreamOffset kByteOffset =
1686 kInitialSessionFlowControlWindowForTest / 2 - 1;
1687 QuicStreamFrame frame(stream->id(), true, kByteOffset, ".");
1688 session_.OnStreamFrame(frame);
1689 EXPECT_TRUE(connection_->connected());
1690
1691 EXPECT_EQ(0u, session_.flow_controller()->bytes_consumed());
1692 EXPECT_EQ(kByteOffset + frame.data_length,
1693 stream->highest_received_byte_offset());
1694
1695 // Reset stream locally.
1696 EXPECT_CALL(*connection_, SendControlFrame(_));
1697 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1698 stream->Reset(QUIC_STREAM_CANCELLED);
1699 EXPECT_EQ(kByteOffset + frame.data_length,
1700 session_.flow_controller()->bytes_consumed());
1701 }
1702
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingFinAfterRst)1703 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAfterRst) {
1704 CompleteHandshake();
1705 // Test that when we RST the stream (and tear down stream state), and then
1706 // receive a FIN from the peer, we correctly adjust our connection level flow
1707 // control receive window.
1708
1709 // Connection starts with some non-zero highest received byte offset,
1710 // due to other active streams.
1711 const uint64_t kInitialConnectionBytesConsumed = 567;
1712 const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
1713 EXPECT_LT(kInitialConnectionBytesConsumed,
1714 kInitialConnectionHighestReceivedOffset);
1715 session_.flow_controller()->UpdateHighestReceivedOffset(
1716 kInitialConnectionHighestReceivedOffset);
1717 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
1718
1719 // Reset our stream: this results in the stream being closed locally.
1720 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1721 EXPECT_CALL(*connection_, SendControlFrame(_));
1722 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1723 stream->Reset(QUIC_STREAM_CANCELLED);
1724
1725 // Now receive a response from the peer with a FIN. We should handle this by
1726 // adjusting the connection level flow control receive window to take into
1727 // account the total number of bytes sent by the peer.
1728 const QuicStreamOffset kByteOffset = 5678;
1729 std::string body = "hello";
1730 QuicStreamFrame frame(stream->id(), true, kByteOffset,
1731 absl::string_view(body));
1732 session_.OnStreamFrame(frame);
1733
1734 QuicStreamOffset total_stream_bytes_sent_by_peer =
1735 kByteOffset + body.length();
1736 EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer,
1737 session_.flow_controller()->bytes_consumed());
1738 EXPECT_EQ(
1739 kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer,
1740 session_.flow_controller()->highest_received_byte_offset());
1741 }
1742
TEST_P(QuicSessionTestServer,ConnectionFlowControlAccountingRstAfterRst)1743 TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstAfterRst) {
1744 CompleteHandshake();
1745 // Test that when we RST the stream (and tear down stream state), and then
1746 // receive a RST from the peer, we correctly adjust our connection level flow
1747 // control receive window.
1748
1749 // Connection starts with some non-zero highest received byte offset,
1750 // due to other active streams.
1751 const uint64_t kInitialConnectionBytesConsumed = 567;
1752 const uint64_t kInitialConnectionHighestReceivedOffset = 1234;
1753 EXPECT_LT(kInitialConnectionBytesConsumed,
1754 kInitialConnectionHighestReceivedOffset);
1755 session_.flow_controller()->UpdateHighestReceivedOffset(
1756 kInitialConnectionHighestReceivedOffset);
1757 session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed);
1758
1759 // Reset our stream: this results in the stream being closed locally.
1760 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1761 EXPECT_CALL(*connection_, SendControlFrame(_));
1762 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1763 stream->Reset(QUIC_STREAM_CANCELLED);
1764 EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream));
1765
1766 // Now receive a RST from the peer. We should handle this by adjusting the
1767 // connection level flow control receive window to take into account the total
1768 // number of bytes sent by the peer.
1769 const QuicStreamOffset kByteOffset = 5678;
1770 QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1771 QUIC_STREAM_CANCELLED, kByteOffset);
1772 session_.OnRstStream(rst_frame);
1773
1774 EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset,
1775 session_.flow_controller()->bytes_consumed());
1776 EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset,
1777 session_.flow_controller()->highest_received_byte_offset());
1778 }
1779
TEST_P(QuicSessionTestServer,InvalidStreamFlowControlWindowInHandshake)1780 TEST_P(QuicSessionTestServer, InvalidStreamFlowControlWindowInHandshake) {
1781 // Test that receipt of an invalid (< default) stream flow control window from
1782 // the peer results in the connection being torn down.
1783 const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
1784 QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(),
1785 kInvalidWindow);
1786
1787 if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) {
1788 EXPECT_CALL(*connection_,
1789 CloseConnection(QUIC_FLOW_CONTROL_INVALID_WINDOW, _, _));
1790 } else {
1791 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
1792 }
1793 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1794 session_.OnConfigNegotiated();
1795 }
1796
1797 // Test negotiation of custom server initial flow control window.
TEST_P(QuicSessionTestServer,CustomFlowControlWindow)1798 TEST_P(QuicSessionTestServer, CustomFlowControlWindow) {
1799 QuicTagVector copt;
1800 copt.push_back(kIFW7);
1801 QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
1802
1803 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1804 session_.OnConfigNegotiated();
1805 EXPECT_EQ(192 * 1024u, QuicFlowControllerPeer::ReceiveWindowSize(
1806 session_.flow_controller()));
1807 }
1808
TEST_P(QuicSessionTestServer,FlowControlWithInvalidFinalOffset)1809 TEST_P(QuicSessionTestServer, FlowControlWithInvalidFinalOffset) {
1810 CompleteHandshake();
1811 // Test that if we receive a stream RST with a highest byte offset that
1812 // violates flow control, that we close the connection.
1813 const uint64_t kLargeOffset = kInitialSessionFlowControlWindowForTest + 1;
1814 EXPECT_CALL(*connection_,
1815 CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _))
1816 .Times(2);
1817
1818 // Check that stream frame + FIN results in connection close.
1819 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1820 EXPECT_CALL(*connection_, SendControlFrame(_));
1821 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
1822 stream->Reset(QUIC_STREAM_CANCELLED);
1823 QuicStreamFrame frame(stream->id(), true, kLargeOffset, absl::string_view());
1824 session_.OnStreamFrame(frame);
1825
1826 // Check that RST results in connection close.
1827 QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
1828 QUIC_STREAM_CANCELLED, kLargeOffset);
1829 session_.OnRstStream(rst_frame);
1830 }
1831
TEST_P(QuicSessionTestServer,TooManyUnfinishedStreamsCauseServerRejectStream)1832 TEST_P(QuicSessionTestServer, TooManyUnfinishedStreamsCauseServerRejectStream) {
1833 CompleteHandshake();
1834 // If a buggy/malicious peer creates too many streams that are not ended
1835 // with a FIN or RST then we send an RST to refuse streams. For IETF QUIC the
1836 // connection is closed.
1837 const QuicStreamId kMaxStreams = 5;
1838 if (VersionHasIetfQuicFrames(transport_version())) {
1839 QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_,
1840 kMaxStreams);
1841 } else {
1842 QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, kMaxStreams);
1843 }
1844 const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
1845 const QuicStreamId kFinalStreamId =
1846 GetNthClientInitiatedBidirectionalId(kMaxStreams);
1847 // Create kMaxStreams data streams, and close them all without receiving a
1848 // FIN or a RST_STREAM from the client.
1849 for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId;
1850 i += QuicUtils::StreamIdDelta(connection_->transport_version())) {
1851 QuicStreamFrame data1(i, false, 0, absl::string_view("HT"));
1852 session_.OnStreamFrame(data1);
1853 CloseStream(i);
1854 }
1855
1856 if (VersionHasIetfQuicFrames(transport_version())) {
1857 EXPECT_CALL(
1858 *connection_,
1859 CloseConnection(QUIC_INVALID_STREAM_ID,
1860 "Stream id 20 would exceed stream count limit 5", _));
1861 } else {
1862 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
1863 EXPECT_CALL(*connection_,
1864 OnStreamReset(kFinalStreamId, QUIC_REFUSED_STREAM))
1865 .Times(1);
1866 }
1867 // Create one more data streams to exceed limit of open stream.
1868 QuicStreamFrame data1(kFinalStreamId, false, 0, absl::string_view("HT"));
1869 session_.OnStreamFrame(data1);
1870 }
1871
TEST_P(QuicSessionTestServer,DrainingStreamsDoNotCountAsOpenedOutgoing)1872 TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpenedOutgoing) {
1873 // Verify that a draining stream (which has received a FIN but not consumed
1874 // it) does not count against the open quota (because it is closed from the
1875 // protocol point of view).
1876 CompleteHandshake();
1877 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
1878 QuicStreamId stream_id = stream->id();
1879 QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT"));
1880 session_.OnStreamFrame(data1);
1881 if (!VersionHasIetfQuicFrames(transport_version())) {
1882 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
1883 }
1884 session_.StreamDraining(stream_id, /*unidirectional=*/false);
1885 }
1886
TEST_P(QuicSessionTestServer,NoPendingStreams)1887 TEST_P(QuicSessionTestServer, NoPendingStreams) {
1888 session_.set_uses_pending_streams(false);
1889
1890 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1891 transport_version(), Perspective::IS_CLIENT);
1892 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1893 session_.OnStreamFrame(data1);
1894 EXPECT_EQ(1, session_.num_incoming_streams_created());
1895
1896 QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1897 session_.OnStreamFrame(data2);
1898 EXPECT_EQ(1, session_.num_incoming_streams_created());
1899 }
1900
TEST_P(QuicSessionTestServer,PendingStreams)1901 TEST_P(QuicSessionTestServer, PendingStreams) {
1902 if (!VersionUsesHttp3(transport_version())) {
1903 return;
1904 }
1905 CompleteHandshake();
1906 session_.set_uses_pending_streams(true);
1907
1908 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1909 transport_version(), Perspective::IS_CLIENT);
1910 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1911 session_.OnStreamFrame(data1);
1912 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1913 EXPECT_EQ(0, session_.num_incoming_streams_created());
1914
1915 QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1916 session_.OnStreamFrame(data2);
1917 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1918 EXPECT_EQ(1, session_.num_incoming_streams_created());
1919 }
1920
TEST_P(QuicSessionTestServer,BufferAllIncomingStreams)1921 TEST_P(QuicSessionTestServer, BufferAllIncomingStreams) {
1922 if (!VersionUsesHttp3(transport_version())) {
1923 return;
1924 }
1925 session_.set_uses_pending_streams(true);
1926
1927 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1928 transport_version(), Perspective::IS_CLIENT);
1929 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1930 session_.OnStreamFrame(data1);
1931 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1932 EXPECT_EQ(0, session_.num_incoming_streams_created());
1933 // Read unidirectional stream is still buffered when the first byte arrives.
1934 QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1935 session_.OnStreamFrame(data2);
1936 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1937 EXPECT_EQ(0, session_.num_incoming_streams_created());
1938
1939 // Bidirectional stream is buffered.
1940 QuicStreamId bidirectional_stream_id =
1941 QuicUtils::GetFirstBidirectionalStreamId(transport_version(),
1942 Perspective::IS_CLIENT);
1943 QuicStreamFrame data3(bidirectional_stream_id, false, 0,
1944 absl::string_view("HT"));
1945 session_.OnStreamFrame(data3);
1946 EXPECT_TRUE(
1947 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
1948 EXPECT_EQ(0, session_.num_incoming_streams_created());
1949
1950 connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
1951 session_.ProcessAllPendingStreams();
1952 // Both bidirectional and read-unidirectional streams are unbuffered.
1953 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1954 EXPECT_FALSE(
1955 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
1956 EXPECT_EQ(2, session_.num_incoming_streams_created());
1957 EXPECT_EQ(1, QuicSessionPeer::GetStream(&session_, stream_id)
1958 ->pending_duration()
1959 .ToMilliseconds());
1960 EXPECT_EQ(1, QuicSessionPeer::GetStream(&session_, bidirectional_stream_id)
1961 ->pending_duration()
1962 .ToMilliseconds());
1963 EXPECT_EQ(2, session_.connection()->GetStats().num_total_pending_streams);
1964 }
1965
TEST_P(QuicSessionTestServer,RstPendingStreams)1966 TEST_P(QuicSessionTestServer, RstPendingStreams) {
1967 if (!VersionUsesHttp3(transport_version())) {
1968 return;
1969 }
1970 session_.set_uses_pending_streams(true);
1971
1972 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
1973 transport_version(), Perspective::IS_CLIENT);
1974 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
1975 session_.OnStreamFrame(data1);
1976 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1977 EXPECT_EQ(0, session_.num_incoming_streams_created());
1978 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
1979
1980 QuicRstStreamFrame rst1(kInvalidControlFrameId, stream_id,
1981 QUIC_ERROR_PROCESSING_STREAM, 12);
1982 session_.OnRstStream(rst1);
1983 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1984 EXPECT_EQ(0, session_.num_incoming_streams_created());
1985 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
1986
1987 QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT"));
1988 session_.OnStreamFrame(data2);
1989 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
1990 EXPECT_EQ(0, session_.num_incoming_streams_created());
1991 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
1992
1993 session_.ProcessAllPendingStreams();
1994 // Bidirectional stream is buffered.
1995 QuicStreamId bidirectional_stream_id =
1996 QuicUtils::GetFirstBidirectionalStreamId(transport_version(),
1997 Perspective::IS_CLIENT);
1998 QuicStreamFrame data3(bidirectional_stream_id, false, 0,
1999 absl::string_view("HT"));
2000 session_.OnStreamFrame(data3);
2001 EXPECT_TRUE(
2002 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
2003 EXPECT_EQ(0, session_.num_incoming_streams_created());
2004
2005 // Bidirectional pending stream is removed after RST_STREAM is received.
2006 QuicRstStreamFrame rst2(kInvalidControlFrameId, bidirectional_stream_id,
2007 QUIC_ERROR_PROCESSING_STREAM, 12);
2008 session_.OnRstStream(rst2);
2009 EXPECT_FALSE(
2010 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
2011 EXPECT_EQ(0, session_.num_incoming_streams_created());
2012 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2013 }
2014
TEST_P(QuicSessionTestServer,OnFinPendingStreamsReadUnidirectional)2015 TEST_P(QuicSessionTestServer, OnFinPendingStreamsReadUnidirectional) {
2016 if (!VersionUsesHttp3(transport_version())) {
2017 return;
2018 }
2019 CompleteHandshake();
2020 session_.set_uses_pending_streams(true);
2021
2022 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
2023 transport_version(), Perspective::IS_CLIENT);
2024 QuicStreamFrame data(stream_id, true, 0, "");
2025 session_.OnStreamFrame(data);
2026
2027 // The pending stream will be immediately converted to a normal unidirectional
2028 // stream, but because its FIN has been received, it should be closed
2029 // immediately.
2030 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2031 EXPECT_EQ(0, session_.num_incoming_streams_created());
2032 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2033 EXPECT_EQ(nullptr, QuicSessionPeer::GetStream(&session_, stream_id));
2034 }
2035
TEST_P(QuicSessionTestServer,OnFinPendingStreamsBidirectional)2036 TEST_P(QuicSessionTestServer, OnFinPendingStreamsBidirectional) {
2037 if (!VersionUsesHttp3(transport_version())) {
2038 return;
2039 }
2040 session_.set_uses_pending_streams(true);
2041 // Bidirectional pending stream remains after Fin is received.
2042 // Bidirectional stream is buffered.
2043 QuicStreamId bidirectional_stream_id =
2044 QuicUtils::GetFirstBidirectionalStreamId(transport_version(),
2045 Perspective::IS_CLIENT);
2046 QuicStreamFrame data2(bidirectional_stream_id, true, 0,
2047 absl::string_view("HT"));
2048 session_.OnStreamFrame(data2);
2049 EXPECT_TRUE(
2050 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
2051 EXPECT_EQ(0, session_.num_incoming_streams_created());
2052
2053 session_.ProcessAllPendingStreams();
2054 EXPECT_FALSE(
2055 QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id));
2056 EXPECT_EQ(1, session_.num_incoming_streams_created());
2057 QuicStream* bidirectional_stream =
2058 QuicSessionPeer::GetStream(&session_, bidirectional_stream_id);
2059 EXPECT_TRUE(bidirectional_stream->fin_received());
2060 }
2061
TEST_P(QuicSessionTestServer,UnidirectionalPendingStreamOnWindowUpdate)2062 TEST_P(QuicSessionTestServer, UnidirectionalPendingStreamOnWindowUpdate) {
2063 if (!VersionUsesHttp3(transport_version())) {
2064 return;
2065 }
2066
2067 session_.set_uses_pending_streams(true);
2068 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
2069 transport_version(), Perspective::IS_CLIENT);
2070 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
2071 session_.OnStreamFrame(data1);
2072 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2073 EXPECT_EQ(0, session_.num_incoming_streams_created());
2074 QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id,
2075 0);
2076 EXPECT_CALL(
2077 *connection_,
2078 CloseConnection(
2079 QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM,
2080 "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream.", _));
2081 session_.OnWindowUpdateFrame(window_update_frame);
2082 }
2083
TEST_P(QuicSessionTestServer,BidirectionalPendingStreamOnWindowUpdate)2084 TEST_P(QuicSessionTestServer, BidirectionalPendingStreamOnWindowUpdate) {
2085 if (!VersionUsesHttp3(transport_version())) {
2086 return;
2087 }
2088
2089 session_.set_uses_pending_streams(true);
2090 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
2091 transport_version(), Perspective::IS_CLIENT);
2092 QuicStreamFrame data(stream_id, true, 10, absl::string_view("HT"));
2093 session_.OnStreamFrame(data);
2094 QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id,
2095 kDefaultFlowControlSendWindow * 2);
2096 session_.OnWindowUpdateFrame(window_update_frame);
2097 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2098 EXPECT_EQ(0, session_.num_incoming_streams_created());
2099
2100 session_.ProcessAllPendingStreams();
2101 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2102 EXPECT_EQ(1, session_.num_incoming_streams_created());
2103 QuicStream* bidirectional_stream =
2104 QuicSessionPeer::GetStream(&session_, stream_id);
2105 QuicByteCount send_window =
2106 QuicStreamPeer::SendWindowSize(bidirectional_stream);
2107 EXPECT_EQ(send_window, kDefaultFlowControlSendWindow * 2);
2108 }
2109
TEST_P(QuicSessionTestServer,UnidirectionalPendingStreamOnStopSending)2110 TEST_P(QuicSessionTestServer, UnidirectionalPendingStreamOnStopSending) {
2111 if (!VersionUsesHttp3(transport_version())) {
2112 return;
2113 }
2114
2115 session_.set_uses_pending_streams(true);
2116 QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
2117 transport_version(), Perspective::IS_CLIENT);
2118 QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT"));
2119 session_.OnStreamFrame(data1);
2120 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2121 EXPECT_EQ(0, session_.num_incoming_streams_created());
2122 QuicStopSendingFrame stop_sending_frame(kInvalidControlFrameId, stream_id,
2123 QUIC_STREAM_CANCELLED);
2124 EXPECT_CALL(
2125 *connection_,
2126 CloseConnection(QUIC_INVALID_STREAM_ID,
2127 "Received STOP_SENDING for a read-only stream", _));
2128 session_.OnStopSendingFrame(stop_sending_frame);
2129 }
2130
TEST_P(QuicSessionTestServer,BidirectionalPendingStreamOnStopSending)2131 TEST_P(QuicSessionTestServer, BidirectionalPendingStreamOnStopSending) {
2132 if (!VersionUsesHttp3(transport_version())) {
2133 return;
2134 }
2135
2136 session_.set_uses_pending_streams(true);
2137 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
2138 transport_version(), Perspective::IS_CLIENT);
2139 QuicStreamFrame data(stream_id, true, 0, absl::string_view("HT"));
2140 session_.OnStreamFrame(data);
2141 QuicStopSendingFrame stop_sending_frame(kInvalidControlFrameId, stream_id,
2142 QUIC_STREAM_CANCELLED);
2143 session_.OnStopSendingFrame(stop_sending_frame);
2144 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2145 EXPECT_EQ(0, session_.num_incoming_streams_created());
2146
2147 EXPECT_CALL(*connection_, OnStreamReset(stream_id, _));
2148 session_.ProcessAllPendingStreams();
2149 EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id));
2150 EXPECT_EQ(1, session_.num_incoming_streams_created());
2151 QuicStream* bidirectional_stream =
2152 QuicSessionPeer::GetStream(&session_, stream_id);
2153 EXPECT_TRUE(bidirectional_stream->write_side_closed());
2154 }
2155
TEST_P(QuicSessionTestServer,DrainingStreamsDoNotCountAsOpened)2156 TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpened) {
2157 // Verify that a draining stream (which has received a FIN but not consumed
2158 // it) does not count against the open quota (because it is closed from the
2159 // protocol point of view).
2160 CompleteHandshake();
2161 if (VersionHasIetfQuicFrames(transport_version())) {
2162 // On IETF QUIC, we will expect to see a MAX_STREAMS go out when there are
2163 // not enough streams to create the next one.
2164 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
2165 } else {
2166 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
2167 }
2168 EXPECT_CALL(*connection_, OnStreamReset(_, QUIC_REFUSED_STREAM)).Times(0);
2169 const QuicStreamId kMaxStreams = 5;
2170 if (VersionHasIetfQuicFrames(transport_version())) {
2171 QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_,
2172 kMaxStreams);
2173 } else {
2174 QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, kMaxStreams);
2175 }
2176
2177 // Create kMaxStreams + 1 data streams, and mark them draining.
2178 const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
2179 const QuicStreamId kFinalStreamId =
2180 GetNthClientInitiatedBidirectionalId(2 * kMaxStreams + 1);
2181 for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId;
2182 i += QuicUtils::StreamIdDelta(connection_->transport_version())) {
2183 QuicStreamFrame data1(i, true, 0, absl::string_view("HT"));
2184 session_.OnStreamFrame(data1);
2185 EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2186 session_.StreamDraining(i, /*unidirectional=*/false);
2187 EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_));
2188 QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_);
2189 if (alarm->IsSet()) {
2190 alarm_factory_.FireAlarm(alarm);
2191 }
2192 }
2193 }
2194
2195 class QuicSessionTestClient : public QuicSessionTestBase {
2196 protected:
QuicSessionTestClient()2197 QuicSessionTestClient()
2198 : QuicSessionTestBase(Perspective::IS_CLIENT,
2199 /*configure_session=*/true) {}
2200 };
2201
2202 INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestClient,
2203 ::testing::ValuesIn(AllSupportedVersions()),
2204 ::testing::PrintToStringParamName());
2205
TEST_P(QuicSessionTestClient,AvailableBidirectionalStreamsClient)2206 TEST_P(QuicSessionTestClient, AvailableBidirectionalStreamsClient) {
2207 ASSERT_TRUE(session_.GetOrCreateStream(
2208 GetNthServerInitiatedBidirectionalId(2)) != nullptr);
2209 // Smaller bidirectional streams should be available.
2210 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2211 &session_, GetNthServerInitiatedBidirectionalId(0)));
2212 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2213 &session_, GetNthServerInitiatedBidirectionalId(1)));
2214 ASSERT_TRUE(session_.GetOrCreateStream(
2215 GetNthServerInitiatedBidirectionalId(0)) != nullptr);
2216 ASSERT_TRUE(session_.GetOrCreateStream(
2217 GetNthServerInitiatedBidirectionalId(1)) != nullptr);
2218 // And 5 should be not available.
2219 EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(
2220 &session_, GetNthClientInitiatedBidirectionalId(1)));
2221 }
2222
2223 // Regression test for
2224 // https://bugs.chromium.org/p/chromium/issues/detail?id=1514016
TEST_P(QuicSessionTestClient,DonotSendRetireCIDFrameWhenConnectionClosed)2225 TEST_P(QuicSessionTestClient, DonotSendRetireCIDFrameWhenConnectionClosed) {
2226 if (!VersionHasIetfQuicFrames(transport_version())) {
2227 return;
2228 }
2229 connection_->ReallyCloseConnection(QUIC_NO_ERROR, "closing",
2230 ConnectionCloseBehavior::SILENT_CLOSE);
2231 EXPECT_FALSE(connection_->connected());
2232 if (!GetQuicReloadableFlag(
2233 quic_no_write_control_frame_upon_connection_close2)) {
2234 EXPECT_QUIC_BUG(session_.SendRetireConnectionId(20),
2235 "Try to write control frame");
2236 } else {
2237 session_.SendRetireConnectionId(20);
2238 }
2239 }
2240
TEST_P(QuicSessionTestClient,NewStreamCreationResumesMultiPortProbing)2241 TEST_P(QuicSessionTestClient, NewStreamCreationResumesMultiPortProbing) {
2242 if (!VersionHasIetfQuicFrames(transport_version())) {
2243 return;
2244 }
2245 session_.config()->SetClientConnectionOptions({kMPQC});
2246 session_.Initialize();
2247 connection_->CreateConnectionIdManager();
2248 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2249 connection_->OnHandshakeComplete();
2250 session_.OnConfigNegotiated();
2251
2252 EXPECT_CALL(*connection_, MaybeProbeMultiPortPath());
2253 session_.CreateOutgoingBidirectionalStream();
2254 }
2255
TEST_P(QuicSessionTestClient,InvalidSessionFlowControlWindowInHandshake)2256 TEST_P(QuicSessionTestClient, InvalidSessionFlowControlWindowInHandshake) {
2257 // Test that receipt of an invalid (< default for gQUIC, < current for TLS)
2258 // session flow control window from the peer results in the connection being
2259 // torn down.
2260 const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
2261 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(),
2262 kInvalidWindow);
2263 EXPECT_CALL(
2264 *connection_,
2265 CloseConnection(connection_->version().AllowsLowFlowControlLimits()
2266 ? QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED
2267 : QUIC_FLOW_CONTROL_INVALID_WINDOW,
2268 _, _));
2269 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2270 session_.OnConfigNegotiated();
2271 }
2272
TEST_P(QuicSessionTestClient,InvalidBidiStreamLimitInHandshake)2273 TEST_P(QuicSessionTestClient, InvalidBidiStreamLimitInHandshake) {
2274 // IETF QUIC only feature.
2275 if (!VersionHasIetfQuicFrames(transport_version())) {
2276 return;
2277 }
2278 QuicConfigPeer::SetReceivedMaxBidirectionalStreams(
2279 session_.config(), kDefaultMaxStreamsPerConnection - 1);
2280 EXPECT_CALL(*connection_,
2281 CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _));
2282 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2283 session_.OnConfigNegotiated();
2284 }
2285
TEST_P(QuicSessionTestClient,InvalidUniStreamLimitInHandshake)2286 TEST_P(QuicSessionTestClient, InvalidUniStreamLimitInHandshake) {
2287 // IETF QUIC only feature.
2288 if (!VersionHasIetfQuicFrames(transport_version())) {
2289 return;
2290 }
2291 QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(
2292 session_.config(), kDefaultMaxStreamsPerConnection - 1);
2293 EXPECT_CALL(*connection_,
2294 CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _));
2295 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2296 session_.OnConfigNegotiated();
2297 }
2298
TEST_P(QuicSessionTestClient,InvalidStreamFlowControlWindowInHandshake)2299 TEST_P(QuicSessionTestClient, InvalidStreamFlowControlWindowInHandshake) {
2300 // IETF QUIC only feature.
2301 if (!VersionHasIetfQuicFrames(transport_version())) {
2302 return;
2303 }
2304 session_.CreateOutgoingBidirectionalStream();
2305 session_.CreateOutgoingBidirectionalStream();
2306 QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
2307 session_.config(), kMinimumFlowControlSendWindow - 1);
2308
2309 EXPECT_CALL(*connection_, CloseConnection(_, _, _))
2310 .WillOnce(
2311 Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
2312 EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _));
2313
2314 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2315 session_.OnConfigNegotiated();
2316 }
2317
TEST_P(QuicSessionTestClient,OnMaxStreamFrame)2318 TEST_P(QuicSessionTestClient, OnMaxStreamFrame) {
2319 if (!VersionUsesHttp3(transport_version())) {
2320 return;
2321 }
2322 QuicMaxStreamsFrame frame;
2323 frame.unidirectional = false;
2324 frame.stream_count = 120;
2325 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
2326 session_.OnMaxStreamsFrame(frame);
2327
2328 QuicMaxStreamsFrame frame2;
2329 frame2.unidirectional = false;
2330 frame2.stream_count = 110;
2331 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0);
2332 session_.OnMaxStreamsFrame(frame2);
2333 }
2334
TEST_P(QuicSessionTestClient,AvailableUnidirectionalStreamsClient)2335 TEST_P(QuicSessionTestClient, AvailableUnidirectionalStreamsClient) {
2336 ASSERT_TRUE(session_.GetOrCreateStream(
2337 GetNthServerInitiatedUnidirectionalId(2)) != nullptr);
2338 // Smaller unidirectional streams should be available.
2339 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2340 &session_, GetNthServerInitiatedUnidirectionalId(0)));
2341 EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
2342 &session_, GetNthServerInitiatedUnidirectionalId(1)));
2343 ASSERT_TRUE(session_.GetOrCreateStream(
2344 GetNthServerInitiatedUnidirectionalId(0)) != nullptr);
2345 ASSERT_TRUE(session_.GetOrCreateStream(
2346 GetNthServerInitiatedUnidirectionalId(1)) != nullptr);
2347 // And 5 should be not available.
2348 EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(
2349 &session_, GetNthClientInitiatedUnidirectionalId(1)));
2350 }
2351
TEST_P(QuicSessionTestClient,RecordFinAfterReadSideClosed)2352 TEST_P(QuicSessionTestClient, RecordFinAfterReadSideClosed) {
2353 CompleteHandshake();
2354 // Verify that an incoming FIN is recorded in a stream object even if the read
2355 // side has been closed. This prevents an entry from being made in
2356 // locally_closed_streams_highest_offset_ (which will never be deleted).
2357 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2358 QuicStreamId stream_id = stream->id();
2359
2360 // Close the read side manually.
2361 QuicStreamPeer::CloseReadSide(stream);
2362
2363 // Receive a stream data frame with FIN.
2364 QuicStreamFrame frame(stream_id, true, 0, absl::string_view());
2365 session_.OnStreamFrame(frame);
2366 EXPECT_TRUE(stream->fin_received());
2367
2368 // Reset stream locally.
2369 EXPECT_CALL(*connection_, SendControlFrame(_));
2370 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
2371 stream->Reset(QUIC_STREAM_CANCELLED);
2372 EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream));
2373
2374 EXPECT_TRUE(connection_->connected());
2375 EXPECT_TRUE(QuicSessionPeer::IsStreamClosed(&session_, stream_id));
2376 EXPECT_FALSE(QuicSessionPeer::IsStreamCreated(&session_, stream_id));
2377
2378 // The stream is not waiting for the arrival of the peer's final offset as it
2379 // was received with the FIN earlier.
2380 EXPECT_EQ(
2381 0u,
2382 QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(&session_).size());
2383 }
2384
TEST_P(QuicSessionTestClient,IncomingStreamWithClientInitiatedStreamId)2385 TEST_P(QuicSessionTestClient, IncomingStreamWithClientInitiatedStreamId) {
2386 const QuicErrorCode expected_error =
2387 VersionHasIetfQuicFrames(transport_version())
2388 ? QUIC_HTTP_STREAM_WRONG_DIRECTION
2389 : QUIC_INVALID_STREAM_ID;
2390 EXPECT_CALL(
2391 *connection_,
2392 CloseConnection(expected_error, "Data for nonexistent stream",
2393 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
2394
2395 QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(1),
2396 /* fin = */ false, /* offset = */ 0,
2397 absl::string_view("foo"));
2398 session_.OnStreamFrame(frame);
2399 }
2400
TEST_P(QuicSessionTestClient,MinAckDelaySetOnTheClientQuicConfig)2401 TEST_P(QuicSessionTestClient, MinAckDelaySetOnTheClientQuicConfig) {
2402 if (!session_.version().HasIetfQuicFrames()) {
2403 return;
2404 }
2405 session_.config()->SetClientConnectionOptions({kAFFE});
2406 session_.Initialize();
2407 ASSERT_EQ(session_.config()->GetMinAckDelayToSendMs(),
2408 kDefaultMinAckDelayTimeMs);
2409 ASSERT_TRUE(session_.connection()->can_receive_ack_frequency_frame());
2410 }
2411
TEST_P(QuicSessionTestClient,FailedToCreateStreamIfTooCloseToIdleTimeout)2412 TEST_P(QuicSessionTestClient, FailedToCreateStreamIfTooCloseToIdleTimeout) {
2413 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2414 EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
2415 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(connection_);
2416 ASSERT_TRUE(deadline.IsInitialized());
2417 QuicTime::Delta timeout = deadline - helper_.GetClock()->ApproximateNow();
2418 // Advance time to very close idle timeout.
2419 connection_->AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
2420 // Verify creation of new stream gets pushed back and connectivity probing
2421 // packet gets sent.
2422 EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _)).Times(1);
2423 EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream());
2424
2425 // New packet gets received, idle deadline gets extended.
2426 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false));
2427 QuicConnectionPeer::GetIdleNetworkDetector(connection_)
2428 .OnPacketReceived(helper_.GetClock()->ApproximateNow());
2429 session_.OnPacketDecrypted(ENCRYPTION_FORWARD_SECURE);
2430
2431 EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream());
2432 }
2433
TEST_P(QuicSessionTestServer,ZombieStreams)2434 TEST_P(QuicSessionTestServer, ZombieStreams) {
2435 CompleteHandshake();
2436 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2437 QuicStreamPeer::SetStreamBytesWritten(3, stream2);
2438 EXPECT_TRUE(stream2->IsWaitingForAcks());
2439
2440 CloseStream(stream2->id());
2441 ASSERT_EQ(1u, session_.closed_streams()->size());
2442 EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2443 session_.MaybeCloseZombieStream(stream2->id());
2444 EXPECT_EQ(1u, session_.closed_streams()->size());
2445 EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2446 }
2447
TEST_P(QuicSessionTestServer,RstStreamReceivedAfterRstStreamSent)2448 TEST_P(QuicSessionTestServer, RstStreamReceivedAfterRstStreamSent) {
2449 CompleteHandshake();
2450 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2451 QuicStreamPeer::SetStreamBytesWritten(3, stream2);
2452 EXPECT_TRUE(stream2->IsWaitingForAcks());
2453
2454 EXPECT_CALL(*connection_, SendControlFrame(_));
2455 EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _));
2456 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0);
2457 stream2->Reset(quic::QUIC_STREAM_CANCELLED);
2458
2459 QuicRstStreamFrame rst1(kInvalidControlFrameId, stream2->id(),
2460 QUIC_ERROR_PROCESSING_STREAM, 0);
2461 if (!VersionHasIetfQuicFrames(transport_version())) {
2462 EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1);
2463 }
2464 session_.OnRstStream(rst1);
2465 }
2466
2467 // Regression test of b/71548958.
TEST_P(QuicSessionTestServer,TestZombieStreams)2468 TEST_P(QuicSessionTestServer, TestZombieStreams) {
2469 CompleteHandshake();
2470 session_.set_writev_consumes_all_data(true);
2471
2472 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2473 std::string body(100, '.');
2474 stream2->WriteOrBufferData(body, false, nullptr);
2475 EXPECT_TRUE(stream2->IsWaitingForAcks());
2476 EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream2).size());
2477
2478 QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream2->id(),
2479 QUIC_STREAM_CANCELLED, 1234);
2480 // Just for the RST_STREAM
2481 EXPECT_CALL(*connection_, SendControlFrame(_))
2482 .WillOnce(Invoke(&ClearControlFrame));
2483 if (VersionHasIetfQuicFrames(transport_version())) {
2484 EXPECT_CALL(*connection_,
2485 OnStreamReset(stream2->id(), QUIC_STREAM_CANCELLED));
2486 } else {
2487 EXPECT_CALL(*connection_,
2488 OnStreamReset(stream2->id(), QUIC_RST_ACKNOWLEDGEMENT));
2489 }
2490 stream2->OnStreamReset(rst_frame);
2491
2492 if (VersionHasIetfQuicFrames(transport_version())) {
2493 // The test requires the stream to be fully closed in both directions. For
2494 // IETF QUIC, the RST_STREAM only closes one side.
2495 QuicStopSendingFrame frame(kInvalidControlFrameId, stream2->id(),
2496 QUIC_STREAM_CANCELLED);
2497 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2498 session_.OnStopSendingFrame(frame);
2499 }
2500 ASSERT_EQ(1u, session_.closed_streams()->size());
2501 EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id());
2502
2503 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2504 if (VersionHasIetfQuicFrames(transport_version())) {
2505 // Once for the RST_STREAM, once for the STOP_SENDING
2506 EXPECT_CALL(*connection_, SendControlFrame(_))
2507 .Times(2)
2508 .WillRepeatedly(Invoke(&ClearControlFrame));
2509 } else {
2510 // Just for the RST_STREAM
2511 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
2512 }
2513 EXPECT_CALL(*connection_,
2514 OnStreamReset(stream4->id(), QUIC_STREAM_CANCELLED));
2515 stream4->WriteOrBufferData(body, false, nullptr);
2516 // Note well: Reset() actually closes the stream in both directions. For
2517 // GOOGLE QUIC it sends a RST_STREAM (which does a 2-way close), for IETF
2518 // QUIC it sends both a RST_STREAM and a STOP_SENDING (each of which
2519 // closes in only one direction).
2520 stream4->Reset(QUIC_STREAM_CANCELLED);
2521 EXPECT_EQ(2u, session_.closed_streams()->size());
2522 }
2523
TEST_P(QuicSessionTestServer,OnStreamFrameLost)2524 TEST_P(QuicSessionTestServer, OnStreamFrameLost) {
2525 CompleteHandshake();
2526 InSequence s;
2527
2528 // Drive congestion control manually.
2529 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
2530 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
2531
2532 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
2533 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2534 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2535
2536 QuicStreamFrame frame1;
2537 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2538 frame1 = QuicStreamFrame(
2539 QuicUtils::GetCryptoStreamId(connection_->transport_version()), false,
2540 0, 1300);
2541 }
2542 QuicStreamFrame frame2(stream2->id(), false, 0, 9);
2543 QuicStreamFrame frame3(stream4->id(), false, 0, 9);
2544
2545 // Lost data on cryption stream, streams 2 and 4.
2546 EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
2547 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2548 EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
2549 .WillOnce(Return(true));
2550 }
2551 EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
2552 session_.OnFrameLost(QuicFrame(frame3));
2553 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2554 session_.OnFrameLost(QuicFrame(frame1));
2555 } else {
2556 QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, 0, 1300);
2557 session_.OnFrameLost(QuicFrame(&crypto_frame));
2558 }
2559 session_.OnFrameLost(QuicFrame(frame2));
2560 EXPECT_TRUE(session_.WillingAndAbleToWrite());
2561
2562 // Mark streams 2 and 4 write blocked.
2563 session_.MarkConnectionLevelWriteBlocked(stream2->id());
2564 session_.MarkConnectionLevelWriteBlocked(stream4->id());
2565
2566 // Lost data is retransmitted before new data, and retransmissions for crypto
2567 // stream go first.
2568 // Do not check congestion window when crypto stream has lost data.
2569 EXPECT_CALL(*send_algorithm, CanSend(_)).Times(0);
2570 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
2571 EXPECT_CALL(*crypto_stream, OnCanWrite());
2572 EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
2573 .WillOnce(Return(false));
2574 }
2575 // Check congestion window for non crypto streams.
2576 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2577 EXPECT_CALL(*stream4, OnCanWrite());
2578 EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(false));
2579 // Connection is blocked.
2580 EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(false));
2581
2582 session_.OnCanWrite();
2583 EXPECT_TRUE(session_.WillingAndAbleToWrite());
2584
2585 // Unblock connection.
2586 // Stream 2 retransmits lost data.
2587 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2588 EXPECT_CALL(*stream2, OnCanWrite());
2589 EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
2590 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2591 // Stream 2 sends new data.
2592 EXPECT_CALL(*stream2, OnCanWrite());
2593 EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
2594 EXPECT_CALL(*stream4, OnCanWrite());
2595 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
2596
2597 session_.OnCanWrite();
2598 EXPECT_FALSE(session_.WillingAndAbleToWrite());
2599 }
2600
TEST_P(QuicSessionTestServer,DonotRetransmitDataOfClosedStreams)2601 TEST_P(QuicSessionTestServer, DonotRetransmitDataOfClosedStreams) {
2602 CompleteHandshake();
2603 InSequence s;
2604
2605 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2606 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2607 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
2608
2609 QuicStreamFrame frame1(stream2->id(), false, 0, 9);
2610 QuicStreamFrame frame2(stream4->id(), false, 0, 9);
2611 QuicStreamFrame frame3(stream6->id(), false, 0, 9);
2612
2613 EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(true));
2614 EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
2615 EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
2616 session_.OnFrameLost(QuicFrame(frame3));
2617 session_.OnFrameLost(QuicFrame(frame2));
2618 session_.OnFrameLost(QuicFrame(frame1));
2619
2620 session_.MarkConnectionLevelWriteBlocked(stream2->id());
2621 session_.MarkConnectionLevelWriteBlocked(stream4->id());
2622 session_.MarkConnectionLevelWriteBlocked(stream6->id());
2623
2624 // Reset stream 4 locally.
2625 EXPECT_CALL(*connection_, SendControlFrame(_));
2626 EXPECT_CALL(*connection_, OnStreamReset(stream4->id(), _));
2627 stream4->Reset(QUIC_STREAM_CANCELLED);
2628
2629 // Verify stream 4 is removed from streams with lost data list.
2630 EXPECT_CALL(*stream6, OnCanWrite());
2631 EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(false));
2632 EXPECT_CALL(*stream2, OnCanWrite());
2633 EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
2634 EXPECT_CALL(*connection_, SendControlFrame(_))
2635 .WillRepeatedly(Invoke(&ClearControlFrame));
2636 EXPECT_CALL(*stream2, OnCanWrite());
2637 EXPECT_CALL(*stream6, OnCanWrite());
2638 session_.OnCanWrite();
2639 }
2640
TEST_P(QuicSessionTestServer,RetransmitFrames)2641 TEST_P(QuicSessionTestServer, RetransmitFrames) {
2642 CompleteHandshake();
2643 MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
2644 QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm);
2645 InSequence s;
2646
2647 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2648 TestStream* stream4 = session_.CreateOutgoingBidirectionalStream();
2649 TestStream* stream6 = session_.CreateOutgoingBidirectionalStream();
2650 EXPECT_CALL(*connection_, SendControlFrame(_))
2651 .WillOnce(Invoke(&ClearControlFrame));
2652 session_.SendWindowUpdate(stream2->id(), 9);
2653
2654 QuicStreamFrame frame1(stream2->id(), false, 0, 9);
2655 QuicStreamFrame frame2(stream4->id(), false, 0, 9);
2656 QuicStreamFrame frame3(stream6->id(), false, 0, 9);
2657 QuicWindowUpdateFrame window_update(1, stream2->id(), 9);
2658 QuicFrames frames;
2659 frames.push_back(QuicFrame(frame1));
2660 frames.push_back(QuicFrame(window_update));
2661 frames.push_back(QuicFrame(frame2));
2662 frames.push_back(QuicFrame(frame3));
2663 EXPECT_FALSE(session_.WillingAndAbleToWrite());
2664
2665 EXPECT_CALL(*stream2, RetransmitStreamData(_, _, _, _))
2666 .WillOnce(Return(true));
2667 EXPECT_CALL(*connection_, SendControlFrame(_))
2668 .WillOnce(Invoke(&ClearControlFrame));
2669 EXPECT_CALL(*stream4, RetransmitStreamData(_, _, _, _))
2670 .WillOnce(Return(true));
2671 EXPECT_CALL(*stream6, RetransmitStreamData(_, _, _, _))
2672 .WillOnce(Return(true));
2673 EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
2674 session_.RetransmitFrames(frames, PTO_RETRANSMISSION);
2675 }
2676
2677 // Regression test of b/110082001.
TEST_P(QuicSessionTestServer,RetransmitLostDataCausesConnectionClose)2678 TEST_P(QuicSessionTestServer, RetransmitLostDataCausesConnectionClose) {
2679 CompleteHandshake();
2680 // This test mimics the scenario when a dynamic stream retransmits lost data
2681 // and causes connection close.
2682 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
2683 QuicStreamFrame frame(stream->id(), false, 0, 9);
2684
2685 EXPECT_CALL(*stream, HasPendingRetransmission())
2686 .Times(2)
2687 .WillOnce(Return(true))
2688 .WillOnce(Return(false));
2689 session_.OnFrameLost(QuicFrame(frame));
2690 // Retransmit stream data causes connection close. Stream has not sent fin
2691 // yet, so an RST is sent.
2692 EXPECT_CALL(*stream, OnCanWrite()).WillOnce(Invoke([this, stream]() {
2693 session_.ResetStream(stream->id(), QUIC_STREAM_CANCELLED);
2694 }));
2695 if (VersionHasIetfQuicFrames(transport_version())) {
2696 // Once for the RST_STREAM, once for the STOP_SENDING
2697 EXPECT_CALL(*connection_, SendControlFrame(_))
2698 .Times(2)
2699 .WillRepeatedly(Invoke(&session_, &TestSession::SaveFrame));
2700 } else {
2701 // Just for the RST_STREAM
2702 EXPECT_CALL(*connection_, SendControlFrame(_))
2703 .WillOnce(Invoke(&session_, &TestSession::SaveFrame));
2704 }
2705 EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
2706 session_.OnCanWrite();
2707 }
2708
TEST_P(QuicSessionTestServer,SendMessage)2709 TEST_P(QuicSessionTestServer, SendMessage) {
2710 // Cannot send message when encryption is not established.
2711 EXPECT_FALSE(session_.OneRttKeysAvailable());
2712 EXPECT_EQ(MessageResult(MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0),
2713 session_.SendMessage(MemSliceFromString("")));
2714
2715 CompleteHandshake();
2716 EXPECT_TRUE(session_.OneRttKeysAvailable());
2717
2718 EXPECT_CALL(*connection_, SendMessage(1, _, false))
2719 .WillOnce(Return(MESSAGE_STATUS_SUCCESS));
2720 EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1),
2721 session_.SendMessage(MemSliceFromString("")));
2722 // Verify message_id increases.
2723 EXPECT_CALL(*connection_, SendMessage(2, _, false))
2724 .WillOnce(Return(MESSAGE_STATUS_TOO_LARGE));
2725 EXPECT_EQ(MessageResult(MESSAGE_STATUS_TOO_LARGE, 0),
2726 session_.SendMessage(MemSliceFromString("")));
2727 // Verify unsent message does not consume a message_id.
2728 EXPECT_CALL(*connection_, SendMessage(2, _, false))
2729 .WillOnce(Return(MESSAGE_STATUS_SUCCESS));
2730 EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 2),
2731 session_.SendMessage(MemSliceFromString("")));
2732
2733 QuicMessageFrame frame(1);
2734 QuicMessageFrame frame2(2);
2735 EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame)));
2736 EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2)));
2737
2738 // Lost message 2.
2739 session_.OnMessageLost(2);
2740 EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2)));
2741
2742 // message 1 gets acked.
2743 session_.OnMessageAcked(1, QuicTime::Zero());
2744 EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame)));
2745 }
2746
2747 // Regression test of b/115323618.
TEST_P(QuicSessionTestServer,LocallyResetZombieStreams)2748 TEST_P(QuicSessionTestServer, LocallyResetZombieStreams) {
2749 CompleteHandshake();
2750 session_.set_writev_consumes_all_data(true);
2751 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2752 std::string body(100, '.');
2753 QuicStreamPeer::CloseReadSide(stream2);
2754 stream2->WriteOrBufferData(body, true, nullptr);
2755 EXPECT_TRUE(stream2->IsWaitingForAcks());
2756 // Verify stream2 is a zombie streams.
2757 auto& stream_map = QuicSessionPeer::stream_map(&session_);
2758 ASSERT_TRUE(stream_map.contains(stream2->id()));
2759 auto* stream = stream_map.find(stream2->id())->second.get();
2760 EXPECT_TRUE(stream->IsZombie());
2761
2762 QuicStreamFrame frame(stream2->id(), true, 0, 100);
2763 EXPECT_CALL(*stream2, HasPendingRetransmission())
2764 .WillRepeatedly(Return(true));
2765 session_.OnFrameLost(QuicFrame(frame));
2766
2767 // Reset stream2 locally.
2768 EXPECT_CALL(*connection_, SendControlFrame(_))
2769 .WillRepeatedly(Invoke(&ClearControlFrame));
2770 EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _));
2771 stream2->Reset(QUIC_STREAM_CANCELLED);
2772
2773 // Verify stream 2 gets closed.
2774 EXPECT_TRUE(session_.IsClosedStream(stream2->id()));
2775 EXPECT_CALL(*stream2, OnCanWrite()).Times(0);
2776 session_.OnCanWrite();
2777 }
2778
TEST_P(QuicSessionTestServer,CleanUpClosedStreamsAlarm)2779 TEST_P(QuicSessionTestServer, CleanUpClosedStreamsAlarm) {
2780 CompleteHandshake();
2781 EXPECT_FALSE(
2782 QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet());
2783
2784 session_.set_writev_consumes_all_data(true);
2785 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
2786 EXPECT_FALSE(stream2->IsWaitingForAcks());
2787
2788 CloseStream(stream2->id());
2789 EXPECT_EQ(1u, session_.closed_streams()->size());
2790 EXPECT_TRUE(
2791 QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet());
2792
2793 alarm_factory_.FireAlarm(
2794 QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_));
2795 EXPECT_TRUE(session_.closed_streams()->empty());
2796 }
2797
TEST_P(QuicSessionTestServer,WriteUnidirectionalStream)2798 TEST_P(QuicSessionTestServer, WriteUnidirectionalStream) {
2799 session_.set_writev_consumes_all_data(true);
2800 TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1),
2801 &session_, WRITE_UNIDIRECTIONAL);
2802 session_.ActivateStream(absl::WrapUnique(stream4));
2803 std::string body(100, '.');
2804 stream4->WriteOrBufferData(body, false, nullptr);
2805 stream4->WriteOrBufferData(body, true, nullptr);
2806 auto& stream_map = QuicSessionPeer::stream_map(&session_);
2807 ASSERT_TRUE(stream_map.contains(stream4->id()));
2808 auto* stream = stream_map.find(stream4->id())->second.get();
2809 EXPECT_TRUE(stream->IsZombie());
2810 }
2811
TEST_P(QuicSessionTestServer,ReceivedDataOnWriteUnidirectionalStream)2812 TEST_P(QuicSessionTestServer, ReceivedDataOnWriteUnidirectionalStream) {
2813 TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1),
2814 &session_, WRITE_UNIDIRECTIONAL);
2815 session_.ActivateStream(absl::WrapUnique(stream4));
2816
2817 EXPECT_CALL(
2818 *connection_,
2819 CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _))
2820 .Times(1);
2821 QuicStreamFrame stream_frame(GetNthServerInitiatedUnidirectionalId(1), false,
2822 0, 2);
2823 session_.OnStreamFrame(stream_frame);
2824 }
2825
TEST_P(QuicSessionTestServer,ReadUnidirectionalStream)2826 TEST_P(QuicSessionTestServer, ReadUnidirectionalStream) {
2827 TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2828 &session_, READ_UNIDIRECTIONAL);
2829 session_.ActivateStream(absl::WrapUnique(stream4));
2830 EXPECT_FALSE(stream4->IsWaitingForAcks());
2831 // Discard all incoming data.
2832 stream4->StopReading();
2833
2834 std::string data(100, '.');
2835 QuicStreamFrame stream_frame(GetNthClientInitiatedUnidirectionalId(1), false,
2836 0, data);
2837 stream4->OnStreamFrame(stream_frame);
2838 EXPECT_TRUE(session_.closed_streams()->empty());
2839
2840 QuicStreamFrame stream_frame2(GetNthClientInitiatedUnidirectionalId(1), true,
2841 100, data);
2842 stream4->OnStreamFrame(stream_frame2);
2843 EXPECT_EQ(1u, session_.closed_streams()->size());
2844 }
2845
TEST_P(QuicSessionTestServer,WriteOrBufferDataOnReadUnidirectionalStream)2846 TEST_P(QuicSessionTestServer, WriteOrBufferDataOnReadUnidirectionalStream) {
2847 TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2848 &session_, READ_UNIDIRECTIONAL);
2849 session_.ActivateStream(absl::WrapUnique(stream4));
2850
2851 EXPECT_CALL(*connection_,
2852 CloseConnection(
2853 QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2854 .Times(1);
2855 std::string body(100, '.');
2856 stream4->WriteOrBufferData(body, false, nullptr);
2857 }
2858
TEST_P(QuicSessionTestServer,WritevDataOnReadUnidirectionalStream)2859 TEST_P(QuicSessionTestServer, WritevDataOnReadUnidirectionalStream) {
2860 TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2861 &session_, READ_UNIDIRECTIONAL);
2862 session_.ActivateStream(absl::WrapUnique(stream4));
2863
2864 EXPECT_CALL(*connection_,
2865 CloseConnection(
2866 QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2867 .Times(1);
2868 std::string body(100, '.');
2869 struct iovec iov = {const_cast<char*>(body.data()), body.length()};
2870 quiche::QuicheMemSliceStorage storage(
2871 &iov, 1, session_.connection()->helper()->GetStreamSendBufferAllocator(),
2872 1024);
2873 stream4->WriteMemSlices(storage.ToSpan(), false);
2874 }
2875
TEST_P(QuicSessionTestServer,WriteMemSlicesOnReadUnidirectionalStream)2876 TEST_P(QuicSessionTestServer, WriteMemSlicesOnReadUnidirectionalStream) {
2877 TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1),
2878 &session_, READ_UNIDIRECTIONAL);
2879 session_.ActivateStream(absl::WrapUnique(stream4));
2880
2881 EXPECT_CALL(*connection_,
2882 CloseConnection(
2883 QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _))
2884 .Times(1);
2885 std::string data(1024, 'a');
2886 std::vector<quiche::QuicheMemSlice> buffers;
2887 buffers.push_back(MemSliceFromString(data));
2888 buffers.push_back(MemSliceFromString(data));
2889 stream4->WriteMemSlices(absl::MakeSpan(buffers), false);
2890 }
2891
2892 // Test code that tests that an incoming stream frame with a new (not previously
2893 // seen) stream id is acceptable. The ID must not be larger than has been
2894 // advertised. It may be equal to what has been advertised. These tests
2895 // invoke QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId by calling
2896 // QuicSession::OnStreamFrame in order to check that all the steps are connected
2897 // properly and that nothing in the call path interferes with the check.
2898 // First test make sure that streams with ids below the limit are accepted.
TEST_P(QuicSessionTestServer,NewStreamIdBelowLimit)2899 TEST_P(QuicSessionTestServer, NewStreamIdBelowLimit) {
2900 if (!VersionHasIetfQuicFrames(transport_version())) {
2901 // Applicable only to IETF QUIC
2902 return;
2903 }
2904 QuicStreamId bidirectional_stream_id = StreamCountToId(
2905 QuicSessionPeer::ietf_streamid_manager(&session_)
2906 ->advertised_max_incoming_bidirectional_streams() -
2907 1,
2908 Perspective::IS_CLIENT,
2909 /*bidirectional=*/true);
2910
2911 QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2912 "Random String");
2913 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2914 session_.OnStreamFrame(bidirectional_stream_frame);
2915
2916 QuicStreamId unidirectional_stream_id = StreamCountToId(
2917 QuicSessionPeer::ietf_streamid_manager(&session_)
2918 ->advertised_max_incoming_unidirectional_streams() -
2919 1,
2920 Perspective::IS_CLIENT,
2921 /*bidirectional=*/false);
2922 QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2923 0, "Random String");
2924 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2925 session_.OnStreamFrame(unidirectional_stream_frame);
2926 }
2927
2928 // Accept a stream with an ID that equals the limit.
TEST_P(QuicSessionTestServer,NewStreamIdAtLimit)2929 TEST_P(QuicSessionTestServer, NewStreamIdAtLimit) {
2930 if (!VersionHasIetfQuicFrames(transport_version())) {
2931 // Applicable only to IETF QUIC
2932 return;
2933 }
2934 QuicStreamId bidirectional_stream_id =
2935 StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_)
2936 ->advertised_max_incoming_bidirectional_streams(),
2937 Perspective::IS_CLIENT, /*bidirectional=*/true);
2938 QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2939 "Random String");
2940 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2941 session_.OnStreamFrame(bidirectional_stream_frame);
2942
2943 QuicStreamId unidirectional_stream_id =
2944 StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_)
2945 ->advertised_max_incoming_unidirectional_streams(),
2946 Perspective::IS_CLIENT, /*bidirectional=*/false);
2947 QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2948 0, "Random String");
2949 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
2950 session_.OnStreamFrame(unidirectional_stream_frame);
2951 }
2952
2953 // Close the connection if the id exceeds the limit.
TEST_P(QuicSessionTestServer,NewStreamIdAboveLimit)2954 TEST_P(QuicSessionTestServer, NewStreamIdAboveLimit) {
2955 if (!VersionHasIetfQuicFrames(transport_version())) {
2956 // Applicable only to IETF QUIC
2957 return;
2958 }
2959
2960 QuicStreamId bidirectional_stream_id = StreamCountToId(
2961 QuicSessionPeer::ietf_streamid_manager(&session_)
2962 ->advertised_max_incoming_bidirectional_streams() +
2963 1,
2964 Perspective::IS_CLIENT, /*bidirectional=*/true);
2965 QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0,
2966 "Random String");
2967 EXPECT_CALL(
2968 *connection_,
2969 CloseConnection(QUIC_INVALID_STREAM_ID,
2970 "Stream id 400 would exceed stream count limit 100", _));
2971 session_.OnStreamFrame(bidirectional_stream_frame);
2972
2973 QuicStreamId unidirectional_stream_id = StreamCountToId(
2974 QuicSessionPeer::ietf_streamid_manager(&session_)
2975 ->advertised_max_incoming_unidirectional_streams() +
2976 1,
2977 Perspective::IS_CLIENT, /*bidirectional=*/false);
2978 QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false,
2979 0, "Random String");
2980 EXPECT_CALL(
2981 *connection_,
2982 CloseConnection(QUIC_INVALID_STREAM_ID,
2983 "Stream id 402 would exceed stream count limit 100", _));
2984 session_.OnStreamFrame(unidirectional_stream_frame);
2985 }
2986
2987 // Checks that invalid stream ids are handled.
TEST_P(QuicSessionTestServer,OnStopSendingInvalidStreamId)2988 TEST_P(QuicSessionTestServer, OnStopSendingInvalidStreamId) {
2989 if (!VersionHasIetfQuicFrames(transport_version())) {
2990 return;
2991 }
2992 // Check that "invalid" stream ids are rejected.
2993 QuicStopSendingFrame frame(1, -1, QUIC_STREAM_CANCELLED);
2994 EXPECT_CALL(
2995 *connection_,
2996 CloseConnection(QUIC_INVALID_STREAM_ID,
2997 "Received STOP_SENDING for an invalid stream", _));
2998 session_.OnStopSendingFrame(frame);
2999 }
3000
TEST_P(QuicSessionTestServer,OnStopSendingReadUnidirectional)3001 TEST_P(QuicSessionTestServer, OnStopSendingReadUnidirectional) {
3002 if (!VersionHasIetfQuicFrames(transport_version())) {
3003 return;
3004 }
3005 // It's illegal to send STOP_SENDING with a stream ID that is read-only.
3006 QuicStopSendingFrame frame(1, GetNthClientInitiatedUnidirectionalId(1),
3007 QUIC_STREAM_CANCELLED);
3008 EXPECT_CALL(
3009 *connection_,
3010 CloseConnection(QUIC_INVALID_STREAM_ID,
3011 "Received STOP_SENDING for a read-only stream", _));
3012 session_.OnStopSendingFrame(frame);
3013 }
3014
3015 // Static streams ignore STOP_SENDING.
TEST_P(QuicSessionTestServer,OnStopSendingStaticStreams)3016 TEST_P(QuicSessionTestServer, OnStopSendingStaticStreams) {
3017 if (!VersionHasIetfQuicFrames(transport_version())) {
3018 return;
3019 }
3020 QuicStreamId stream_id = 0;
3021 std::unique_ptr<TestStream> fake_static_stream = std::make_unique<TestStream>(
3022 stream_id, &session_, /*is_static*/ true, BIDIRECTIONAL);
3023 QuicSessionPeer::ActivateStream(&session_, std::move(fake_static_stream));
3024 // Check that a stream id in the static stream map is ignored.
3025 QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
3026 EXPECT_CALL(*connection_,
3027 CloseConnection(QUIC_INVALID_STREAM_ID,
3028 "Received STOP_SENDING for a static stream", _));
3029 session_.OnStopSendingFrame(frame);
3030 }
3031
3032 // If stream is write closed, do not send a RST_STREAM frame.
TEST_P(QuicSessionTestServer,OnStopSendingForWriteClosedStream)3033 TEST_P(QuicSessionTestServer, OnStopSendingForWriteClosedStream) {
3034 if (!VersionHasIetfQuicFrames(transport_version())) {
3035 return;
3036 }
3037
3038 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3039 QuicStreamId stream_id = stream->id();
3040 QuicStreamPeer::SetFinSent(stream);
3041 stream->CloseWriteSide();
3042 EXPECT_TRUE(stream->write_side_closed());
3043 QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
3044 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
3045 session_.OnStopSendingFrame(frame);
3046 }
3047
3048 // If stream is closed, return true and do not close the connection.
TEST_P(QuicSessionTestServer,OnStopSendingClosedStream)3049 TEST_P(QuicSessionTestServer, OnStopSendingClosedStream) {
3050 if (!VersionHasIetfQuicFrames(transport_version())) {
3051 return;
3052 }
3053 CompleteHandshake();
3054 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3055 QuicStreamId stream_id = stream->id();
3056 CloseStream(stream_id);
3057 QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
3058 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
3059 session_.OnStopSendingFrame(frame);
3060 }
3061
3062 // If stream id is a nonexistent local stream, return false and close the
3063 // connection.
TEST_P(QuicSessionTestServer,OnStopSendingInputNonExistentLocalStream)3064 TEST_P(QuicSessionTestServer, OnStopSendingInputNonExistentLocalStream) {
3065 if (!VersionHasIetfQuicFrames(transport_version())) {
3066 return;
3067 }
3068
3069 QuicStopSendingFrame frame(1, GetNthServerInitiatedBidirectionalId(123456),
3070 QUIC_STREAM_CANCELLED);
3071 EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_STREAM_WRONG_DIRECTION,
3072 "Data for nonexistent stream", _))
3073 .Times(1);
3074 session_.OnStopSendingFrame(frame);
3075 }
3076
3077 // If a STOP_SENDING is received for a peer initiated stream, the new stream
3078 // will be created.
TEST_P(QuicSessionTestServer,OnStopSendingNewStream)3079 TEST_P(QuicSessionTestServer, OnStopSendingNewStream) {
3080 CompleteHandshake();
3081 if (!VersionHasIetfQuicFrames(transport_version())) {
3082 return;
3083 }
3084 QuicStopSendingFrame frame(1, GetNthClientInitiatedBidirectionalId(1),
3085 QUIC_STREAM_CANCELLED);
3086
3087 // A Rst will be sent as a response for STOP_SENDING.
3088 EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
3089 EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1);
3090 session_.OnStopSendingFrame(frame);
3091
3092 QuicStream* stream =
3093 session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(1));
3094 EXPECT_TRUE(stream);
3095 EXPECT_TRUE(stream->write_side_closed());
3096 }
3097
3098 // For a valid stream, ensure that all works
TEST_P(QuicSessionTestServer,OnStopSendingInputValidStream)3099 TEST_P(QuicSessionTestServer, OnStopSendingInputValidStream) {
3100 CompleteHandshake();
3101 if (!VersionHasIetfQuicFrames(transport_version())) {
3102 // Applicable only to IETF QUIC
3103 return;
3104 }
3105
3106 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3107
3108 // Ensure that the stream starts out open in both directions.
3109 EXPECT_FALSE(stream->write_side_closed());
3110 EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream));
3111
3112 QuicStreamId stream_id = stream->id();
3113 QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED);
3114 // Expect a reset to come back out.
3115 EXPECT_CALL(*connection_, SendControlFrame(_));
3116 EXPECT_CALL(*connection_, OnStreamReset(stream_id, QUIC_STREAM_CANCELLED));
3117 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
3118 session_.OnStopSendingFrame(frame);
3119
3120 EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream));
3121 EXPECT_TRUE(stream->write_side_closed());
3122 }
3123
TEST_P(QuicSessionTestServer,WriteBufferedCryptoFrames)3124 TEST_P(QuicSessionTestServer, WriteBufferedCryptoFrames) {
3125 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
3126 return;
3127 }
3128 std::string data(1350, 'a');
3129 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
3130 // Only consumed 1000 bytes.
3131 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
3132 .WillOnce(Return(1000));
3133 crypto_stream->WriteCryptoData(ENCRYPTION_INITIAL, data);
3134 EXPECT_TRUE(session_.HasPendingHandshake());
3135 EXPECT_TRUE(session_.WillingAndAbleToWrite());
3136
3137 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
3138 connection_->SetEncrypter(
3139 ENCRYPTION_ZERO_RTT,
3140 std::make_unique<NullEncrypter>(connection_->perspective()));
3141 crypto_stream->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
3142
3143 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000))
3144 .WillOnce(Return(350));
3145 EXPECT_CALL(
3146 *connection_,
3147 SendCryptoData(crypto_stream->GetEncryptionLevelToSendCryptoDataOfSpace(
3148 QuicUtils::GetPacketNumberSpace(ENCRYPTION_ZERO_RTT)),
3149 1350, 0))
3150 .WillOnce(Return(1350));
3151 session_.OnCanWrite();
3152 EXPECT_FALSE(session_.HasPendingHandshake());
3153 EXPECT_FALSE(session_.WillingAndAbleToWrite());
3154 }
3155
3156 // Regression test for
3157 // https://bugs.chromium.org/p/chromium/issues/detail?id=1002119
TEST_P(QuicSessionTestServer,StreamFrameReceivedAfterFin)3158 TEST_P(QuicSessionTestServer, StreamFrameReceivedAfterFin) {
3159 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3160 QuicStreamFrame frame(stream->id(), true, 0, ",");
3161 session_.OnStreamFrame(frame);
3162
3163 QuicStreamFrame frame1(stream->id(), false, 1, ",");
3164 EXPECT_CALL(*connection_,
3165 CloseConnection(QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, _, _));
3166 session_.OnStreamFrame(frame1);
3167 }
3168
TEST_P(QuicSessionTestServer,ResetForIETFStreamTypes)3169 TEST_P(QuicSessionTestServer, ResetForIETFStreamTypes) {
3170 CompleteHandshake();
3171 if (!VersionHasIetfQuicFrames(transport_version())) {
3172 return;
3173 }
3174
3175 QuicStreamId read_only = GetNthClientInitiatedUnidirectionalId(0);
3176
3177 EXPECT_CALL(*connection_, SendControlFrame(_))
3178 .Times(1)
3179 .WillOnce(Invoke(&ClearControlFrame));
3180 EXPECT_CALL(*connection_, OnStreamReset(read_only, _));
3181 session_.ResetStream(read_only, QUIC_STREAM_CANCELLED);
3182
3183 QuicStreamId write_only = GetNthServerInitiatedUnidirectionalId(0);
3184 EXPECT_CALL(*connection_, SendControlFrame(_))
3185 .Times(1)
3186 .WillOnce(Invoke(&ClearControlFrame));
3187 EXPECT_CALL(*connection_, OnStreamReset(write_only, _));
3188 session_.ResetStream(write_only, QUIC_STREAM_CANCELLED);
3189
3190 QuicStreamId bidirectional = GetNthClientInitiatedBidirectionalId(0);
3191 EXPECT_CALL(*connection_, SendControlFrame(_))
3192 .Times(2)
3193 .WillRepeatedly(Invoke(&ClearControlFrame));
3194 EXPECT_CALL(*connection_, OnStreamReset(bidirectional, _));
3195 session_.ResetStream(bidirectional, QUIC_STREAM_CANCELLED);
3196 }
3197
TEST_P(QuicSessionTestServer,DecryptionKeyAvailableBeforeEncryptionKey)3198 TEST_P(QuicSessionTestServer, DecryptionKeyAvailableBeforeEncryptionKey) {
3199 if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) {
3200 return;
3201 }
3202 ASSERT_FALSE(connection_->framer().HasEncrypterOfEncryptionLevel(
3203 ENCRYPTION_HANDSHAKE));
3204 EXPECT_FALSE(session_.OnNewDecryptionKeyAvailable(
3205 ENCRYPTION_HANDSHAKE, /*decrypter=*/nullptr,
3206 /*set_alternative_decrypter=*/false, /*latch_once_used=*/false));
3207 }
3208
TEST_P(QuicSessionTestServer,IncomingStreamWithServerInitiatedStreamId)3209 TEST_P(QuicSessionTestServer, IncomingStreamWithServerInitiatedStreamId) {
3210 const QuicErrorCode expected_error =
3211 VersionHasIetfQuicFrames(transport_version())
3212 ? QUIC_HTTP_STREAM_WRONG_DIRECTION
3213 : QUIC_INVALID_STREAM_ID;
3214 EXPECT_CALL(
3215 *connection_,
3216 CloseConnection(expected_error, "Data for nonexistent stream",
3217 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
3218
3219 QuicStreamFrame frame(GetNthServerInitiatedBidirectionalId(1),
3220 /* fin = */ false, /* offset = */ 0,
3221 absl::string_view("foo"));
3222 session_.OnStreamFrame(frame);
3223 }
3224
3225 // Regression test for b/235204908.
TEST_P(QuicSessionTestServer,BlockedFrameCausesWriteError)3226 TEST_P(QuicSessionTestServer, BlockedFrameCausesWriteError) {
3227 CompleteHandshake();
3228 MockPacketWriter* writer = static_cast<MockPacketWriter*>(
3229 QuicConnectionPeer::GetWriter(session_.connection()));
3230 EXPECT_CALL(*writer, WritePacket(_, _, _, _, _, _))
3231 .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
3232 // Set a small connection level flow control limit.
3233 const uint64_t kWindow = 36;
3234 QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(),
3235 kWindow);
3236 auto stream =
3237 session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(0));
3238 // Try to send more data than the flow control limit allows.
3239 const uint64_t kOverflow = 15;
3240 std::string body(kWindow + kOverflow, 'a');
3241 EXPECT_CALL(*connection_, SendControlFrame(_))
3242 .WillOnce(testing::InvokeWithoutArgs([this]() {
3243 connection_->ReallyCloseConnection(
3244 QUIC_PACKET_WRITE_ERROR, "write error",
3245 ConnectionCloseBehavior::SILENT_CLOSE);
3246 return false;
3247 }));
3248 stream->WriteOrBufferData(body, false, nullptr);
3249 }
3250
TEST_P(QuicSessionTestServer,BufferedCryptoFrameCausesWriteError)3251 TEST_P(QuicSessionTestServer, BufferedCryptoFrameCausesWriteError) {
3252 if (!VersionHasIetfQuicFrames(transport_version())) {
3253 return;
3254 }
3255 std::string data(1350, 'a');
3256 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
3257 // Only consumed 1000 bytes.
3258 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 1350, 0))
3259 .WillOnce(Return(1000));
3260 crypto_stream->WriteCryptoData(ENCRYPTION_FORWARD_SECURE, data);
3261 EXPECT_TRUE(session_.HasPendingHandshake());
3262 EXPECT_TRUE(session_.WillingAndAbleToWrite());
3263
3264 EXPECT_CALL(*connection_,
3265 SendCryptoData(ENCRYPTION_FORWARD_SECURE, 350, 1000))
3266 .WillOnce(Return(0));
3267 // Buffer the HANDSHAKE_DONE frame.
3268 EXPECT_CALL(*connection_, SendControlFrame(_)).WillOnce(Return(false));
3269 CryptoHandshakeMessage msg;
3270 session_.GetMutableCryptoStream()->OnHandshakeMessage(msg);
3271
3272 // Flush both frames.
3273 EXPECT_CALL(*connection_,
3274 SendCryptoData(ENCRYPTION_FORWARD_SECURE, 350, 1000))
3275 .WillOnce(testing::InvokeWithoutArgs([this]() {
3276 connection_->ReallyCloseConnection(
3277 QUIC_PACKET_WRITE_ERROR, "write error",
3278 ConnectionCloseBehavior::SILENT_CLOSE);
3279 return 350;
3280 }));
3281 if (!GetQuicReloadableFlag(
3282 quic_no_write_control_frame_upon_connection_close)) {
3283 EXPECT_CALL(*connection_, SendControlFrame(_)).WillOnce(Return(false));
3284 EXPECT_QUIC_BUG(session_.OnCanWrite(), "Try to write control frame");
3285 } else {
3286 session_.OnCanWrite();
3287 }
3288 }
3289
TEST_P(QuicSessionTestServer,DonotPtoStreamDataBeforeHandshakeConfirmed)3290 TEST_P(QuicSessionTestServer, DonotPtoStreamDataBeforeHandshakeConfirmed) {
3291 if (!session_.version().UsesTls()) {
3292 return;
3293 }
3294 EXPECT_NE(HANDSHAKE_CONFIRMED, session_.GetHandshakeState());
3295
3296 TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream();
3297 EXPECT_FALSE(crypto_stream->HasBufferedCryptoFrames());
3298 std::string data(1350, 'a');
3299 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
3300 .WillOnce(Return(1000));
3301 crypto_stream->WriteCryptoData(ENCRYPTION_INITIAL, data);
3302 ASSERT_TRUE(crypto_stream->HasBufferedCryptoFrames());
3303
3304 TestStream* stream = session_.CreateOutgoingBidirectionalStream();
3305
3306 session_.MarkConnectionLevelWriteBlocked(stream->id());
3307 // Buffered crypto data gets sent.
3308 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, _, _))
3309 .WillOnce(Return(350));
3310 // Verify stream data is not sent on PTO before handshake confirmed.
3311 EXPECT_CALL(*stream, OnCanWrite()).Times(0);
3312
3313 // Fire PTO.
3314 QuicConnectionPeer::SetInProbeTimeOut(connection_, true);
3315 session_.OnCanWrite();
3316 EXPECT_FALSE(crypto_stream->HasBufferedCryptoFrames());
3317 }
3318
TEST_P(QuicSessionTestServer,SetStatelessResetTokenToSend)3319 TEST_P(QuicSessionTestServer, SetStatelessResetTokenToSend) {
3320 if (!session_.version().HasIetfQuicFrames()) {
3321 return;
3322 }
3323 EXPECT_TRUE(session_.config()->HasStatelessResetTokenToSend());
3324 }
3325
TEST_P(QuicSessionTestServer,SetServerPreferredAddressAccordingToAddressFamily)3326 TEST_P(QuicSessionTestServer,
3327 SetServerPreferredAddressAccordingToAddressFamily) {
3328 if (!session_.version().HasIetfQuicFrames()) {
3329 return;
3330 }
3331 EXPECT_EQ(quiche::IpAddressFamily::IP_V4,
3332 connection_->peer_address().host().address_family());
3333 QuicConnectionPeer::SetEffectivePeerAddress(connection_,
3334 connection_->peer_address());
3335 QuicTagVector copt;
3336 copt.push_back(kSPAD);
3337 QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
3338 QuicSocketAddress preferred_address(QuicIpAddress::Loopback4(), 12345);
3339 session_.config()->SetIPv4AlternateServerAddressToSend(preferred_address);
3340 session_.config()->SetIPv6AlternateServerAddressToSend(
3341 QuicSocketAddress(QuicIpAddress::Loopback6(), 12345));
3342
3343 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3344 session_.OnConfigNegotiated();
3345 EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), 12345),
3346 session_.config()
3347 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)
3348 .value());
3349 EXPECT_FALSE(session_.config()
3350 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6)
3351 .has_value());
3352 EXPECT_EQ(preferred_address,
3353 connection_->expected_server_preferred_address());
3354 }
3355
TEST_P(QuicSessionTestServer,SetDNatServerPreferredAddressAccordingToAddressFamily)3356 TEST_P(QuicSessionTestServer,
3357 SetDNatServerPreferredAddressAccordingToAddressFamily) {
3358 if (!session_.version().HasIetfQuicFrames()) {
3359 return;
3360 }
3361 EXPECT_EQ(quiche::IpAddressFamily::IP_V4,
3362 connection_->peer_address().host().address_family());
3363 QuicConnectionPeer::SetEffectivePeerAddress(connection_,
3364 connection_->peer_address());
3365 QuicTagVector copt;
3366 copt.push_back(kSPAD);
3367 QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
3368 QuicSocketAddress sent_preferred_address(QuicIpAddress::Loopback4(), 12345);
3369 QuicSocketAddress expected_preferred_address(QuicIpAddress::Loopback4(),
3370 12346);
3371 session_.config()->SetIPv4AlternateServerAddressForDNat(
3372 sent_preferred_address, expected_preferred_address);
3373 session_.config()->SetIPv6AlternateServerAddressForDNat(
3374 QuicSocketAddress(QuicIpAddress::Loopback6(), 12345),
3375 QuicSocketAddress(QuicIpAddress::Loopback6(), 12346));
3376
3377 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3378 session_.OnConfigNegotiated();
3379 EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), 12345),
3380 session_.config()
3381 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)
3382 .value());
3383 EXPECT_FALSE(session_.config()
3384 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6)
3385 .has_value());
3386 EXPECT_EQ(expected_preferred_address,
3387 connection_->expected_server_preferred_address());
3388 }
3389
TEST_P(QuicSessionTestServer,NoServerPreferredAddressIfAddressFamilyMismatch)3390 TEST_P(QuicSessionTestServer, NoServerPreferredAddressIfAddressFamilyMismatch) {
3391 if (!session_.version().HasIetfQuicFrames()) {
3392 return;
3393 }
3394 EXPECT_EQ(quiche::IpAddressFamily::IP_V4,
3395 connection_->peer_address().host().address_family());
3396 QuicConnectionPeer::SetEffectivePeerAddress(connection_,
3397 connection_->peer_address());
3398 QuicTagVector copt;
3399 copt.push_back(kSPAD);
3400 QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt);
3401 session_.config()->SetIPv6AlternateServerAddressToSend(
3402 QuicSocketAddress(QuicIpAddress::Loopback6(), 12345));
3403
3404 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3405 session_.OnConfigNegotiated();
3406 EXPECT_FALSE(session_.config()
3407 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)
3408 .has_value());
3409 EXPECT_FALSE(session_.config()
3410 ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6)
3411 .has_value());
3412 EXPECT_FALSE(
3413 connection_->expected_server_preferred_address().IsInitialized());
3414 }
3415
TEST_P(QuicSessionTestServer,OpenStreamLimitPerEventLoop)3416 TEST_P(QuicSessionTestServer, OpenStreamLimitPerEventLoop) {
3417 if (!VersionHasIetfQuicFrames(transport_version())) {
3418 // Only needed for version 99/IETF QUIC. Noop otherwise.
3419 return;
3420 }
3421 session_.set_uses_pending_streams(true);
3422 CompleteHandshake();
3423
3424 // Receive data on a read uni stream without 1st byte and the stream
3425 // should become pending.
3426 QuicStreamId unidirectional_stream_id =
3427 QuicUtils::GetFirstUnidirectionalStreamId(transport_version(),
3428 Perspective::IS_CLIENT);
3429 QuicStreamFrame data1(unidirectional_stream_id, false, 10,
3430 absl::string_view("HT"));
3431 session_.OnStreamFrame(data1);
3432 EXPECT_TRUE(
3433 QuicSessionPeer::GetPendingStream(&session_, unidirectional_stream_id));
3434 EXPECT_EQ(0, session_.num_incoming_streams_created());
3435 // Receive data on 10 more bidi streams. Only the first 5 should open new
3436 // streams.
3437 size_t i = 0u;
3438 for (; i < 10u; ++i) {
3439 QuicStreamId bidi_stream_id = GetNthClientInitiatedBidirectionalId(i);
3440 QuicStreamFrame data(bidi_stream_id, false, 0, "aaaa");
3441 session_.OnStreamFrame(data);
3442 if (i > 4u) {
3443 EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, bidi_stream_id));
3444 }
3445 }
3446 EXPECT_EQ(5u, session_.num_incoming_streams_created());
3447 EXPECT_EQ(GetNthClientInitiatedBidirectionalId(i - 1),
3448 QuicSessionPeer::GetLargestPeerCreatedStreamId(&session_, false));
3449 EXPECT_TRUE(session_.GetActiveStream(GetNthClientInitiatedBidirectionalId(4))
3450 ->pending_duration()
3451 .IsZero());
3452 // Receive 1st byte on the read uni stream. The stream should still be pending
3453 // due to the stream limit.
3454 QuicStreamFrame data2(unidirectional_stream_id, false, 0,
3455 absl::string_view("HT"));
3456 session_.OnStreamFrame(data2);
3457 EXPECT_TRUE(
3458 QuicSessionPeer::GetPendingStream(&session_, unidirectional_stream_id));
3459
3460 // Start another loop should cause 5 more pending streams to open, including
3461 // the unidirectional stream.
3462 helper_.GetClock()->AdvanceTime(QuicTime::Delta::FromMicroseconds(100));
3463 QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_);
3464 EXPECT_TRUE(alarm->IsSet());
3465 alarm_factory_.FireAlarm(alarm);
3466 EXPECT_EQ(10u, session_.num_incoming_streams_created());
3467 EXPECT_NE(nullptr, session_.GetActiveStream(unidirectional_stream_id));
3468 EXPECT_EQ(100, session_.GetActiveStream(unidirectional_stream_id)
3469 ->pending_duration()
3470 .ToMicroseconds());
3471 EXPECT_EQ(
3472 100,
3473 session_.GetActiveStream(GetNthClientInitiatedBidirectionalId(i - 2))
3474 ->pending_duration()
3475 .ToMicroseconds());
3476 // The 10th bidi stream should remain pending.
3477 EXPECT_EQ(nullptr, session_.GetActiveStream(
3478 GetNthClientInitiatedBidirectionalId(i - 1)));
3479 }
3480
3481 // A client test class that can be used when the automatic configuration is not
3482 // desired.
3483 class QuicSessionTestClientUnconfigured : public QuicSessionTestBase {
3484 protected:
QuicSessionTestClientUnconfigured()3485 QuicSessionTestClientUnconfigured()
3486 : QuicSessionTestBase(Perspective::IS_CLIENT,
3487 /*configure_session=*/false) {}
3488 };
3489
3490 INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestClientUnconfigured,
3491 ::testing::ValuesIn(AllSupportedVersions()),
3492 ::testing::PrintToStringParamName());
3493
TEST_P(QuicSessionTestClientUnconfigured,StreamInitiallyBlockedThenUnblocked)3494 TEST_P(QuicSessionTestClientUnconfigured, StreamInitiallyBlockedThenUnblocked) {
3495 if (!connection_->version().AllowsLowFlowControlLimits()) {
3496 return;
3497 }
3498 // Create a stream before negotiating the config and verify it starts off
3499 // blocked.
3500 QuicSessionPeer::SetMaxOpenOutgoingBidirectionalStreams(&session_, 10);
3501 TestStream* stream2 = session_.CreateOutgoingBidirectionalStream();
3502 EXPECT_TRUE(stream2->IsFlowControlBlocked());
3503 EXPECT_TRUE(session_.IsConnectionFlowControlBlocked());
3504 EXPECT_TRUE(session_.IsStreamFlowControlBlocked());
3505
3506 // Negotiate the config with higher received limits.
3507 QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
3508 session_.config(), kMinimumFlowControlSendWindow);
3509 QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
3510 session_.config(), kMinimumFlowControlSendWindow);
3511 session_.OnConfigNegotiated();
3512
3513 // Stream is now unblocked.
3514 EXPECT_FALSE(stream2->IsFlowControlBlocked());
3515 EXPECT_FALSE(session_.IsConnectionFlowControlBlocked());
3516 EXPECT_FALSE(session_.IsStreamFlowControlBlocked());
3517 }
3518
3519 } // namespace
3520 } // namespace test
3521 } // namespace quic
3522