1 // Copyright 2016 The Chromium Authors
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 "net/quic/bidirectional_stream_quic_impl.h"
6
7 #include <memory>
8 #include <utility>
9
10 #include "base/memory/ptr_util.h"
11 #include "base/memory/raw_ptr.h"
12 #include "base/run_loop.h"
13 #include "base/strings/strcat.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/task/single_thread_task_runner.h"
16 #include "base/time/default_tick_clock.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "net/base/completion_once_callback.h"
20 #include "net/base/ip_address.h"
21 #include "net/base/load_timing_info.h"
22 #include "net/base/load_timing_info_test_util.h"
23 #include "net/base/net_errors.h"
24 #include "net/dns/public/host_resolver_results.h"
25 #include "net/dns/public/secure_dns_policy.h"
26 #include "net/http/bidirectional_stream_request_info.h"
27 #include "net/http/transport_security_state.h"
28 #include "net/log/net_log.h"
29 #include "net/log/net_log_event_type.h"
30 #include "net/log/test_net_log.h"
31 #include "net/log/test_net_log_util.h"
32 #include "net/quic/address_utils.h"
33 #include "net/quic/mock_crypto_client_stream_factory.h"
34 #include "net/quic/quic_chromium_alarm_factory.h"
35 #include "net/quic/quic_chromium_connection_helper.h"
36 #include "net/quic/quic_chromium_packet_reader.h"
37 #include "net/quic/quic_chromium_packet_writer.h"
38 #include "net/quic/quic_context.h"
39 #include "net/quic/quic_crypto_client_config_handle.h"
40 #include "net/quic/quic_http_utils.h"
41 #include "net/quic/quic_server_info.h"
42 #include "net/quic/quic_stream_factory.h"
43 #include "net/quic/quic_test_packet_maker.h"
44 #include "net/quic/quic_test_packet_printer.h"
45 #include "net/quic/test_quic_crypto_client_config_handle.h"
46 #include "net/quic/test_task_runner.h"
47 #include "net/socket/socket_test_util.h"
48 #include "net/ssl/ssl_config_service_defaults.h"
49 #include "net/test/gtest_util.h"
50 #include "net/test/test_with_task_environment.h"
51 #include "net/third_party/quiche/src/quiche/common/quiche_text_utils.h"
52 #include "net/third_party/quiche/src/quiche/quic/core/crypto/crypto_protocol.h"
53 #include "net/third_party/quiche/src/quiche/quic/core/crypto/quic_decrypter.h"
54 #include "net/third_party/quiche/src/quiche/quic/core/crypto/quic_encrypter.h"
55 #include "net/third_party/quiche/src/quiche/quic/core/http/spdy_utils.h"
56 #include "net/third_party/quiche/src/quiche/quic/core/quic_connection.h"
57 #include "net/third_party/quiche/src/quiche/quic/test_tools/crypto_test_utils.h"
58 #include "net/third_party/quiche/src/quiche/quic/test_tools/mock_clock.h"
59 #include "net/third_party/quiche/src/quiche/quic/test_tools/mock_connection_id_generator.h"
60 #include "net/third_party/quiche/src/quiche/quic/test_tools/mock_random.h"
61 #include "net/third_party/quiche/src/quiche/quic/test_tools/qpack/qpack_test_utils.h"
62 #include "net/third_party/quiche/src/quiche/quic/test_tools/quic_connection_peer.h"
63 #include "net/third_party/quiche/src/quiche/quic/test_tools/quic_session_peer.h"
64 #include "net/third_party/quiche/src/quiche/quic/test_tools/quic_spdy_session_peer.h"
65 #include "net/third_party/quiche/src/quiche/quic/test_tools/quic_test_utils.h"
66 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
67 #include "testing/gmock/include/gmock/gmock.h"
68 #include "testing/gtest/include/gtest/gtest.h"
69 #include "url/scheme_host_port.h"
70 #include "url/url_constants.h"
71
72 namespace net::test {
73
74 namespace {
75
76 const char kUploadData[] = "Really nifty data!";
77 const char kDefaultServerHostName[] = "www.google.com";
78 const uint16_t kDefaultServerPort = 80;
79 // Size of the buffer to be allocated for each read.
80 const size_t kReadBufferSize = 4096;
81
82 enum DelegateMethod {
83 kOnStreamReady,
84 kOnHeadersReceived,
85 kOnTrailersReceived,
86 kOnDataRead,
87 kOnDataSent,
88 kOnFailed
89 };
90
91 class TestDelegateBase : public BidirectionalStreamImpl::Delegate {
92 public:
TestDelegateBase(IOBuffer * read_buf,int read_buf_len)93 TestDelegateBase(IOBuffer* read_buf, int read_buf_len)
94 : TestDelegateBase(read_buf,
95 read_buf_len,
96 std::make_unique<base::OneShotTimer>()) {}
97
TestDelegateBase(IOBuffer * read_buf,int read_buf_len,std::unique_ptr<base::OneShotTimer> timer)98 TestDelegateBase(IOBuffer* read_buf,
99 int read_buf_len,
100 std::unique_ptr<base::OneShotTimer> timer)
101 : read_buf_(read_buf),
102 read_buf_len_(read_buf_len),
103 timer_(std::move(timer)) {
104 loop_ = std::make_unique<base::RunLoop>();
105 }
106
107 TestDelegateBase(const TestDelegateBase&) = delete;
108 TestDelegateBase& operator=(const TestDelegateBase&) = delete;
109
110 ~TestDelegateBase() override = default;
111
OnStreamReady(bool request_headers_sent)112 void OnStreamReady(bool request_headers_sent) override {
113 CHECK(!is_ready_);
114 CHECK(!on_failed_called_);
115 EXPECT_EQ(send_request_headers_automatically_, request_headers_sent);
116 CHECK(!not_expect_callback_);
117 is_ready_ = true;
118 loop_->Quit();
119 }
120
OnHeadersReceived(const spdy::Http2HeaderBlock & response_headers)121 void OnHeadersReceived(
122 const spdy::Http2HeaderBlock& response_headers) override {
123 CHECK(!on_failed_called_);
124 CHECK(!not_expect_callback_);
125
126 response_headers_ = response_headers.Clone();
127 loop_->Quit();
128 }
129
OnDataRead(int bytes_read)130 void OnDataRead(int bytes_read) override {
131 CHECK(!on_failed_called_);
132 CHECK(!not_expect_callback_);
133 CHECK(!callback_.is_null());
134
135 // If read EOF, make sure this callback is after trailers callback.
136 if (bytes_read == 0)
137 EXPECT_TRUE(!trailers_expected_ || trailers_received_);
138 ++on_data_read_count_;
139 CHECK_GE(bytes_read, OK);
140 data_received_.append(read_buf_->data(), bytes_read);
141 std::move(callback_).Run(bytes_read);
142 }
143
OnDataSent()144 void OnDataSent() override {
145 CHECK(!on_failed_called_);
146 CHECK(!not_expect_callback_);
147
148 ++on_data_sent_count_;
149 loop_->Quit();
150 }
151
OnTrailersReceived(const spdy::Http2HeaderBlock & trailers)152 void OnTrailersReceived(const spdy::Http2HeaderBlock& trailers) override {
153 CHECK(!on_failed_called_);
154 CHECK(!not_expect_callback_);
155
156 trailers_received_ = true;
157 trailers_ = trailers.Clone();
158 loop_->Quit();
159 }
160
OnFailed(int error)161 void OnFailed(int error) override {
162 CHECK(!on_failed_called_);
163 CHECK(!not_expect_callback_);
164 CHECK_EQ(OK, error_);
165 CHECK_NE(OK, error);
166
167 on_failed_called_ = true;
168 error_ = error;
169 loop_->Quit();
170 }
171
Start(const BidirectionalStreamRequestInfo * request_info,const NetLogWithSource & net_log,std::unique_ptr<QuicChromiumClientSession::Handle> session)172 void Start(const BidirectionalStreamRequestInfo* request_info,
173 const NetLogWithSource& net_log,
174 std::unique_ptr<QuicChromiumClientSession::Handle> session) {
175 not_expect_callback_ = true;
176 stream_ = std::make_unique<BidirectionalStreamQuicImpl>(std::move(session));
177 stream_->Start(request_info, net_log, send_request_headers_automatically_,
178 this, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS);
179 not_expect_callback_ = false;
180 }
181
SendRequestHeaders()182 void SendRequestHeaders() {
183 not_expect_callback_ = true;
184 stream_->SendRequestHeaders();
185 not_expect_callback_ = false;
186 }
187
SendData(const scoped_refptr<IOBuffer> & data,int length,bool end_of_stream)188 void SendData(const scoped_refptr<IOBuffer>& data,
189 int length,
190 bool end_of_stream) {
191 SendvData({data}, {length}, end_of_stream);
192 }
193
SendvData(const std::vector<scoped_refptr<IOBuffer>> & data,const std::vector<int> & lengths,bool end_of_stream)194 void SendvData(const std::vector<scoped_refptr<IOBuffer>>& data,
195 const std::vector<int>& lengths,
196 bool end_of_stream) {
197 not_expect_callback_ = true;
198 stream_->SendvData(data, lengths, end_of_stream);
199 not_expect_callback_ = false;
200 }
201
202 // Waits until next Delegate callback.
WaitUntilNextCallback(DelegateMethod method)203 void WaitUntilNextCallback(DelegateMethod method) {
204 ASSERT_FALSE(on_failed_called_);
205 bool is_ready = is_ready_;
206 bool headers_received = !response_headers_.empty();
207 bool trailers_received = trailers_received_;
208 int on_data_read_count = on_data_read_count_;
209 int on_data_sent_count = on_data_sent_count_;
210
211 loop_->Run();
212 loop_ = std::make_unique<base::RunLoop>();
213
214 EXPECT_EQ(method == kOnFailed, on_failed_called_);
215 EXPECT_EQ(is_ready || (method == kOnStreamReady), is_ready_);
216 EXPECT_EQ(headers_received || (method == kOnHeadersReceived),
217 !response_headers_.empty());
218 EXPECT_EQ(trailers_received || (method == kOnTrailersReceived),
219 trailers_received_);
220 EXPECT_EQ(on_data_read_count + (method == kOnDataRead ? 1 : 0),
221 on_data_read_count_);
222 EXPECT_EQ(on_data_sent_count + (method == kOnDataSent ? 1 : 0),
223 on_data_sent_count_);
224 }
225
226 // Calls ReadData on the |stream_| and updates |data_received_|.
ReadData(CompletionOnceCallback callback)227 int ReadData(CompletionOnceCallback callback) {
228 not_expect_callback_ = true;
229 int rv = stream_->ReadData(read_buf_.get(), read_buf_len_);
230 not_expect_callback_ = false;
231 if (rv > 0)
232 data_received_.append(read_buf_->data(), rv);
233 if (rv == ERR_IO_PENDING)
234 callback_ = std::move(callback);
235 return rv;
236 }
237
GetProtocol() const238 NextProto GetProtocol() const {
239 if (stream_)
240 return stream_->GetProtocol();
241 return next_proto_;
242 }
243
GetTotalReceivedBytes() const244 int64_t GetTotalReceivedBytes() const {
245 if (stream_)
246 return stream_->GetTotalReceivedBytes();
247 return received_bytes_;
248 }
249
GetTotalSentBytes() const250 int64_t GetTotalSentBytes() const {
251 if (stream_)
252 return stream_->GetTotalSentBytes();
253 return sent_bytes_;
254 }
255
GetLoadTimingInfo(LoadTimingInfo * load_timing_info)256 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) {
257 if (stream_)
258 return stream_->GetLoadTimingInfo(load_timing_info);
259 *load_timing_info = load_timing_info_;
260 return has_load_timing_info_;
261 }
262
DoNotSendRequestHeadersAutomatically()263 void DoNotSendRequestHeadersAutomatically() {
264 send_request_headers_automatically_ = false;
265 }
266
267 // Deletes |stream_|.
DeleteStream()268 void DeleteStream() {
269 next_proto_ = stream_->GetProtocol();
270 received_bytes_ = stream_->GetTotalReceivedBytes();
271 sent_bytes_ = stream_->GetTotalSentBytes();
272 has_load_timing_info_ = stream_->GetLoadTimingInfo(&load_timing_info_);
273 stream_.reset();
274 }
275
set_trailers_expected(bool trailers_expected)276 void set_trailers_expected(bool trailers_expected) {
277 trailers_expected_ = trailers_expected;
278 }
279 // Const getters for internal states.
data_received() const280 const std::string& data_received() const { return data_received_; }
error() const281 int error() const { return error_; }
response_headers() const282 const spdy::Http2HeaderBlock& response_headers() const {
283 return response_headers_;
284 }
trailers() const285 const spdy::Http2HeaderBlock& trailers() const { return trailers_; }
on_data_read_count() const286 int on_data_read_count() const { return on_data_read_count_; }
on_data_sent_count() const287 int on_data_sent_count() const { return on_data_sent_count_; }
on_failed_called() const288 bool on_failed_called() const { return on_failed_called_; }
is_ready() const289 bool is_ready() const { return is_ready_; }
290
291 protected:
292 // Quits |loop_|.
QuitLoop()293 void QuitLoop() { loop_->Quit(); }
294
295 private:
296 std::unique_ptr<BidirectionalStreamQuicImpl> stream_;
297 scoped_refptr<IOBuffer> read_buf_;
298 int read_buf_len_;
299 std::unique_ptr<base::OneShotTimer> timer_;
300 std::string data_received_;
301 std::unique_ptr<base::RunLoop> loop_;
302 spdy::Http2HeaderBlock response_headers_;
303 spdy::Http2HeaderBlock trailers_;
304 NextProto next_proto_ = kProtoUnknown;
305 int64_t received_bytes_ = 0;
306 int64_t sent_bytes_ = 0;
307 bool has_load_timing_info_ = false;
308 LoadTimingInfo load_timing_info_;
309 int error_ = OK;
310 int on_data_read_count_ = 0;
311 int on_data_sent_count_ = 0;
312 // This is to ensure that delegate callback is not invoked synchronously when
313 // calling into |stream_|.
314 bool not_expect_callback_ = false;
315 bool on_failed_called_ = false;
316 CompletionOnceCallback callback_;
317 bool send_request_headers_automatically_ = true;
318 bool is_ready_ = false;
319 bool trailers_expected_ = false;
320 bool trailers_received_ = false;
321 };
322
323 // A delegate that deletes the stream in a particular callback.
324 class DeleteStreamDelegate : public TestDelegateBase {
325 public:
326 // Specifies in which callback the stream can be deleted.
327 enum Phase {
328 ON_STREAM_READY,
329 ON_HEADERS_RECEIVED,
330 ON_DATA_READ,
331 ON_TRAILERS_RECEIVED,
332 ON_FAILED,
333 };
334
DeleteStreamDelegate(IOBuffer * buf,int buf_len,Phase phase)335 DeleteStreamDelegate(IOBuffer* buf, int buf_len, Phase phase)
336 : TestDelegateBase(buf, buf_len), phase_(phase) {}
337
338 DeleteStreamDelegate(const DeleteStreamDelegate&) = delete;
339 DeleteStreamDelegate& operator=(const DeleteStreamDelegate&) = delete;
340
341 ~DeleteStreamDelegate() override = default;
342
OnStreamReady(bool request_headers_sent)343 void OnStreamReady(bool request_headers_sent) override {
344 TestDelegateBase::OnStreamReady(request_headers_sent);
345 if (phase_ == ON_STREAM_READY)
346 DeleteStream();
347 }
348
OnHeadersReceived(const spdy::Http2HeaderBlock & response_headers)349 void OnHeadersReceived(
350 const spdy::Http2HeaderBlock& response_headers) override {
351 // Make a copy of |response_headers| before the stream is deleted, since
352 // the headers are owned by the stream.
353 spdy::Http2HeaderBlock headers_copy = response_headers.Clone();
354 if (phase_ == ON_HEADERS_RECEIVED)
355 DeleteStream();
356 TestDelegateBase::OnHeadersReceived(headers_copy);
357 }
358
OnDataSent()359 void OnDataSent() override { NOTREACHED(); }
360
OnDataRead(int bytes_read)361 void OnDataRead(int bytes_read) override {
362 DCHECK_NE(ON_HEADERS_RECEIVED, phase_);
363 if (phase_ == ON_DATA_READ)
364 DeleteStream();
365 TestDelegateBase::OnDataRead(bytes_read);
366 }
367
OnTrailersReceived(const spdy::Http2HeaderBlock & trailers)368 void OnTrailersReceived(const spdy::Http2HeaderBlock& trailers) override {
369 DCHECK_NE(ON_HEADERS_RECEIVED, phase_);
370 DCHECK_NE(ON_DATA_READ, phase_);
371 // Make a copy of |response_headers| before the stream is deleted, since
372 // the headers are owned by the stream.
373 spdy::Http2HeaderBlock trailers_copy = trailers.Clone();
374 if (phase_ == ON_TRAILERS_RECEIVED)
375 DeleteStream();
376 TestDelegateBase::OnTrailersReceived(trailers_copy);
377 }
378
OnFailed(int error)379 void OnFailed(int error) override {
380 DCHECK_EQ(ON_FAILED, phase_);
381 DeleteStream();
382 TestDelegateBase::OnFailed(error);
383 }
384
385 private:
386 // Indicates in which callback the delegate should cancel or delete the
387 // stream.
388 Phase phase_;
389 };
390
391 } // namespace
392
393 class BidirectionalStreamQuicImplTest
394 : public ::testing::TestWithParam<quic::ParsedQuicVersion>,
395 public WithTaskEnvironment {
396 protected:
397 static const bool kFin = true;
398 static const bool kIncludeVersion = true;
399
400 // Holds a packet to be written to the wire, and the IO mode that should
401 // be used by the mock socket when performing the write.
402 struct PacketToWrite {
PacketToWritenet::test::BidirectionalStreamQuicImplTest::PacketToWrite403 PacketToWrite(IoMode mode, quic::QuicReceivedPacket* packet)
404 : mode(mode), packet(packet) {}
PacketToWritenet::test::BidirectionalStreamQuicImplTest::PacketToWrite405 PacketToWrite(IoMode mode, int rv) : mode(mode), packet(nullptr), rv(rv) {}
406 IoMode mode;
407 raw_ptr<quic::QuicReceivedPacket> packet;
408 int rv;
409 };
410
BidirectionalStreamQuicImplTest()411 BidirectionalStreamQuicImplTest()
412 : version_(GetParam()),
413 crypto_config_(
414 quic::test::crypto_test_utils::ProofVerifierForTesting()),
415 read_buffer_(base::MakeRefCounted<IOBufferWithSize>(4096)),
416 connection_id_(quic::test::TestConnectionId(2)),
417 stream_id_(GetNthClientInitiatedBidirectionalStreamId(0)),
418 client_maker_(version_,
419 connection_id_,
420 &clock_,
421 kDefaultServerHostName,
422 quic::Perspective::IS_CLIENT),
423 server_maker_(version_,
424 connection_id_,
425 &clock_,
426 kDefaultServerHostName,
427 quic::Perspective::IS_SERVER,
428 false),
429 printer_(version_),
430 destination_(url::kHttpsScheme,
431 kDefaultServerHostName,
432 kDefaultServerPort) {
433 quic::QuicEnableVersion(version_);
434 FLAGS_quic_enable_http3_grease_randomness = false;
435 IPAddress ip(192, 0, 2, 33);
436 peer_addr_ = IPEndPoint(ip, 443);
437 self_addr_ = IPEndPoint(ip, 8435);
438 clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(20));
439 }
440
~BidirectionalStreamQuicImplTest()441 ~BidirectionalStreamQuicImplTest() override {
442 if (session_) {
443 session_->CloseSessionOnError(
444 ERR_ABORTED, quic::QUIC_INTERNAL_ERROR,
445 quic::ConnectionCloseBehavior::SILENT_CLOSE);
446 }
447 for (auto& write : writes_) {
448 delete write.packet;
449 }
450 }
451
TearDown()452 void TearDown() override {
453 if (socket_data_) {
454 EXPECT_TRUE(socket_data_->AllReadDataConsumed());
455 EXPECT_TRUE(socket_data_->AllWriteDataConsumed());
456 }
457 }
458
459 // Adds a packet to the list of expected writes.
AddWrite(std::unique_ptr<quic::QuicReceivedPacket> packet)460 void AddWrite(std::unique_ptr<quic::QuicReceivedPacket> packet) {
461 writes_.emplace_back(SYNCHRONOUS, packet.release());
462 }
463
464 // Adds a write error to the list of expected writes.
AddWriteError(IoMode mode,int rv)465 void AddWriteError(IoMode mode, int rv) { writes_.emplace_back(mode, rv); }
466
ProcessPacket(std::unique_ptr<quic::QuicReceivedPacket> packet)467 void ProcessPacket(std::unique_ptr<quic::QuicReceivedPacket> packet) {
468 connection_->ProcessUdpPacket(ToQuicSocketAddress(self_addr_),
469 ToQuicSocketAddress(peer_addr_), *packet);
470 }
471
472 // Configures the test fixture to use the list of expected writes.
Initialize()473 void Initialize() {
474 crypto_client_stream_factory_.set_handshake_mode(
475 MockCryptoClientStream::ZERO_RTT);
476 mock_writes_ = std::make_unique<MockWrite[]>(writes_.size());
477 for (size_t i = 0; i < writes_.size(); i++) {
478 if (writes_[i].packet == nullptr) {
479 mock_writes_[i] = MockWrite(writes_[i].mode, writes_[i].rv, i);
480 } else {
481 mock_writes_[i] = MockWrite(writes_[i].mode, writes_[i].packet->data(),
482 writes_[i].packet->length());
483 }
484 }
485
486 socket_data_ = std::make_unique<StaticSocketDataProvider>(
487 base::span<MockRead>(),
488 base::make_span(mock_writes_.get(), writes_.size()));
489 socket_data_->set_printer(&printer_);
490
491 auto socket = std::make_unique<MockUDPClientSocket>(socket_data_.get(),
492 NetLog::Get());
493 socket->Connect(peer_addr_);
494 runner_ = base::MakeRefCounted<TestTaskRunner>(&clock_);
495 helper_ = std::make_unique<QuicChromiumConnectionHelper>(
496 &clock_, &random_generator_);
497 alarm_factory_ =
498 std::make_unique<QuicChromiumAlarmFactory>(runner_.get(), &clock_);
499 connection_ = new quic::QuicConnection(
500 connection_id_, quic::QuicSocketAddress(),
501 ToQuicSocketAddress(peer_addr_), helper_.get(), alarm_factory_.get(),
502 new QuicChromiumPacketWriter(socket.get(), runner_.get()),
503 true /* owns_writer */, quic::Perspective::IS_CLIENT,
504 quic::test::SupportedVersions(version_), connection_id_generator_);
505 if (connection_->version().KnowsWhichDecrypterToUse()) {
506 connection_->InstallDecrypter(
507 quic::ENCRYPTION_FORWARD_SECURE,
508 std::make_unique<quic::test::StrictTaggingDecrypter>(
509 quic::ENCRYPTION_FORWARD_SECURE));
510 }
511 base::TimeTicks dns_end = base::TimeTicks::Now();
512 base::TimeTicks dns_start = dns_end - base::Milliseconds(1);
513
514 session_ = std::make_unique<QuicChromiumClientSession>(
515 connection_, std::move(socket),
516 /*stream_factory=*/nullptr, &crypto_client_stream_factory_, &clock_,
517 &transport_security_state_, &ssl_config_service_,
518 base::WrapUnique(static_cast<QuicServerInfo*>(nullptr)),
519 QuicSessionKey(kDefaultServerHostName, kDefaultServerPort,
520 PRIVACY_MODE_DISABLED, SocketTag(),
521 NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
522 /*require_dns_https_alpn=*/false),
523 /*require_confirmation=*/false,
524 /*migrate_session_early_v2=*/false,
525 /*migrate_session_on_network_change_v2=*/false,
526 /*default_network=*/handles::kInvalidNetworkHandle,
527 quic::QuicTime::Delta::FromMilliseconds(
528 kDefaultRetransmittableOnWireTimeout.InMilliseconds()),
529 /*migrate_idle_session=*/false, /*allow_port_migration=*/false,
530 kDefaultIdleSessionMigrationPeriod, kMaxTimeOnNonDefaultNetwork,
531 kMaxMigrationsToNonDefaultNetworkOnWriteError,
532 kMaxMigrationsToNonDefaultNetworkOnPathDegrading,
533 kQuicYieldAfterPacketsRead,
534 quic::QuicTime::Delta::FromMilliseconds(
535 kQuicYieldAfterDurationMilliseconds),
536 /*cert_verify_flags=*/0, quic::test::DefaultQuicConfig(),
537 std::make_unique<TestQuicCryptoClientConfigHandle>(&crypto_config_),
538 "CONNECTION_UNKNOWN", dns_start, dns_end,
539 std::make_unique<quic::QuicClientPushPromiseIndex>(), nullptr,
540 base::DefaultTickClock::GetInstance(),
541 base::SingleThreadTaskRunner::GetCurrentDefault().get(),
542 /*socket_performance_watcher=*/nullptr, HostResolverEndpointResult(),
543 NetLog::Get());
544 session_->Initialize();
545
546 // Blackhole QPACK decoder stream instead of constructing mock writes.
547 session_->qpack_decoder()->set_qpack_stream_sender_delegate(
548 &noop_qpack_stream_sender_delegate_);
549
550 TestCompletionCallback callback;
551 session_->CryptoConnect(callback.callback());
552 EXPECT_TRUE(session_->IsEncryptionEstablished());
553 }
554
ConfirmHandshake()555 void ConfirmHandshake() {
556 crypto_client_stream_factory_.last_stream()
557 ->NotifySessionOneRttKeyAvailable();
558 }
559
SetRequest(const std::string & method,const std::string & path,RequestPriority priority)560 void SetRequest(const std::string& method,
561 const std::string& path,
562 RequestPriority priority) {
563 request_headers_ = client_maker_.GetRequestHeaders(method, "http", path);
564 }
565
ConstructResponseHeaders(const std::string & response_code)566 spdy::Http2HeaderBlock ConstructResponseHeaders(
567 const std::string& response_code) {
568 return server_maker_.GetResponseHeaders(response_code);
569 }
570
ConstructServerDataPacket(uint64_t packet_number,bool should_include_version,bool fin,absl::string_view data)571 std::unique_ptr<quic::QuicReceivedPacket> ConstructServerDataPacket(
572 uint64_t packet_number,
573 bool should_include_version,
574 bool fin,
575 absl::string_view data) {
576 std::unique_ptr<quic::QuicReceivedPacket> packet(
577 server_maker_.MakeDataPacket(packet_number, stream_id_,
578 should_include_version, fin, data));
579 DVLOG(2) << "packet(" << packet_number << "): " << std::endl
580 << quiche::QuicheTextUtils::HexDump(packet->AsStringPiece());
581 return packet;
582 }
583
ConstructClientDataPacket(bool should_include_version,bool fin,absl::string_view data)584 std::unique_ptr<quic::QuicReceivedPacket> ConstructClientDataPacket(
585 bool should_include_version,
586 bool fin,
587 absl::string_view data) {
588 return client_maker_.MakeDataPacket(++packet_number_, stream_id_,
589 should_include_version, fin, data);
590 }
591
ConstructRequestHeadersPacket(bool fin,RequestPriority request_priority,size_t * spdy_headers_frame_length)592 std::unique_ptr<quic::QuicReceivedPacket> ConstructRequestHeadersPacket(
593 bool fin,
594 RequestPriority request_priority,
595 size_t* spdy_headers_frame_length) {
596 return ConstructRequestHeadersPacketInner(stream_id_, fin, request_priority,
597 spdy_headers_frame_length);
598 }
599
ConstructRequestHeadersPacketInner(quic::QuicStreamId stream_id,bool fin,RequestPriority request_priority,size_t * spdy_headers_frame_length)600 std::unique_ptr<quic::QuicReceivedPacket> ConstructRequestHeadersPacketInner(
601 quic::QuicStreamId stream_id,
602 bool fin,
603 RequestPriority request_priority,
604 size_t* spdy_headers_frame_length) {
605 spdy::SpdyPriority priority =
606 ConvertRequestPriorityToQuicPriority(request_priority);
607 std::unique_ptr<quic::QuicReceivedPacket> packet(
608 client_maker_.MakeRequestHeadersPacket(
609 ++packet_number_, stream_id, kIncludeVersion, fin, priority,
610 std::move(request_headers_), spdy_headers_frame_length));
611 DVLOG(2) << "packet(" << packet_number_ << "): " << std::endl
612 << quiche::QuicheTextUtils::HexDump(packet->AsStringPiece());
613 return packet;
614 }
615
616 std::unique_ptr<quic::QuicReceivedPacket>
ConstructRequestHeadersAndMultipleDataFramesPacket(bool fin,RequestPriority request_priority,size_t * spdy_headers_frame_length,const std::vector<std::string> & data)617 ConstructRequestHeadersAndMultipleDataFramesPacket(
618 bool fin,
619 RequestPriority request_priority,
620 size_t* spdy_headers_frame_length,
621 const std::vector<std::string>& data) {
622 spdy::SpdyPriority priority =
623 ConvertRequestPriorityToQuicPriority(request_priority);
624 std::unique_ptr<quic::QuicReceivedPacket> packet(
625 client_maker_.MakeRequestHeadersAndMultipleDataFramesPacket(
626 ++packet_number_, stream_id_, kIncludeVersion, fin, priority,
627 std::move(request_headers_), spdy_headers_frame_length, data));
628 DVLOG(2) << "packet(" << packet_number_ << "): " << std::endl
629 << quiche::QuicheTextUtils::HexDump(packet->AsStringPiece());
630 return packet;
631 }
632
ConstructResponseHeadersPacket(uint64_t packet_number,bool fin,spdy::Http2HeaderBlock response_headers,size_t * spdy_headers_frame_length)633 std::unique_ptr<quic::QuicReceivedPacket> ConstructResponseHeadersPacket(
634 uint64_t packet_number,
635 bool fin,
636 spdy::Http2HeaderBlock response_headers,
637 size_t* spdy_headers_frame_length) {
638 return ConstructResponseHeadersPacketInner(packet_number, stream_id_, fin,
639 std::move(response_headers),
640 spdy_headers_frame_length);
641 }
642
ConstructResponseHeadersPacketInner(uint64_t packet_number,quic::QuicStreamId stream_id,bool fin,spdy::Http2HeaderBlock response_headers,size_t * spdy_headers_frame_length)643 std::unique_ptr<quic::QuicReceivedPacket> ConstructResponseHeadersPacketInner(
644 uint64_t packet_number,
645 quic::QuicStreamId stream_id,
646 bool fin,
647 spdy::Http2HeaderBlock response_headers,
648 size_t* spdy_headers_frame_length) {
649 return server_maker_.MakeResponseHeadersPacket(
650 packet_number, stream_id, !kIncludeVersion, fin,
651 std::move(response_headers), spdy_headers_frame_length);
652 }
653
ConstructResponseTrailersPacket(uint64_t packet_number,bool fin,spdy::Http2HeaderBlock trailers,size_t * spdy_headers_frame_length)654 std::unique_ptr<quic::QuicReceivedPacket> ConstructResponseTrailersPacket(
655 uint64_t packet_number,
656 bool fin,
657 spdy::Http2HeaderBlock trailers,
658 size_t* spdy_headers_frame_length) {
659 return server_maker_.MakeResponseHeadersPacket(
660 packet_number, stream_id_, !kIncludeVersion, fin, std::move(trailers),
661 spdy_headers_frame_length);
662 }
663
ConstructClientRstStreamPacket()664 std::unique_ptr<quic::QuicReceivedPacket> ConstructClientRstStreamPacket() {
665 return ConstructRstStreamCancelledPacket(++packet_number_, !kIncludeVersion,
666 &client_maker_);
667 }
668
ConstructServerRstStreamPacket(uint64_t packet_number)669 std::unique_ptr<quic::QuicReceivedPacket> ConstructServerRstStreamPacket(
670 uint64_t packet_number) {
671 return ConstructRstStreamCancelledPacket(packet_number, !kIncludeVersion,
672 &server_maker_);
673 }
674
675 std::unique_ptr<quic::QuicReceivedPacket>
ConstructClientEarlyRstStreamPacket()676 ConstructClientEarlyRstStreamPacket() {
677 return ConstructRstStreamCancelledPacket(++packet_number_, kIncludeVersion,
678 &client_maker_);
679 }
680
ConstructRstStreamCancelledPacket(uint64_t packet_number,bool include_version,QuicTestPacketMaker * maker)681 std::unique_ptr<quic::QuicReceivedPacket> ConstructRstStreamCancelledPacket(
682 uint64_t packet_number,
683 bool include_version,
684 QuicTestPacketMaker* maker) {
685 std::unique_ptr<quic::QuicReceivedPacket> packet(maker->MakeRstPacket(
686 packet_number, include_version, stream_id_, quic::QUIC_STREAM_CANCELLED,
687 /*include_stop_sending_if_v99=*/true));
688 DVLOG(2) << "packet(" << packet_number << "): " << std::endl
689 << quiche::QuicheTextUtils::HexDump(packet->AsStringPiece());
690 return packet;
691 }
692
693 std::unique_ptr<quic::QuicReceivedPacket>
ConstructClientAckAndRstStreamPacket(uint64_t largest_received,uint64_t smallest_received)694 ConstructClientAckAndRstStreamPacket(uint64_t largest_received,
695 uint64_t smallest_received) {
696 return client_maker_.MakeAckAndRstPacket(
697 ++packet_number_, !kIncludeVersion, stream_id_,
698 quic::QUIC_STREAM_CANCELLED, largest_received, smallest_received);
699 }
700
ConstructAckAndDataPacket(uint64_t packet_number,bool should_include_version,uint64_t largest_received,uint64_t smallest_received,bool fin,absl::string_view data,QuicTestPacketMaker * maker)701 std::unique_ptr<quic::QuicReceivedPacket> ConstructAckAndDataPacket(
702 uint64_t packet_number,
703 bool should_include_version,
704 uint64_t largest_received,
705 uint64_t smallest_received,
706 bool fin,
707 absl::string_view data,
708 QuicTestPacketMaker* maker) {
709 std::unique_ptr<quic::QuicReceivedPacket> packet(
710 maker->MakeAckAndDataPacket(packet_number, should_include_version,
711 stream_id_, largest_received,
712 smallest_received, fin, data));
713 DVLOG(2) << "packet(" << packet_number << "): " << std::endl
714 << quiche::QuicheTextUtils::HexDump(packet->AsStringPiece());
715 return packet;
716 }
717
ConstructClientAckPacket(uint64_t largest_received,uint64_t smallest_received)718 std::unique_ptr<quic::QuicReceivedPacket> ConstructClientAckPacket(
719 uint64_t largest_received,
720 uint64_t smallest_received) {
721 return client_maker_.MakeAckPacket(++packet_number_, largest_received,
722 smallest_received);
723 }
724
ConstructServerAckPacket(uint64_t packet_number,uint64_t largest_received,uint64_t smallest_received,uint64_t least_unacked)725 std::unique_ptr<quic::QuicReceivedPacket> ConstructServerAckPacket(
726 uint64_t packet_number,
727 uint64_t largest_received,
728 uint64_t smallest_received,
729 uint64_t least_unacked) {
730 return server_maker_.MakeAckPacket(packet_number, largest_received,
731 smallest_received, least_unacked);
732 }
733
ConstructInitialSettingsPacket()734 std::unique_ptr<quic::QuicReceivedPacket> ConstructInitialSettingsPacket() {
735 return client_maker_.MakeInitialSettingsPacket(++packet_number_);
736 }
737
ExpectLoadTimingValid(const LoadTimingInfo & load_timing_info,bool session_reused)738 void ExpectLoadTimingValid(const LoadTimingInfo& load_timing_info,
739 bool session_reused) {
740 EXPECT_EQ(session_reused, load_timing_info.socket_reused);
741
742 if (session_reused) {
743 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
744 } else {
745 ExpectConnectTimingHasTimes(
746 load_timing_info.connect_timing,
747 CONNECT_TIMING_HAS_SSL_TIMES | CONNECT_TIMING_HAS_DNS_TIMES);
748 }
749 ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
750 }
751
net_log_observer() const752 const RecordingNetLogObserver& net_log_observer() const {
753 return net_log_observer_;
754 }
755
net_log_with_source() const756 const NetLogWithSource& net_log_with_source() const {
757 return net_log_with_source_;
758 }
759
session() const760 QuicChromiumClientSession* session() const { return session_.get(); }
761
GetNthClientInitiatedBidirectionalStreamId(int n)762 quic::QuicStreamId GetNthClientInitiatedBidirectionalStreamId(int n) {
763 return quic::test::GetNthClientInitiatedBidirectionalStreamId(
764 version_.transport_version, n);
765 }
766
ConstructDataHeader(size_t body_len)767 std::string ConstructDataHeader(size_t body_len) {
768 quiche::QuicheBuffer buffer = quic::HttpEncoder::SerializeDataFrameHeader(
769 body_len, quiche::SimpleBufferAllocator::Get());
770 return std::string(buffer.data(), buffer.size());
771 }
772
773 protected:
774 quic::test::QuicFlagSaver saver_;
775 const quic::ParsedQuicVersion version_;
776 RecordingNetLogObserver net_log_observer_;
777 NetLogWithSource net_log_with_source_{
778 NetLogWithSource::Make(NetLogSourceType::NONE)};
779 scoped_refptr<TestTaskRunner> runner_;
780 std::unique_ptr<MockWrite[]> mock_writes_;
781 quic::MockClock clock_;
782 raw_ptr<quic::QuicConnection> connection_;
783 std::unique_ptr<QuicChromiumConnectionHelper> helper_;
784 std::unique_ptr<QuicChromiumAlarmFactory> alarm_factory_;
785 TransportSecurityState transport_security_state_;
786 SSLConfigServiceDefaults ssl_config_service_;
787 std::unique_ptr<QuicChromiumClientSession> session_;
788 quic::QuicCryptoClientConfig crypto_config_;
789 HttpRequestHeaders headers_;
790 HttpResponseInfo response_;
791 scoped_refptr<IOBufferWithSize> read_buffer_;
792 spdy::Http2HeaderBlock request_headers_;
793 const quic::QuicConnectionId connection_id_;
794 const quic::QuicStreamId stream_id_;
795 QuicTestPacketMaker client_maker_;
796 uint64_t packet_number_ = 0;
797 QuicTestPacketMaker server_maker_;
798 IPEndPoint self_addr_;
799 IPEndPoint peer_addr_;
800 quic::test::MockRandom random_generator_{0};
801 QuicPacketPrinter printer_;
802 MockCryptoClientStreamFactory crypto_client_stream_factory_;
803 std::unique_ptr<StaticSocketDataProvider> socket_data_;
804 std::vector<PacketToWrite> writes_;
805 url::SchemeHostPort destination_;
806 quic::test::MockConnectionIdGenerator connection_id_generator_;
807 quic::test::NoopQpackStreamSenderDelegate noop_qpack_stream_sender_delegate_;
808 };
809
810 INSTANTIATE_TEST_SUITE_P(Version,
811 BidirectionalStreamQuicImplTest,
812 ::testing::ValuesIn(AllSupportedQuicVersions()),
813 ::testing::PrintToStringParamName());
814
TEST_P(BidirectionalStreamQuicImplTest,GetRequest)815 TEST_P(BidirectionalStreamQuicImplTest, GetRequest) {
816 SetRequest("GET", "/", DEFAULT_PRIORITY);
817 size_t spdy_request_headers_frame_length;
818 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
819 AddWrite(ConstructInitialSettingsPacket());
820 AddWrite(ConstructRequestHeadersPacketInner(
821 GetNthClientInitiatedBidirectionalStreamId(0), kFin, DEFAULT_PRIORITY,
822 &spdy_request_headers_frame_length));
823 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
824 AddWrite(ConstructClientAckPacket(3, 1));
825
826 Initialize();
827
828 BidirectionalStreamRequestInfo request;
829 request.method = "GET";
830 request.url = GURL("http://www.google.com/");
831 request.end_stream_on_headers = true;
832 request.priority = DEFAULT_PRIORITY;
833
834 scoped_refptr<IOBuffer> read_buffer =
835 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
836 auto delegate =
837 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
838 delegate->set_trailers_expected(true);
839 delegate->Start(&request, net_log_with_source(),
840 session()->CreateHandle(destination_));
841 delegate->WaitUntilNextCallback(kOnStreamReady);
842 ConfirmHandshake();
843
844 // Server acks the request.
845 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
846
847 // Server sends the response headers.
848 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
849
850 size_t spdy_response_headers_frame_length;
851 ProcessPacket(
852 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
853 &spdy_response_headers_frame_length));
854
855 delegate->WaitUntilNextCallback(kOnHeadersReceived);
856 LoadTimingInfo load_timing_info;
857 EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
858 ExpectLoadTimingValid(load_timing_info, /*session_reused=*/false);
859 TestCompletionCallback cb;
860 int rv = delegate->ReadData(cb.callback());
861 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
862 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
863 const char kResponseBody[] = "Hello world!";
864 // Server sends data.
865 std::string header = ConstructDataHeader(strlen(kResponseBody));
866 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
867 header + kResponseBody));
868 EXPECT_EQ(12, cb.WaitForResult());
869
870 EXPECT_EQ(std::string(kResponseBody), delegate->data_received());
871 TestCompletionCallback cb2;
872 EXPECT_THAT(delegate->ReadData(cb2.callback()), IsError(ERR_IO_PENDING));
873
874 spdy::Http2HeaderBlock trailers;
875 size_t spdy_trailers_frame_length;
876 trailers["foo"] = "bar";
877 // Server sends trailers.
878 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
879 &spdy_trailers_frame_length));
880
881 delegate->WaitUntilNextCallback(kOnTrailersReceived);
882 EXPECT_THAT(cb2.WaitForResult(), IsOk());
883 EXPECT_EQ(trailers, delegate->trailers());
884
885 EXPECT_THAT(delegate->ReadData(cb2.callback()), IsOk());
886 base::RunLoop().RunUntilIdle();
887
888 EXPECT_EQ(2, delegate->on_data_read_count());
889 EXPECT_EQ(0, delegate->on_data_sent_count());
890 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
891 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
892 delegate->GetTotalSentBytes());
893 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
894 strlen(kResponseBody) + header.length() +
895 spdy_trailers_frame_length),
896 delegate->GetTotalReceivedBytes());
897 // Check that NetLog was filled as expected.
898 auto entries = net_log_observer().GetEntries();
899 size_t pos = ExpectLogContainsSomewhere(
900 entries, /*min_offset=*/0,
901 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
902 NetLogEventPhase::NONE);
903 pos = ExpectLogContainsSomewhere(
904 entries, /*min_offset=*/pos,
905 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
906 NetLogEventPhase::NONE);
907 ExpectLogContainsSomewhere(
908 entries, /*min_offset=*/pos,
909 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
910 NetLogEventPhase::NONE);
911 }
912
TEST_P(BidirectionalStreamQuicImplTest,LoadTimingTwoRequests)913 TEST_P(BidirectionalStreamQuicImplTest, LoadTimingTwoRequests) {
914 SetRequest("GET", "/", DEFAULT_PRIORITY);
915 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
916 AddWrite(ConstructInitialSettingsPacket());
917 AddWrite(ConstructRequestHeadersPacketInner(
918 GetNthClientInitiatedBidirectionalStreamId(0), kFin, DEFAULT_PRIORITY,
919 nullptr));
920 // SetRequest() again for second request as |request_headers_| was moved.
921 SetRequest("GET", "/", DEFAULT_PRIORITY);
922 AddWrite(ConstructRequestHeadersPacketInner(
923 GetNthClientInitiatedBidirectionalStreamId(1), kFin, DEFAULT_PRIORITY,
924 nullptr));
925 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
926 AddWrite(ConstructClientAckPacket(3, 1));
927 Initialize();
928
929 BidirectionalStreamRequestInfo request;
930 request.method = "GET";
931 request.url = GURL("http://www.google.com/");
932 request.end_stream_on_headers = true;
933 request.priority = DEFAULT_PRIORITY;
934
935 // Start first request.
936 scoped_refptr<IOBuffer> read_buffer =
937 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
938 auto delegate =
939 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
940 delegate->Start(&request, net_log_with_source(),
941 session()->CreateHandle(destination_));
942
943 // Start second request.
944 scoped_refptr<IOBuffer> read_buffer2 =
945 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
946 auto delegate2 =
947 std::make_unique<TestDelegateBase>(read_buffer2.get(), kReadBufferSize);
948 delegate2->Start(&request, net_log_with_source(),
949 session()->CreateHandle(destination_));
950
951 delegate->WaitUntilNextCallback(kOnStreamReady);
952 delegate2->WaitUntilNextCallback(kOnStreamReady);
953
954 ConfirmHandshake();
955 // Server acks the request.
956 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
957
958 // Server sends the response headers.
959 ProcessPacket(ConstructResponseHeadersPacketInner(
960 2, GetNthClientInitiatedBidirectionalStreamId(0), kFin,
961 ConstructResponseHeaders("200"), nullptr));
962
963 ProcessPacket(ConstructResponseHeadersPacketInner(
964 3, GetNthClientInitiatedBidirectionalStreamId(1), kFin,
965 ConstructResponseHeaders("200"), nullptr));
966
967 delegate->WaitUntilNextCallback(kOnHeadersReceived);
968 delegate2->WaitUntilNextCallback(kOnHeadersReceived);
969
970 LoadTimingInfo load_timing_info;
971 EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
972 LoadTimingInfo load_timing_info2;
973 EXPECT_TRUE(delegate2->GetLoadTimingInfo(&load_timing_info2));
974 ExpectLoadTimingValid(load_timing_info, /*session_reused=*/false);
975 ExpectLoadTimingValid(load_timing_info2, /*session_reused=*/true);
976 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
977 EXPECT_EQ("200", delegate2->response_headers().find(":status")->second);
978 // No response body. ReadData() should return OK synchronously.
979 TestCompletionCallback dummy_callback;
980 EXPECT_EQ(OK, delegate->ReadData(dummy_callback.callback()));
981 EXPECT_EQ(OK, delegate2->ReadData(dummy_callback.callback()));
982 }
983
984 // Tests that when request headers are not delayed, only data buffers are
985 // coalesced.
TEST_P(BidirectionalStreamQuicImplTest,CoalesceDataBuffersNotHeadersFrame)986 TEST_P(BidirectionalStreamQuicImplTest, CoalesceDataBuffersNotHeadersFrame) {
987 SetRequest("POST", "/", DEFAULT_PRIORITY);
988 size_t spdy_request_headers_frame_length;
989 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
990 AddWrite(ConstructInitialSettingsPacket());
991 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
992 const std::string kBody1 = "here are some data";
993 const std::string kBody2 = "data keep coming";
994 std::string header = ConstructDataHeader(kBody1.length());
995 std::string header2 = ConstructDataHeader(kBody2.length());
996 std::vector<std::string> two_writes = {kBody1, kBody2};
997 AddWrite(ConstructRequestHeadersPacketInner(
998 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
999 &spdy_request_headers_frame_length));
1000 AddWrite(ConstructClientDataPacket(kIncludeVersion, !kFin,
1001 header + kBody1 + header2 + kBody2));
1002
1003 // Ack server's data packet.
1004 AddWrite(ConstructClientAckPacket(3, 1));
1005 const std::string kBody3 = "hello there";
1006 const std::string kBody4 = "another piece of small data";
1007 const std::string kBody5 = "really small";
1008 std::string header3 = ConstructDataHeader(kBody3.length());
1009 std::string header4 = ConstructDataHeader(kBody4.length());
1010 std::string header5 = ConstructDataHeader(kBody5.length());
1011 AddWrite(ConstructClientDataPacket(
1012 !kIncludeVersion, kFin,
1013 header3 + kBody3 + header4 + kBody4 + header5 + kBody5));
1014
1015 Initialize();
1016
1017 BidirectionalStreamRequestInfo request;
1018 request.method = "POST";
1019 request.url = GURL("http://www.google.com/");
1020 request.end_stream_on_headers = false;
1021 request.priority = DEFAULT_PRIORITY;
1022
1023 scoped_refptr<IOBuffer> read_buffer =
1024 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1025 auto delegate =
1026 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1027 delegate->DoNotSendRequestHeadersAutomatically();
1028 delegate->Start(&request, net_log_with_source(),
1029 session()->CreateHandle(destination_));
1030 EXPECT_FALSE(delegate->is_ready());
1031 ConfirmHandshake();
1032 delegate->WaitUntilNextCallback(kOnStreamReady);
1033 EXPECT_TRUE(delegate->is_ready());
1034
1035 // Sends request headers separately, which causes them to be sent in a
1036 // separate packet.
1037 delegate->SendRequestHeaders();
1038 // Send a Data packet.
1039 scoped_refptr<StringIOBuffer> buf1 =
1040 base::MakeRefCounted<StringIOBuffer>(kBody1);
1041 scoped_refptr<StringIOBuffer> buf2 =
1042 base::MakeRefCounted<StringIOBuffer>(kBody2);
1043
1044 std::vector<int> lengths = {buf1->size(), buf2->size()};
1045 delegate->SendvData({buf1, buf2}, lengths, !kFin);
1046 delegate->WaitUntilNextCallback(kOnDataSent);
1047
1048 // Server acks the request.
1049 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1050
1051 // Server sends the response headers.
1052 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1053 size_t spdy_response_headers_frame_length;
1054 ProcessPacket(
1055 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1056 &spdy_response_headers_frame_length));
1057
1058 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1059 TestCompletionCallback cb;
1060 int rv = delegate->ReadData(cb.callback());
1061 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1062 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1063 const char kResponseBody[] = "Hello world!";
1064 std::string header6 = ConstructDataHeader(strlen(kResponseBody));
1065 // Server sends data.
1066 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
1067 header6 + kResponseBody));
1068
1069 EXPECT_EQ(static_cast<int>(strlen(kResponseBody)), cb.WaitForResult());
1070
1071 // Send a second Data packet.
1072 scoped_refptr<StringIOBuffer> buf3 =
1073 base::MakeRefCounted<StringIOBuffer>(kBody3);
1074 scoped_refptr<StringIOBuffer> buf4 =
1075 base::MakeRefCounted<StringIOBuffer>(kBody4);
1076 scoped_refptr<StringIOBuffer> buf5 =
1077 base::MakeRefCounted<StringIOBuffer>(kBody5);
1078
1079 delegate->SendvData({buf3, buf4, buf5},
1080 {buf3->size(), buf4->size(), buf5->size()}, kFin);
1081 delegate->WaitUntilNextCallback(kOnDataSent);
1082
1083 size_t spdy_trailers_frame_length;
1084 spdy::Http2HeaderBlock trailers;
1085 trailers["foo"] = "bar";
1086 // Server sends trailers.
1087 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
1088 &spdy_trailers_frame_length));
1089
1090 delegate->WaitUntilNextCallback(kOnTrailersReceived);
1091 EXPECT_EQ(trailers, delegate->trailers());
1092 EXPECT_THAT(delegate->ReadData(cb.callback()), IsOk());
1093
1094 EXPECT_EQ(1, delegate->on_data_read_count());
1095 EXPECT_EQ(2, delegate->on_data_sent_count());
1096 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1097 EXPECT_EQ(static_cast<int64_t>(
1098 spdy_request_headers_frame_length + kBody1.length() +
1099 kBody2.length() + kBody3.length() + kBody4.length() +
1100 kBody5.length() + header.length() + header2.length() +
1101 header3.length() + header4.length() + header5.length()),
1102 delegate->GetTotalSentBytes());
1103 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
1104 strlen(kResponseBody) + header6.length() +
1105 spdy_trailers_frame_length),
1106 delegate->GetTotalReceivedBytes());
1107 }
1108
1109 // Tests that when request headers are delayed, SendData triggers coalescing of
1110 // request headers with data buffers.
TEST_P(BidirectionalStreamQuicImplTest,SendDataCoalesceDataBufferAndHeaderFrame)1111 TEST_P(BidirectionalStreamQuicImplTest,
1112 SendDataCoalesceDataBufferAndHeaderFrame) {
1113 SetRequest("POST", "/", DEFAULT_PRIORITY);
1114 size_t spdy_request_headers_frame_length;
1115 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1116 AddWrite(ConstructInitialSettingsPacket());
1117 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1118 const char kBody1[] = "here are some data";
1119 std::string header = ConstructDataHeader(strlen(kBody1));
1120 AddWrite(ConstructRequestHeadersAndMultipleDataFramesPacket(
1121 !kFin, DEFAULT_PRIORITY, &spdy_request_headers_frame_length,
1122 {header, kBody1}));
1123
1124 // Ack server's data packet.
1125 AddWrite(ConstructClientAckPacket(3, 1));
1126 const char kBody2[] = "really small";
1127 std::string header2 = ConstructDataHeader(strlen(kBody2));
1128 AddWrite(ConstructClientDataPacket(!kIncludeVersion, kFin,
1129 header2 + std::string(kBody2)));
1130
1131 Initialize();
1132
1133 BidirectionalStreamRequestInfo request;
1134 request.method = "POST";
1135 request.url = GURL("http://www.google.com/");
1136 request.end_stream_on_headers = false;
1137 request.priority = DEFAULT_PRIORITY;
1138
1139 scoped_refptr<IOBuffer> read_buffer =
1140 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1141 auto delegate =
1142 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1143 delegate->DoNotSendRequestHeadersAutomatically();
1144 delegate->Start(&request, net_log_with_source(),
1145 session()->CreateHandle(destination_));
1146 ConfirmHandshake();
1147 delegate->WaitUntilNextCallback(kOnStreamReady);
1148
1149 // Send a Data packet.
1150 scoped_refptr<StringIOBuffer> buf1 =
1151 base::MakeRefCounted<StringIOBuffer>(kBody1);
1152
1153 delegate->SendData(buf1, buf1->size(), false);
1154 delegate->WaitUntilNextCallback(kOnDataSent);
1155
1156 // Server acks the request.
1157 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1158
1159 // Server sends the response headers.
1160 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1161 size_t spdy_response_headers_frame_length;
1162 ProcessPacket(
1163 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1164 &spdy_response_headers_frame_length));
1165
1166 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1167 TestCompletionCallback cb;
1168 int rv = delegate->ReadData(cb.callback());
1169 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1170 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1171 const char kResponseBody[] = "Hello world!";
1172 // Server sends data.
1173 std::string header3 = ConstructDataHeader(strlen(kResponseBody));
1174 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
1175 header3 + kResponseBody));
1176
1177 EXPECT_EQ(static_cast<int>(strlen(kResponseBody)), cb.WaitForResult());
1178
1179 // Send a second Data packet.
1180 scoped_refptr<StringIOBuffer> buf2 =
1181 base::MakeRefCounted<StringIOBuffer>(kBody2);
1182
1183 delegate->SendData(buf2, buf2->size(), true);
1184 delegate->WaitUntilNextCallback(kOnDataSent);
1185
1186 size_t spdy_trailers_frame_length;
1187 spdy::Http2HeaderBlock trailers;
1188 trailers["foo"] = "bar";
1189 // Server sends trailers.
1190 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
1191 &spdy_trailers_frame_length));
1192
1193 delegate->WaitUntilNextCallback(kOnTrailersReceived);
1194 EXPECT_EQ(trailers, delegate->trailers());
1195 EXPECT_THAT(delegate->ReadData(cb.callback()), IsOk());
1196
1197 EXPECT_EQ(1, delegate->on_data_read_count());
1198 EXPECT_EQ(2, delegate->on_data_sent_count());
1199 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1200 EXPECT_EQ(
1201 static_cast<int64_t>(spdy_request_headers_frame_length + strlen(kBody1) +
1202 strlen(kBody2) + header.length() + header2.length()),
1203 delegate->GetTotalSentBytes());
1204 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
1205 strlen(kResponseBody) + header3.length() +
1206 spdy_trailers_frame_length),
1207 delegate->GetTotalReceivedBytes());
1208 }
1209
1210 // Tests that when request headers are delayed, SendvData triggers coalescing of
1211 // request headers with data buffers.
TEST_P(BidirectionalStreamQuicImplTest,SendvDataCoalesceDataBuffersAndHeaderFrame)1212 TEST_P(BidirectionalStreamQuicImplTest,
1213 SendvDataCoalesceDataBuffersAndHeaderFrame) {
1214 SetRequest("POST", "/", DEFAULT_PRIORITY);
1215 size_t spdy_request_headers_frame_length;
1216 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1217 AddWrite(ConstructInitialSettingsPacket());
1218 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1219 const std::string kBody1 = "here are some data";
1220 const std::string kBody2 = "data keep coming";
1221 std::string header = ConstructDataHeader(kBody1.length());
1222 std::string header2 = ConstructDataHeader(kBody2.length());
1223
1224 AddWrite(ConstructRequestHeadersAndMultipleDataFramesPacket(
1225 !kFin, DEFAULT_PRIORITY, &spdy_request_headers_frame_length,
1226 {header + kBody1 + header2 + kBody2}));
1227
1228 // Ack server's data packet.
1229 AddWrite(ConstructClientAckPacket(3, 1));
1230 const std::string kBody3 = "hello there";
1231 const std::string kBody4 = "another piece of small data";
1232 const std::string kBody5 = "really small";
1233 std::string header3 = ConstructDataHeader(kBody3.length());
1234 std::string header4 = ConstructDataHeader(kBody4.length());
1235 std::string header5 = ConstructDataHeader(kBody5.length());
1236 AddWrite(ConstructClientDataPacket(
1237 !kIncludeVersion, kFin,
1238 header3 + kBody3 + header4 + kBody4 + header5 + kBody5));
1239
1240 Initialize();
1241
1242 BidirectionalStreamRequestInfo request;
1243 request.method = "POST";
1244 request.url = GURL("http://www.google.com/");
1245 request.end_stream_on_headers = false;
1246 request.priority = DEFAULT_PRIORITY;
1247
1248 scoped_refptr<IOBuffer> read_buffer =
1249 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1250 auto delegate =
1251 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1252 delegate->DoNotSendRequestHeadersAutomatically();
1253 delegate->Start(&request, net_log_with_source(),
1254 session()->CreateHandle(destination_));
1255 ConfirmHandshake();
1256 delegate->WaitUntilNextCallback(kOnStreamReady);
1257
1258 // Send a Data packet.
1259 scoped_refptr<StringIOBuffer> buf1 =
1260 base::MakeRefCounted<StringIOBuffer>(kBody1);
1261 scoped_refptr<StringIOBuffer> buf2 =
1262 base::MakeRefCounted<StringIOBuffer>(kBody2);
1263
1264 std::vector<int> lengths = {buf1->size(), buf2->size()};
1265 delegate->SendvData({buf1, buf2}, lengths, !kFin);
1266 delegate->WaitUntilNextCallback(kOnDataSent);
1267
1268 // Server acks the request.
1269 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1270
1271 // Server sends the response headers.
1272 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1273 size_t spdy_response_headers_frame_length;
1274 ProcessPacket(
1275 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1276 &spdy_response_headers_frame_length));
1277
1278 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1279 TestCompletionCallback cb;
1280 int rv = delegate->ReadData(cb.callback());
1281 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1282 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1283 const char kResponseBody[] = "Hello world!";
1284 std::string header6 = ConstructDataHeader(strlen(kResponseBody));
1285 // Server sends data.
1286 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
1287 header6 + kResponseBody));
1288
1289 EXPECT_EQ(static_cast<int>(strlen(kResponseBody)), cb.WaitForResult());
1290
1291 // Send a second Data packet.
1292 scoped_refptr<StringIOBuffer> buf3 =
1293 base::MakeRefCounted<StringIOBuffer>(kBody3);
1294 scoped_refptr<StringIOBuffer> buf4 =
1295 base::MakeRefCounted<StringIOBuffer>(kBody4);
1296 scoped_refptr<StringIOBuffer> buf5 =
1297 base::MakeRefCounted<StringIOBuffer>(kBody5);
1298
1299 delegate->SendvData({buf3, buf4, buf5},
1300 {buf3->size(), buf4->size(), buf5->size()}, kFin);
1301 delegate->WaitUntilNextCallback(kOnDataSent);
1302
1303 size_t spdy_trailers_frame_length;
1304 spdy::Http2HeaderBlock trailers;
1305 trailers["foo"] = "bar";
1306 // Server sends trailers.
1307 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
1308 &spdy_trailers_frame_length));
1309
1310 delegate->WaitUntilNextCallback(kOnTrailersReceived);
1311 EXPECT_EQ(trailers, delegate->trailers());
1312 EXPECT_THAT(delegate->ReadData(cb.callback()), IsOk());
1313
1314 EXPECT_EQ(1, delegate->on_data_read_count());
1315 EXPECT_EQ(2, delegate->on_data_sent_count());
1316 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1317 EXPECT_EQ(static_cast<int64_t>(
1318 spdy_request_headers_frame_length + kBody1.length() +
1319 kBody2.length() + kBody3.length() + kBody4.length() +
1320 kBody5.length() + header.length() + header2.length() +
1321 header3.length() + header4.length() + header5.length()),
1322 delegate->GetTotalSentBytes());
1323 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
1324 strlen(kResponseBody) + header6.length() +
1325 spdy_trailers_frame_length),
1326 delegate->GetTotalReceivedBytes());
1327 }
1328
1329 // Tests that when request headers are delayed and SendData triggers the
1330 // headers to be sent, if that write fails the stream does not crash.
TEST_P(BidirectionalStreamQuicImplTest,SendDataWriteErrorCoalesceDataBufferAndHeaderFrame)1331 TEST_P(BidirectionalStreamQuicImplTest,
1332 SendDataWriteErrorCoalesceDataBufferAndHeaderFrame) {
1333 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1334 AddWrite(ConstructInitialSettingsPacket());
1335 AddWriteError(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
1336
1337 Initialize();
1338
1339 BidirectionalStreamRequestInfo request;
1340 request.method = "POST";
1341 request.url = GURL("http://www.google.com/");
1342 request.end_stream_on_headers = false;
1343 request.priority = DEFAULT_PRIORITY;
1344 request.extra_headers.SetHeader("cookie", std::string(2048, 'A'));
1345
1346 scoped_refptr<IOBuffer> read_buffer =
1347 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1348 auto delegate = std::make_unique<DeleteStreamDelegate>(
1349 read_buffer.get(), kReadBufferSize, DeleteStreamDelegate::ON_FAILED);
1350 delegate->DoNotSendRequestHeadersAutomatically();
1351 delegate->Start(&request, net_log_with_source(),
1352 session()->CreateHandle(destination_));
1353 ConfirmHandshake();
1354 delegate->WaitUntilNextCallback(kOnStreamReady);
1355
1356 // Attempt to send the headers and data.
1357 const char kBody1[] = "here are some data";
1358 scoped_refptr<StringIOBuffer> buf1 =
1359 base::MakeRefCounted<StringIOBuffer>(kBody1);
1360 delegate->SendData(buf1, buf1->size(), !kFin);
1361
1362 delegate->WaitUntilNextCallback(kOnFailed);
1363 }
1364
1365 // Tests that when request headers are delayed and SendvData triggers the
1366 // headers to be sent, if that write fails the stream does not crash.
TEST_P(BidirectionalStreamQuicImplTest,SendvDataWriteErrorCoalesceDataBufferAndHeaderFrame)1367 TEST_P(BidirectionalStreamQuicImplTest,
1368 SendvDataWriteErrorCoalesceDataBufferAndHeaderFrame) {
1369 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1370 AddWrite(ConstructInitialSettingsPacket());
1371 AddWriteError(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
1372
1373 Initialize();
1374
1375 BidirectionalStreamRequestInfo request;
1376 request.method = "POST";
1377 request.url = GURL("http://www.google.com/");
1378 request.end_stream_on_headers = false;
1379 request.priority = DEFAULT_PRIORITY;
1380 request.extra_headers.SetHeader("cookie", std::string(2048, 'A'));
1381
1382 scoped_refptr<IOBuffer> read_buffer =
1383 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1384 auto delegate = std::make_unique<DeleteStreamDelegate>(
1385 read_buffer.get(), kReadBufferSize, DeleteStreamDelegate::ON_FAILED);
1386 delegate->DoNotSendRequestHeadersAutomatically();
1387 delegate->Start(&request, net_log_with_source(),
1388 session()->CreateHandle(destination_));
1389 ConfirmHandshake();
1390 delegate->WaitUntilNextCallback(kOnStreamReady);
1391
1392 // Attempt to send the headers and data.
1393 const char kBody1[] = "here are some data";
1394 const char kBody2[] = "data keep coming";
1395 scoped_refptr<StringIOBuffer> buf1 =
1396 base::MakeRefCounted<StringIOBuffer>(kBody1);
1397 scoped_refptr<StringIOBuffer> buf2 =
1398 base::MakeRefCounted<StringIOBuffer>(kBody2);
1399 std::vector<int> lengths = {buf1->size(), buf2->size()};
1400 delegate->SendvData({buf1, buf2}, lengths, !kFin);
1401
1402 delegate->WaitUntilNextCallback(kOnFailed);
1403 }
1404
TEST_P(BidirectionalStreamQuicImplTest,PostRequest)1405 TEST_P(BidirectionalStreamQuicImplTest, PostRequest) {
1406 SetRequest("POST", "/", DEFAULT_PRIORITY);
1407 size_t spdy_request_headers_frame_length;
1408 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1409 AddWrite(ConstructInitialSettingsPacket());
1410 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1411 AddWrite(ConstructRequestHeadersPacketInner(
1412 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
1413 &spdy_request_headers_frame_length));
1414 std::string header = ConstructDataHeader(strlen(kUploadData));
1415 AddWrite(ConstructClientDataPacket(kIncludeVersion, kFin,
1416 header + std::string(kUploadData)));
1417
1418 AddWrite(ConstructClientAckPacket(3, 1));
1419
1420 Initialize();
1421
1422 BidirectionalStreamRequestInfo request;
1423 request.method = "POST";
1424 request.url = GURL("http://www.google.com/");
1425 request.end_stream_on_headers = false;
1426 request.priority = DEFAULT_PRIORITY;
1427
1428 scoped_refptr<IOBuffer> read_buffer =
1429 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1430 auto delegate =
1431 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1432 delegate->Start(&request, net_log_with_source(),
1433 session()->CreateHandle(destination_));
1434 ConfirmHandshake();
1435 delegate->WaitUntilNextCallback(kOnStreamReady);
1436
1437 // Send a DATA frame.
1438 scoped_refptr<StringIOBuffer> buf =
1439 base::MakeRefCounted<StringIOBuffer>(kUploadData);
1440
1441 delegate->SendData(buf, buf->size(), true);
1442 delegate->WaitUntilNextCallback(kOnDataSent);
1443
1444 // Server acks the request.
1445 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1446
1447 // Server sends the response headers.
1448 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1449 size_t spdy_response_headers_frame_length;
1450 ProcessPacket(
1451 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1452 &spdy_response_headers_frame_length));
1453
1454 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1455 TestCompletionCallback cb;
1456 int rv = delegate->ReadData(cb.callback());
1457 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1458 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1459 const char kResponseBody[] = "Hello world!";
1460 std::string header2 = ConstructDataHeader(strlen(kResponseBody));
1461 // Server sends data.
1462 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
1463 header2 + kResponseBody));
1464
1465 EXPECT_EQ(static_cast<int>(strlen(kResponseBody)), cb.WaitForResult());
1466
1467 size_t spdy_trailers_frame_length;
1468 spdy::Http2HeaderBlock trailers;
1469 trailers["foo"] = "bar";
1470 // Server sends trailers.
1471 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
1472 &spdy_trailers_frame_length));
1473
1474 delegate->WaitUntilNextCallback(kOnTrailersReceived);
1475 EXPECT_EQ(trailers, delegate->trailers());
1476 EXPECT_THAT(delegate->ReadData(cb.callback()), IsOk());
1477
1478 EXPECT_EQ(1, delegate->on_data_read_count());
1479 EXPECT_EQ(1, delegate->on_data_sent_count());
1480 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1481 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length +
1482 strlen(kUploadData) + header.length()),
1483 delegate->GetTotalSentBytes());
1484 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
1485 strlen(kResponseBody) + header2.length() +
1486 spdy_trailers_frame_length),
1487 delegate->GetTotalReceivedBytes());
1488 }
1489
TEST_P(BidirectionalStreamQuicImplTest,EarlyDataOverrideRequest)1490 TEST_P(BidirectionalStreamQuicImplTest, EarlyDataOverrideRequest) {
1491 SetRequest("PUT", "/", DEFAULT_PRIORITY);
1492 size_t spdy_request_headers_frame_length;
1493 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1494 AddWrite(ConstructInitialSettingsPacket());
1495 AddWrite(ConstructRequestHeadersPacketInner(
1496 GetNthClientInitiatedBidirectionalStreamId(0), kFin, DEFAULT_PRIORITY,
1497 &spdy_request_headers_frame_length));
1498 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1499 AddWrite(ConstructClientAckPacket(3, 1));
1500
1501 Initialize();
1502
1503 BidirectionalStreamRequestInfo request;
1504 request.method = "PUT";
1505 request.allow_early_data_override = true;
1506 request.url = GURL("http://www.google.com/");
1507 request.end_stream_on_headers = true;
1508 request.priority = DEFAULT_PRIORITY;
1509
1510 scoped_refptr<IOBuffer> read_buffer =
1511 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1512 auto delegate =
1513 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1514 delegate->set_trailers_expected(true);
1515 delegate->Start(&request, net_log_with_source(),
1516 session()->CreateHandle(destination_));
1517 delegate->WaitUntilNextCallback(kOnStreamReady);
1518 ConfirmHandshake();
1519
1520 // Server acks the request.
1521 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1522
1523 // Server sends the response headers.
1524 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1525
1526 size_t spdy_response_headers_frame_length;
1527 ProcessPacket(
1528 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1529 &spdy_response_headers_frame_length));
1530
1531 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1532 LoadTimingInfo load_timing_info;
1533 EXPECT_TRUE(delegate->GetLoadTimingInfo(&load_timing_info));
1534 ExpectLoadTimingValid(load_timing_info, /*session_reused=*/false);
1535 TestCompletionCallback cb;
1536 int rv = delegate->ReadData(cb.callback());
1537 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1538 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1539 const char kResponseBody[] = "Hello world!";
1540 // Server sends data.
1541 std::string header = ConstructDataHeader(strlen(kResponseBody));
1542 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
1543 header + kResponseBody));
1544 EXPECT_EQ(12, cb.WaitForResult());
1545
1546 EXPECT_EQ(std::string(kResponseBody), delegate->data_received());
1547 TestCompletionCallback cb2;
1548 EXPECT_THAT(delegate->ReadData(cb2.callback()), IsError(ERR_IO_PENDING));
1549
1550 spdy::Http2HeaderBlock trailers;
1551 size_t spdy_trailers_frame_length;
1552 trailers["foo"] = "bar";
1553 // Server sends trailers.
1554 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
1555 &spdy_trailers_frame_length));
1556
1557 delegate->WaitUntilNextCallback(kOnTrailersReceived);
1558 EXPECT_THAT(cb2.WaitForResult(), IsOk());
1559 EXPECT_EQ(trailers, delegate->trailers());
1560
1561 EXPECT_THAT(delegate->ReadData(cb2.callback()), IsOk());
1562 base::RunLoop().RunUntilIdle();
1563
1564 EXPECT_EQ(2, delegate->on_data_read_count());
1565 EXPECT_EQ(0, delegate->on_data_sent_count());
1566 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1567 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
1568 delegate->GetTotalSentBytes());
1569 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length +
1570 strlen(kResponseBody) + header.length() +
1571 spdy_trailers_frame_length),
1572 delegate->GetTotalReceivedBytes());
1573 // Check that NetLog was filled as expected.
1574 auto entries = net_log_observer().GetEntries();
1575 size_t pos = ExpectLogContainsSomewhere(
1576 entries, /*min_offset=*/0,
1577 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
1578 NetLogEventPhase::NONE);
1579 pos = ExpectLogContainsSomewhere(
1580 entries, /*min_offset=*/pos,
1581 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
1582 NetLogEventPhase::NONE);
1583 ExpectLogContainsSomewhere(
1584 entries, /*min_offset=*/pos,
1585 NetLogEventType::QUIC_CHROMIUM_CLIENT_STREAM_SEND_REQUEST_HEADERS,
1586 NetLogEventPhase::NONE);
1587 }
1588
TEST_P(BidirectionalStreamQuicImplTest,InterleaveReadDataAndSendData)1589 TEST_P(BidirectionalStreamQuicImplTest, InterleaveReadDataAndSendData) {
1590 SetRequest("POST", "/", DEFAULT_PRIORITY);
1591 size_t spdy_request_headers_frame_length;
1592 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1593 AddWrite(ConstructInitialSettingsPacket());
1594 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1595 AddWrite(ConstructRequestHeadersPacketInner(
1596 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
1597 &spdy_request_headers_frame_length));
1598
1599 std::string header = ConstructDataHeader(strlen(kUploadData));
1600 AddWrite(ConstructAckAndDataPacket(++packet_number_, !kIncludeVersion, 2, 1,
1601 !kFin, header + std::string(kUploadData),
1602 &client_maker_));
1603 AddWrite(ConstructAckAndDataPacket(++packet_number_, !kIncludeVersion, 3, 3,
1604 kFin, header + std::string(kUploadData),
1605 &client_maker_));
1606 Initialize();
1607
1608 BidirectionalStreamRequestInfo request;
1609 request.method = "POST";
1610 request.url = GURL("http://www.google.com/");
1611 request.end_stream_on_headers = false;
1612 request.priority = DEFAULT_PRIORITY;
1613
1614 scoped_refptr<IOBuffer> read_buffer =
1615 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1616 auto delegate =
1617 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1618 delegate->Start(&request, net_log_with_source(),
1619 session()->CreateHandle(destination_));
1620 ConfirmHandshake();
1621 delegate->WaitUntilNextCallback(kOnStreamReady);
1622
1623 // Server acks the request.
1624 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1625
1626 // Server sends the response headers.
1627 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1628 size_t spdy_response_headers_frame_length;
1629 ProcessPacket(
1630 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1631 &spdy_response_headers_frame_length));
1632
1633 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1634 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1635
1636 // Client sends a data packet.
1637 scoped_refptr<StringIOBuffer> buf =
1638 base::MakeRefCounted<StringIOBuffer>(kUploadData);
1639
1640 delegate->SendData(buf, buf->size(), false);
1641 delegate->WaitUntilNextCallback(kOnDataSent);
1642
1643 TestCompletionCallback cb;
1644 int rv = delegate->ReadData(cb.callback());
1645 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1646 const char kResponseBody[] = "Hello world!";
1647
1648 std::string header2 = ConstructDataHeader(strlen(kResponseBody));
1649 // Server sends a data packet
1650 int server_ack = 2;
1651 ProcessPacket(ConstructAckAndDataPacket(3, !kIncludeVersion, server_ack++, 1,
1652 !kFin, header2 + kResponseBody,
1653 &server_maker_));
1654
1655 EXPECT_EQ(static_cast<int64_t>(strlen(kResponseBody)), cb.WaitForResult());
1656 EXPECT_EQ(std::string(kResponseBody), delegate->data_received());
1657
1658 // Client sends a data packet.
1659 delegate->SendData(buf, buf->size(), true);
1660 delegate->WaitUntilNextCallback(kOnDataSent);
1661
1662 TestCompletionCallback cb2;
1663 rv = delegate->ReadData(cb2.callback());
1664 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1665 ProcessPacket(
1666 ConstructAckAndDataPacket(4, !kIncludeVersion, server_ack++, 1, kFin,
1667
1668 header2 + kResponseBody, &server_maker_));
1669
1670 EXPECT_EQ(static_cast<int64_t>(strlen(kResponseBody)), cb2.WaitForResult());
1671
1672 std::string expected_body(kResponseBody);
1673 expected_body.append(kResponseBody);
1674 EXPECT_EQ(expected_body, delegate->data_received());
1675
1676 EXPECT_THAT(delegate->ReadData(cb.callback()), IsOk());
1677 EXPECT_EQ(2, delegate->on_data_read_count());
1678 EXPECT_EQ(2, delegate->on_data_sent_count());
1679 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1680 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length +
1681 2 * strlen(kUploadData) + 2 * header.length()),
1682 delegate->GetTotalSentBytes());
1683 EXPECT_EQ(
1684 static_cast<int64_t>(spdy_response_headers_frame_length +
1685 2 * strlen(kResponseBody) + 2 * header2.length()),
1686 delegate->GetTotalReceivedBytes());
1687 }
1688
TEST_P(BidirectionalStreamQuicImplTest,ServerSendsRstAfterHeaders)1689 TEST_P(BidirectionalStreamQuicImplTest, ServerSendsRstAfterHeaders) {
1690 SetRequest("GET", "/", DEFAULT_PRIORITY);
1691 size_t spdy_request_headers_frame_length;
1692 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1693 AddWrite(ConstructInitialSettingsPacket());
1694 AddWrite(ConstructRequestHeadersPacketInner(
1695 GetNthClientInitiatedBidirectionalStreamId(0), kFin, DEFAULT_PRIORITY,
1696 &spdy_request_headers_frame_length));
1697 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1698 Initialize();
1699
1700 BidirectionalStreamRequestInfo request;
1701 request.method = "GET";
1702 request.url = GURL("http://www.google.com/");
1703 request.end_stream_on_headers = true;
1704 request.priority = DEFAULT_PRIORITY;
1705
1706 scoped_refptr<IOBuffer> read_buffer =
1707 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1708 auto delegate =
1709 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1710 delegate->Start(&request, net_log_with_source(),
1711 session()->CreateHandle(destination_));
1712 delegate->WaitUntilNextCallback(kOnStreamReady);
1713 ConfirmHandshake();
1714
1715 // Server sends a Rst. Since the stream has sent fin, the rst is one way in
1716 // IETF QUIC.
1717 ProcessPacket(server_maker_.MakeRstPacket(
1718 1, !kIncludeVersion, GetNthClientInitiatedBidirectionalStreamId(0),
1719 quic::QUIC_STREAM_CANCELLED,
1720 /*include_stop_sending_if_v99=*/false));
1721
1722 delegate->WaitUntilNextCallback(kOnFailed);
1723
1724 TestCompletionCallback cb;
1725 EXPECT_THAT(delegate->ReadData(cb.callback()),
1726 IsError(ERR_QUIC_PROTOCOL_ERROR));
1727
1728 base::RunLoop().RunUntilIdle();
1729
1730 EXPECT_THAT(delegate->error(), IsError(ERR_QUIC_PROTOCOL_ERROR));
1731 EXPECT_EQ(0, delegate->on_data_read_count());
1732 EXPECT_EQ(0, delegate->on_data_sent_count());
1733 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
1734 delegate->GetTotalSentBytes());
1735 EXPECT_EQ(0, delegate->GetTotalReceivedBytes());
1736 }
1737
TEST_P(BidirectionalStreamQuicImplTest,ServerSendsRstAfterReadData)1738 TEST_P(BidirectionalStreamQuicImplTest, ServerSendsRstAfterReadData) {
1739 SetRequest("GET", "/", DEFAULT_PRIORITY);
1740 size_t spdy_request_headers_frame_length;
1741 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1742 AddWrite(ConstructInitialSettingsPacket());
1743 AddWrite(ConstructRequestHeadersPacketInner(
1744 GetNthClientInitiatedBidirectionalStreamId(0), kFin, DEFAULT_PRIORITY,
1745 &spdy_request_headers_frame_length));
1746 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1747 // Why does QUIC ack Rst? Is this expected?
1748 AddWrite(ConstructClientAckPacket(3, 1));
1749
1750 Initialize();
1751
1752 BidirectionalStreamRequestInfo request;
1753 request.method = "GET";
1754 request.url = GURL("http://www.google.com/");
1755 request.end_stream_on_headers = true;
1756 request.priority = DEFAULT_PRIORITY;
1757
1758 scoped_refptr<IOBuffer> read_buffer =
1759 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1760 auto delegate =
1761 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1762 delegate->Start(&request, net_log_with_source(),
1763 session()->CreateHandle(destination_));
1764 delegate->WaitUntilNextCallback(kOnStreamReady);
1765 ConfirmHandshake();
1766
1767 // Server acks the request.
1768 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1769
1770 // Server sends the response headers.
1771 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1772
1773 size_t spdy_response_headers_frame_length;
1774 ProcessPacket(
1775 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1776 &spdy_response_headers_frame_length));
1777
1778 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1779 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
1780
1781 TestCompletionCallback cb;
1782 int rv = delegate->ReadData(cb.callback());
1783 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1784
1785 // Server sends a Rst. Since the stream has sent fin, the rst is one way in
1786 // IETF QUIC.
1787 ProcessPacket(server_maker_.MakeRstPacket(
1788 3, !kIncludeVersion, GetNthClientInitiatedBidirectionalStreamId(0),
1789 quic::QUIC_STREAM_CANCELLED,
1790 /*include_stop_sending_if_v99=*/false));
1791
1792 delegate->WaitUntilNextCallback(kOnFailed);
1793
1794 EXPECT_THAT(delegate->ReadData(cb.callback()),
1795 IsError(ERR_QUIC_PROTOCOL_ERROR));
1796 EXPECT_THAT(delegate->error(), IsError(ERR_QUIC_PROTOCOL_ERROR));
1797 EXPECT_EQ(0, delegate->on_data_read_count());
1798 EXPECT_EQ(0, delegate->on_data_sent_count());
1799 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
1800 delegate->GetTotalSentBytes());
1801 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length),
1802 delegate->GetTotalReceivedBytes());
1803 }
1804
TEST_P(BidirectionalStreamQuicImplTest,SessionClosedBeforeReadData)1805 TEST_P(BidirectionalStreamQuicImplTest, SessionClosedBeforeReadData) {
1806 SetRequest("POST", "/", DEFAULT_PRIORITY);
1807 size_t spdy_request_headers_frame_length;
1808 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1809 AddWrite(ConstructInitialSettingsPacket());
1810 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1811 AddWrite(ConstructRequestHeadersPacketInner(
1812 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
1813 &spdy_request_headers_frame_length));
1814 Initialize();
1815
1816 BidirectionalStreamRequestInfo request;
1817 request.method = "POST";
1818 request.url = GURL("http://www.google.com/");
1819 request.end_stream_on_headers = false;
1820 request.priority = DEFAULT_PRIORITY;
1821
1822 scoped_refptr<IOBuffer> read_buffer =
1823 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1824 auto delegate =
1825 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1826 delegate->Start(&request, net_log_with_source(),
1827 session()->CreateHandle(destination_));
1828 ConfirmHandshake();
1829 delegate->WaitUntilNextCallback(kOnStreamReady);
1830
1831 // Server acks the request.
1832 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
1833
1834 // Server sends the response headers.
1835 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
1836
1837 size_t spdy_response_headers_frame_length;
1838 ProcessPacket(
1839 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
1840 &spdy_response_headers_frame_length));
1841
1842 delegate->WaitUntilNextCallback(kOnHeadersReceived);
1843 TestCompletionCallback cb;
1844 int rv = delegate->ReadData(cb.callback());
1845 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1846 session()->connection()->CloseConnection(
1847 quic::QUIC_NO_ERROR, "test", quic::ConnectionCloseBehavior::SILENT_CLOSE);
1848 delegate->WaitUntilNextCallback(kOnFailed);
1849
1850 // Try to send data after OnFailed(), should not get called back.
1851 scoped_refptr<StringIOBuffer> buf =
1852 base::MakeRefCounted<StringIOBuffer>(kUploadData);
1853 delegate->SendData(buf, buf->size(), false);
1854
1855 EXPECT_THAT(delegate->ReadData(cb.callback()),
1856 IsError(ERR_QUIC_PROTOCOL_ERROR));
1857 EXPECT_THAT(delegate->error(), IsError(ERR_QUIC_PROTOCOL_ERROR));
1858 EXPECT_EQ(0, delegate->on_data_read_count());
1859 EXPECT_EQ(0, delegate->on_data_sent_count());
1860 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
1861 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
1862 delegate->GetTotalSentBytes());
1863 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length),
1864 delegate->GetTotalReceivedBytes());
1865 }
1866
TEST_P(BidirectionalStreamQuicImplTest,SessionClosedBeforeStartConfirmed)1867 TEST_P(BidirectionalStreamQuicImplTest, SessionClosedBeforeStartConfirmed) {
1868 SetRequest("POST", "/", DEFAULT_PRIORITY);
1869 Initialize();
1870
1871 BidirectionalStreamRequestInfo request;
1872 request.method = "POST";
1873 request.url = GURL("http://www.google.com/");
1874 request.end_stream_on_headers = false;
1875 request.priority = DEFAULT_PRIORITY;
1876
1877 ConfirmHandshake();
1878 session()->connection()->CloseConnection(
1879 quic::QUIC_NO_ERROR, "test", quic::ConnectionCloseBehavior::SILENT_CLOSE);
1880
1881 scoped_refptr<IOBuffer> read_buffer =
1882 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1883 auto delegate =
1884 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1885 delegate->Start(&request, net_log_with_source(),
1886 session()->CreateHandle(destination_));
1887 delegate->WaitUntilNextCallback(kOnFailed);
1888 EXPECT_TRUE(delegate->on_failed_called());
1889 EXPECT_THAT(delegate->error(), IsError(ERR_CONNECTION_CLOSED));
1890 }
1891
TEST_P(BidirectionalStreamQuicImplTest,SessionClosedBeforeStartNotConfirmed)1892 TEST_P(BidirectionalStreamQuicImplTest, SessionClosedBeforeStartNotConfirmed) {
1893 SetRequest("POST", "/", DEFAULT_PRIORITY);
1894 Initialize();
1895
1896 session()->connection()->CloseConnection(
1897 quic::QUIC_NO_ERROR, "test", quic::ConnectionCloseBehavior::SILENT_CLOSE);
1898
1899 BidirectionalStreamRequestInfo request;
1900 request.method = "POST";
1901 request.url = GURL("http://www.google.com/");
1902 request.end_stream_on_headers = false;
1903 request.priority = DEFAULT_PRIORITY;
1904
1905 scoped_refptr<IOBuffer> read_buffer =
1906 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1907 auto delegate =
1908 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1909 delegate->Start(&request, net_log_with_source(),
1910 session()->CreateHandle(destination_));
1911 delegate->WaitUntilNextCallback(kOnFailed);
1912 EXPECT_TRUE(delegate->on_failed_called());
1913 EXPECT_THAT(delegate->error(), IsError(ERR_QUIC_HANDSHAKE_FAILED));
1914 }
1915
TEST_P(BidirectionalStreamQuicImplTest,SessionCloseDuringOnStreamReady)1916 TEST_P(BidirectionalStreamQuicImplTest, SessionCloseDuringOnStreamReady) {
1917 SetRequest("POST", "/", DEFAULT_PRIORITY);
1918 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1919 AddWrite(ConstructInitialSettingsPacket());
1920 AddWriteError(SYNCHRONOUS, ERR_CONNECTION_REFUSED);
1921
1922 Initialize();
1923
1924 BidirectionalStreamRequestInfo request;
1925 request.method = "POST";
1926 request.url = GURL("http://www.google.com/");
1927 request.end_stream_on_headers = false;
1928 request.priority = DEFAULT_PRIORITY;
1929
1930 scoped_refptr<IOBuffer> read_buffer =
1931 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1932 auto delegate = std::make_unique<DeleteStreamDelegate>(
1933 read_buffer.get(), kReadBufferSize, DeleteStreamDelegate::ON_FAILED);
1934 delegate->Start(&request, net_log_with_source(),
1935 session()->CreateHandle(destination_));
1936 ConfirmHandshake();
1937 delegate->WaitUntilNextCallback(kOnFailed);
1938
1939 EXPECT_EQ(0, delegate->on_data_read_count());
1940 EXPECT_EQ(0, delegate->on_data_sent_count());
1941 }
1942
TEST_P(BidirectionalStreamQuicImplTest,DeleteStreamDuringOnStreamReady)1943 TEST_P(BidirectionalStreamQuicImplTest, DeleteStreamDuringOnStreamReady) {
1944 SetRequest("POST", "/", DEFAULT_PRIORITY);
1945 size_t spdy_request_headers_frame_length;
1946 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1947 AddWrite(ConstructInitialSettingsPacket());
1948 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1949 AddWrite(ConstructRequestHeadersPacketInner(
1950 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
1951 &spdy_request_headers_frame_length));
1952 AddWrite(ConstructClientEarlyRstStreamPacket());
1953
1954 Initialize();
1955
1956 BidirectionalStreamRequestInfo request;
1957 request.method = "POST";
1958 request.url = GURL("http://www.google.com/");
1959 request.end_stream_on_headers = false;
1960 request.priority = DEFAULT_PRIORITY;
1961
1962 scoped_refptr<IOBuffer> read_buffer =
1963 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1964 auto delegate = std::make_unique<DeleteStreamDelegate>(
1965 read_buffer.get(), kReadBufferSize,
1966 DeleteStreamDelegate::ON_STREAM_READY);
1967 delegate->Start(&request, net_log_with_source(),
1968 session()->CreateHandle(destination_));
1969 ConfirmHandshake();
1970 delegate->WaitUntilNextCallback(kOnStreamReady);
1971
1972 EXPECT_EQ(0, delegate->on_data_read_count());
1973 EXPECT_EQ(0, delegate->on_data_sent_count());
1974 }
1975
TEST_P(BidirectionalStreamQuicImplTest,DeleteStreamAfterReadData)1976 TEST_P(BidirectionalStreamQuicImplTest, DeleteStreamAfterReadData) {
1977 SetRequest("POST", "/", DEFAULT_PRIORITY);
1978 size_t spdy_request_headers_frame_length;
1979 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
1980 AddWrite(ConstructInitialSettingsPacket());
1981 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
1982 AddWrite(ConstructRequestHeadersPacketInner(
1983 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
1984 &spdy_request_headers_frame_length));
1985 AddWrite(ConstructClientAckAndRstStreamPacket(2, 1));
1986
1987 Initialize();
1988
1989 BidirectionalStreamRequestInfo request;
1990 request.method = "POST";
1991 request.url = GURL("http://www.google.com/");
1992 request.end_stream_on_headers = false;
1993 request.priority = DEFAULT_PRIORITY;
1994
1995 scoped_refptr<IOBuffer> read_buffer =
1996 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
1997 auto delegate =
1998 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
1999 delegate->Start(&request, net_log_with_source(),
2000 session()->CreateHandle(destination_));
2001 ConfirmHandshake();
2002 delegate->WaitUntilNextCallback(kOnStreamReady);
2003
2004 // Server acks the request.
2005 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
2006
2007 // Server sends the response headers.
2008 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
2009 size_t spdy_response_headers_frame_length;
2010 ProcessPacket(
2011 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
2012 &spdy_response_headers_frame_length));
2013
2014 delegate->WaitUntilNextCallback(kOnHeadersReceived);
2015 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
2016
2017 // Cancel the stream after ReadData returns ERR_IO_PENDING.
2018 TestCompletionCallback cb;
2019 EXPECT_THAT(delegate->ReadData(cb.callback()), IsError(ERR_IO_PENDING));
2020 delegate->DeleteStream();
2021
2022 base::RunLoop().RunUntilIdle();
2023
2024 EXPECT_EQ(0, delegate->on_data_read_count());
2025 EXPECT_EQ(0, delegate->on_data_sent_count());
2026 EXPECT_EQ(kProtoQUIC, delegate->GetProtocol());
2027 EXPECT_EQ(static_cast<int64_t>(spdy_request_headers_frame_length),
2028 delegate->GetTotalSentBytes());
2029 EXPECT_EQ(static_cast<int64_t>(spdy_response_headers_frame_length),
2030 delegate->GetTotalReceivedBytes());
2031 }
2032
TEST_P(BidirectionalStreamQuicImplTest,DeleteStreamDuringOnHeadersReceived)2033 TEST_P(BidirectionalStreamQuicImplTest, DeleteStreamDuringOnHeadersReceived) {
2034 SetRequest("POST", "/", DEFAULT_PRIORITY);
2035 size_t spdy_request_headers_frame_length;
2036 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
2037 AddWrite(ConstructInitialSettingsPacket());
2038 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
2039 AddWrite(ConstructRequestHeadersPacketInner(
2040 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
2041 &spdy_request_headers_frame_length));
2042 AddWrite(ConstructClientAckAndRstStreamPacket(2, 1));
2043
2044 Initialize();
2045
2046 BidirectionalStreamRequestInfo request;
2047 request.method = "POST";
2048 request.url = GURL("http://www.google.com/");
2049 request.end_stream_on_headers = false;
2050 request.priority = DEFAULT_PRIORITY;
2051
2052 scoped_refptr<IOBuffer> read_buffer =
2053 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
2054 auto delegate = std::make_unique<DeleteStreamDelegate>(
2055 read_buffer.get(), kReadBufferSize,
2056 DeleteStreamDelegate::ON_HEADERS_RECEIVED);
2057 delegate->Start(&request, net_log_with_source(),
2058 session()->CreateHandle(destination_));
2059 ConfirmHandshake();
2060 delegate->WaitUntilNextCallback(kOnStreamReady);
2061
2062 // Server acks the request.
2063 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
2064
2065 // Server sends the response headers.
2066 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
2067
2068 size_t spdy_response_headers_frame_length;
2069 ProcessPacket(
2070 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
2071 &spdy_response_headers_frame_length));
2072
2073 delegate->WaitUntilNextCallback(kOnHeadersReceived);
2074 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
2075
2076 base::RunLoop().RunUntilIdle();
2077
2078 EXPECT_EQ(0, delegate->on_data_read_count());
2079 EXPECT_EQ(0, delegate->on_data_sent_count());
2080 }
2081
TEST_P(BidirectionalStreamQuicImplTest,DeleteStreamDuringOnDataRead)2082 TEST_P(BidirectionalStreamQuicImplTest, DeleteStreamDuringOnDataRead) {
2083 SetRequest("POST", "/", DEFAULT_PRIORITY);
2084 size_t spdy_request_headers_frame_length;
2085 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
2086 AddWrite(ConstructInitialSettingsPacket());
2087 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
2088 AddWrite(ConstructRequestHeadersPacketInner(
2089 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
2090 &spdy_request_headers_frame_length));
2091 AddWrite(ConstructClientAckPacket(3, 1));
2092 AddWrite(ConstructClientRstStreamPacket());
2093
2094 Initialize();
2095
2096 BidirectionalStreamRequestInfo request;
2097 request.method = "POST";
2098 request.url = GURL("http://www.google.com/");
2099 request.end_stream_on_headers = false;
2100 request.priority = DEFAULT_PRIORITY;
2101
2102 scoped_refptr<IOBuffer> read_buffer =
2103 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
2104 auto delegate = std::make_unique<DeleteStreamDelegate>(
2105 read_buffer.get(), kReadBufferSize, DeleteStreamDelegate::ON_DATA_READ);
2106 delegate->Start(&request, net_log_with_source(),
2107 session()->CreateHandle(destination_));
2108 ConfirmHandshake();
2109 delegate->WaitUntilNextCallback(kOnStreamReady);
2110
2111 // Server acks the request.
2112 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
2113
2114 // Server sends the response headers.
2115 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
2116
2117 size_t spdy_response_headers_frame_length;
2118 ProcessPacket(
2119 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
2120 &spdy_response_headers_frame_length));
2121
2122 delegate->WaitUntilNextCallback(kOnHeadersReceived);
2123
2124 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
2125
2126 TestCompletionCallback cb;
2127 int rv = delegate->ReadData(cb.callback());
2128 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2129 const char kResponseBody[] = "Hello world!";
2130 std::string header = ConstructDataHeader(strlen(kResponseBody));
2131 // Server sends data.
2132 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
2133 header + kResponseBody));
2134 EXPECT_EQ(static_cast<int64_t>(strlen(kResponseBody)), cb.WaitForResult());
2135
2136 base::RunLoop().RunUntilIdle();
2137
2138 EXPECT_EQ(1, delegate->on_data_read_count());
2139 EXPECT_EQ(0, delegate->on_data_sent_count());
2140 }
2141
TEST_P(BidirectionalStreamQuicImplTest,AsyncFinRead)2142 TEST_P(BidirectionalStreamQuicImplTest, AsyncFinRead) {
2143 const char kBody[] = "here is some data";
2144 SetRequest("POST", "/", DEFAULT_PRIORITY);
2145 size_t spdy_request_headers_frame_length;
2146 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
2147 AddWrite(ConstructInitialSettingsPacket());
2148 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
2149 AddWrite(ConstructRequestHeadersPacketInner(
2150 GetNthClientInitiatedBidirectionalStreamId(0), !kFin, DEFAULT_PRIORITY,
2151 &spdy_request_headers_frame_length));
2152 std::string header = ConstructDataHeader(strlen(kBody));
2153 AddWrite(ConstructClientDataPacket(kIncludeVersion, kFin, header + kBody));
2154 AddWrite(ConstructClientAckPacket(3, 1));
2155
2156 Initialize();
2157
2158 BidirectionalStreamRequestInfo request;
2159 request.method = "POST";
2160 request.url = GURL("http://www.google.com/");
2161 request.end_stream_on_headers = false;
2162 request.priority = DEFAULT_PRIORITY;
2163
2164 scoped_refptr<IOBuffer> read_buffer =
2165 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
2166 auto delegate =
2167 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
2168
2169 delegate->Start(&request, net_log_with_source(),
2170 session()->CreateHandle(destination_));
2171 ConfirmHandshake();
2172 delegate->WaitUntilNextCallback(kOnStreamReady);
2173
2174 // Send a Data packet with fin set.
2175 scoped_refptr<StringIOBuffer> buf1 =
2176 base::MakeRefCounted<StringIOBuffer>(kBody);
2177 delegate->SendData(buf1, buf1->size(), /*fin*/ true);
2178 delegate->WaitUntilNextCallback(kOnDataSent);
2179
2180 // Server acks the request.
2181 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
2182
2183 // Server sends the response headers.
2184 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
2185
2186 size_t spdy_response_headers_frame_length;
2187 ProcessPacket(
2188 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
2189 &spdy_response_headers_frame_length));
2190
2191 delegate->WaitUntilNextCallback(kOnHeadersReceived);
2192
2193 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
2194
2195 // Read the body, which will complete asynchronously.
2196 TestCompletionCallback cb;
2197 int rv = delegate->ReadData(cb.callback());
2198 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2199 const char kResponseBody[] = "Hello world!";
2200 std::string header2 = ConstructDataHeader(strlen(kResponseBody));
2201
2202 // Server sends data with the fin set, which should result in the stream
2203 // being closed and hence no RST_STREAM will be sent.
2204 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, kFin,
2205 header2 + kResponseBody));
2206 EXPECT_EQ(static_cast<int64_t>(strlen(kResponseBody)), cb.WaitForResult());
2207
2208 base::RunLoop().RunUntilIdle();
2209
2210 EXPECT_EQ(1, delegate->on_data_read_count());
2211 EXPECT_EQ(1, delegate->on_data_sent_count());
2212 }
2213
TEST_P(BidirectionalStreamQuicImplTest,DeleteStreamDuringOnTrailersReceived)2214 TEST_P(BidirectionalStreamQuicImplTest, DeleteStreamDuringOnTrailersReceived) {
2215 SetRequest("GET", "/", DEFAULT_PRIORITY);
2216 size_t spdy_request_headers_frame_length;
2217 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_ZERO_RTT);
2218 AddWrite(ConstructInitialSettingsPacket());
2219 client_maker_.SetEncryptionLevel(quic::ENCRYPTION_FORWARD_SECURE);
2220 AddWrite(ConstructRequestHeadersPacket(kFin, DEFAULT_PRIORITY,
2221 &spdy_request_headers_frame_length));
2222 AddWrite(ConstructClientAckPacket(3, 1)); // Ack the data packet
2223 AddWrite(ConstructClientAckAndRstStreamPacket(4, 4));
2224
2225 Initialize();
2226
2227 BidirectionalStreamRequestInfo request;
2228 request.method = "GET";
2229 request.url = GURL("http://www.google.com/");
2230 request.end_stream_on_headers = true;
2231 request.priority = DEFAULT_PRIORITY;
2232
2233 scoped_refptr<IOBuffer> read_buffer =
2234 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
2235 auto delegate = std::make_unique<DeleteStreamDelegate>(
2236 read_buffer.get(), kReadBufferSize,
2237 DeleteStreamDelegate::ON_TRAILERS_RECEIVED);
2238 delegate->Start(&request, net_log_with_source(),
2239 session()->CreateHandle(destination_));
2240 ConfirmHandshake();
2241 delegate->WaitUntilNextCallback(kOnStreamReady);
2242
2243 // Server acks the request.
2244 ProcessPacket(ConstructServerAckPacket(1, 1, 1, 1));
2245
2246 // Server sends the response headers.
2247 spdy::Http2HeaderBlock response_headers = ConstructResponseHeaders("200");
2248
2249 size_t spdy_response_headers_frame_length;
2250 ProcessPacket(
2251 ConstructResponseHeadersPacket(2, !kFin, std::move(response_headers),
2252 &spdy_response_headers_frame_length));
2253
2254 delegate->WaitUntilNextCallback(kOnHeadersReceived);
2255
2256 EXPECT_EQ("200", delegate->response_headers().find(":status")->second);
2257
2258 TestCompletionCallback cb;
2259 int rv = delegate->ReadData(cb.callback());
2260 EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2261 const char kResponseBody[] = "Hello world!";
2262
2263 // Server sends data.
2264 std::string header = ConstructDataHeader(strlen(kResponseBody));
2265 ProcessPacket(ConstructServerDataPacket(3, !kIncludeVersion, !kFin,
2266 header + kResponseBody));
2267
2268 EXPECT_EQ(static_cast<int64_t>(strlen(kResponseBody)), cb.WaitForResult());
2269 EXPECT_EQ(std::string(kResponseBody), delegate->data_received());
2270
2271 size_t spdy_trailers_frame_length;
2272 spdy::Http2HeaderBlock trailers;
2273 trailers["foo"] = "bar";
2274 // Server sends trailers.
2275 ProcessPacket(ConstructResponseTrailersPacket(4, kFin, trailers.Clone(),
2276 &spdy_trailers_frame_length));
2277
2278 delegate->WaitUntilNextCallback(kOnTrailersReceived);
2279 EXPECT_EQ(trailers, delegate->trailers());
2280
2281 base::RunLoop().RunUntilIdle();
2282
2283 EXPECT_EQ(1, delegate->on_data_read_count());
2284 EXPECT_EQ(0, delegate->on_data_sent_count());
2285 }
2286
2287 // Tests that if QuicChromiumClientSession is closed after
2288 // BidirectionalStreamQuicImpl::OnStreamReady() but before
2289 // QuicChromiumClientSession::Handle::ReleaseStream() is called, there is no
2290 // crash. Regression test for crbug.com/754823.
TEST_P(BidirectionalStreamQuicImplTest,ReleaseStreamFails)2291 TEST_P(BidirectionalStreamQuicImplTest, ReleaseStreamFails) {
2292 SetRequest("GET", "/", DEFAULT_PRIORITY);
2293 Initialize();
2294
2295 ConfirmHandshake();
2296
2297 BidirectionalStreamRequestInfo request;
2298 request.method = "GET";
2299 request.url = GURL("http://www.google.com/");
2300 request.end_stream_on_headers = true;
2301 request.priority = DEFAULT_PRIORITY;
2302
2303 scoped_refptr<IOBuffer> read_buffer =
2304 base::MakeRefCounted<IOBuffer>(kReadBufferSize);
2305 auto delegate =
2306 std::make_unique<TestDelegateBase>(read_buffer.get(), kReadBufferSize);
2307 delegate->set_trailers_expected(true);
2308 // QuicChromiumClientSession::Handle::RequestStream() returns OK synchronously
2309 // because Initialize() has established a Session.
2310 delegate->Start(&request, net_log_with_source(),
2311 session()->CreateHandle(destination_));
2312 // Now closes the underlying session.
2313 session_->CloseSessionOnError(ERR_ABORTED, quic::QUIC_INTERNAL_ERROR,
2314 quic::ConnectionCloseBehavior::SILENT_CLOSE);
2315 delegate->WaitUntilNextCallback(kOnFailed);
2316
2317 EXPECT_THAT(delegate->error(), IsError(ERR_CONNECTION_CLOSED));
2318 }
2319
2320 } // namespace net::test
2321