1 // Copyright 2012 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/quic_http_stream.h"
6
7 #include <set>
8 #include <string_view>
9 #include <utility>
10
11 #include "base/auto_reset.h"
12 #include "base/functional/bind.h"
13 #include "base/metrics/histogram_functions.h"
14 #include "base/strings/string_split.h"
15 #include "base/task/single_thread_task_runner.h"
16 #include "net/base/features.h"
17 #include "net/base/ip_endpoint.h"
18 #include "net/base/load_flags.h"
19 #include "net/base/net_errors.h"
20 #include "net/http/http_response_headers.h"
21 #include "net/http/http_status_code.h"
22 #include "net/http/http_util.h"
23 #include "net/log/net_log.h"
24 #include "net/log/net_log_event_type.h"
25 #include "net/log/net_log_source.h"
26 #include "net/quic/quic_http_utils.h"
27 #include "net/spdy/spdy_http_utils.h"
28 #include "net/ssl/ssl_info.h"
29 #include "net/third_party/quiche/src/quiche/http2/core/spdy_frame_builder.h"
30 #include "net/third_party/quiche/src/quiche/http2/core/spdy_framer.h"
31 #include "net/third_party/quiche/src/quiche/quic/core/http/spdy_utils.h"
32 #include "net/third_party/quiche/src/quiche/quic/core/quic_stream_sequencer.h"
33 #include "net/third_party/quiche/src/quiche/quic/core/quic_utils.h"
34 #include "url/origin.h"
35 #include "url/scheme_host_port.h"
36
37 namespace net {
38
QuicHttpStream(std::unique_ptr<QuicChromiumClientSession::Handle> session,std::set<std::string> dns_aliases)39 QuicHttpStream::QuicHttpStream(
40 std::unique_ptr<QuicChromiumClientSession::Handle> session,
41 std::set<std::string> dns_aliases)
42 : MultiplexedHttpStream(std::move(session)),
43 dns_aliases_(std::move(dns_aliases)) {}
44
~QuicHttpStream()45 QuicHttpStream::~QuicHttpStream() {
46 CHECK(!in_loop_);
47 Close(false);
48 }
49
ConnectionInfoFromQuicVersion(quic::ParsedQuicVersion quic_version)50 HttpConnectionInfo QuicHttpStream::ConnectionInfoFromQuicVersion(
51 quic::ParsedQuicVersion quic_version) {
52 switch (quic_version.transport_version) {
53 case quic::QUIC_VERSION_UNSUPPORTED:
54 return HttpConnectionInfo::kQUIC_UNKNOWN_VERSION;
55 case quic::QUIC_VERSION_46:
56 return HttpConnectionInfo::kQUIC_46;
57 case quic::QUIC_VERSION_IETF_DRAFT_29:
58 DCHECK(quic_version.UsesTls());
59 return HttpConnectionInfo::kQUIC_DRAFT_29;
60 case quic::QUIC_VERSION_IETF_RFC_V1:
61 DCHECK(quic_version.UsesTls());
62 return HttpConnectionInfo::kQUIC_RFC_V1;
63 case quic::QUIC_VERSION_RESERVED_FOR_NEGOTIATION:
64 return HttpConnectionInfo::kQUIC_999;
65 case quic::QUIC_VERSION_IETF_RFC_V2:
66 DCHECK(quic_version.UsesTls());
67 return HttpConnectionInfo::kQUIC_2_DRAFT_8;
68 }
69 NOTREACHED();
70 }
71
RegisterRequest(const HttpRequestInfo * request_info)72 void QuicHttpStream::RegisterRequest(const HttpRequestInfo* request_info) {
73 DCHECK(request_info);
74 DCHECK(request_info->traffic_annotation.is_valid());
75 request_info_ = request_info;
76 }
77
InitializeStream(bool can_send_early,RequestPriority priority,const NetLogWithSource & stream_net_log,CompletionOnceCallback callback)78 int QuicHttpStream::InitializeStream(bool can_send_early,
79 RequestPriority priority,
80 const NetLogWithSource& stream_net_log,
81 CompletionOnceCallback callback) {
82 CHECK(callback_.is_null());
83 DCHECK(request_info_);
84 DCHECK(!stream_);
85
86 // HttpNetworkTransaction will retry any request that fails with
87 // ERR_QUIC_HANDSHAKE_FAILED. It will retry any request with
88 // ERR_CONNECTION_CLOSED so long as the connection has been used for other
89 // streams first and headers have not yet been received.
90 if (!quic_session()->IsConnected()) {
91 return GetResponseStatus();
92 }
93
94 stream_net_log.AddEventReferencingSource(
95 NetLogEventType::HTTP_STREAM_REQUEST_BOUND_TO_QUIC_SESSION,
96 quic_session()->net_log().source());
97 stream_net_log.AddEventWithIntParams(
98 NetLogEventType::QUIC_CONNECTION_MIGRATION_MODE,
99 "connection_migration_mode",
100 static_cast<int>(quic_session()->connection_migration_mode()));
101
102 stream_net_log_ = stream_net_log;
103 can_send_early_ = can_send_early;
104 request_time_ = base::Time::Now();
105 priority_ = priority;
106
107 SaveSSLInfo();
108
109 next_state_ = STATE_REQUEST_STREAM;
110 int rv = DoLoop(OK);
111 if (rv == ERR_IO_PENDING) {
112 callback_ = std::move(callback);
113 }
114
115 return MapStreamError(rv);
116 }
117
SendRequest(const HttpRequestHeaders & request_headers,HttpResponseInfo * response,CompletionOnceCallback callback)118 int QuicHttpStream::SendRequest(const HttpRequestHeaders& request_headers,
119 HttpResponseInfo* response,
120 CompletionOnceCallback callback) {
121 CHECK(!request_body_stream_);
122 CHECK(!response_info_);
123 CHECK(callback_.is_null());
124 CHECK(!callback.is_null());
125 CHECK(response);
126
127 if (!stream_ || !quic_session()->IsConnected()) {
128 return GetResponseStatus();
129 }
130
131 // Store the serialized request headers.
132 CreateSpdyHeadersFromHttpRequest(*request_info_, priority_, request_headers,
133 &request_headers_);
134
135 // Store the request body.
136 request_body_stream_ = request_info_->upload_data_stream;
137 if (request_body_stream_) {
138 // TODO(rch): Can we be more precise about when to allocate
139 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
140 // was being called even if we didn't yet allocate raw_request_body_buf_.
141 // && (request_body_stream_->size() ||
142 // request_body_stream_->is_chunked()))
143 // Set the body buffer size to be the size of the body clamped
144 // into the range [10 * quic::kMaxOutgoingPacketSize, 256 *
145 // quic::kMaxOutgoingPacketSize]. With larger bodies, larger buffers reduce
146 // CPU usage.
147 raw_request_body_buf_ =
148 base::MakeRefCounted<IOBufferWithSize>(static_cast<size_t>(
149 std::max(10 * quic::kMaxOutgoingPacketSize,
150 std::min(request_body_stream_->size(),
151 256 * quic::kMaxOutgoingPacketSize))));
152 // The request body buffer is empty at first.
153 request_body_buf_ =
154 base::MakeRefCounted<DrainableIOBuffer>(raw_request_body_buf_, 0);
155 }
156
157 // Store the response info.
158 response_info_ = response;
159
160 // Put the peer's IP address and port into the response.
161 IPEndPoint address;
162 int rv = quic_session()->GetPeerAddress(&address);
163 if (rv != OK) {
164 return rv;
165 }
166 response_info_->remote_endpoint = address;
167
168 next_state_ = STATE_SET_REQUEST_PRIORITY;
169 rv = DoLoop(OK);
170
171 if (rv == ERR_IO_PENDING) {
172 callback_ = std::move(callback);
173 }
174
175 return rv > 0 ? OK : MapStreamError(rv);
176 }
177
ReadResponseHeaders(CompletionOnceCallback callback)178 int QuicHttpStream::ReadResponseHeaders(CompletionOnceCallback callback) {
179 CHECK(callback_.is_null());
180 CHECK(!callback.is_null());
181
182 int rv = stream_->ReadInitialHeaders(
183 &response_header_block_,
184 base::BindOnce(&QuicHttpStream::OnReadResponseHeadersComplete,
185 weak_factory_.GetWeakPtr()));
186
187 if (rv == ERR_IO_PENDING) {
188 // Still waiting for the response, return IO_PENDING.
189 CHECK(callback_.is_null());
190 callback_ = std::move(callback);
191 return ERR_IO_PENDING;
192 }
193
194 if (rv < 0) {
195 return MapStreamError(rv);
196 }
197
198 // Check if we already have the response headers. If so, return synchronously.
199 if (response_headers_received_) {
200 return OK;
201 }
202
203 headers_bytes_received_ += rv;
204 return ProcessResponseHeaders(response_header_block_);
205 }
206
ReadResponseBody(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)207 int QuicHttpStream::ReadResponseBody(IOBuffer* buf,
208 int buf_len,
209 CompletionOnceCallback callback) {
210 CHECK(callback_.is_null());
211 CHECK(!callback.is_null());
212 CHECK(!user_buffer_.get());
213 CHECK_EQ(0, user_buffer_len_);
214
215 // Invalidate HttpRequestInfo pointer. This is to allow the stream to be
216 // shared across multiple transactions which might require this
217 // stream to outlive the request_info_'s owner.
218 // Only allowed when Read state machine starts. It is safe to reset it at
219 // this point since request_info_->upload_data_stream is also not needed
220 // anymore.
221 request_info_ = nullptr;
222
223 // If the stream is already closed, there is no body to read.
224 if (stream_->IsDoneReading()) {
225 return HandleReadComplete(OK);
226 }
227
228 int rv = stream_->ReadBody(buf, buf_len,
229 base::BindOnce(&QuicHttpStream::OnReadBodyComplete,
230 weak_factory_.GetWeakPtr()));
231 if (rv == ERR_IO_PENDING) {
232 callback_ = std::move(callback);
233 user_buffer_ = buf;
234 user_buffer_len_ = buf_len;
235 return ERR_IO_PENDING;
236 }
237
238 if (rv < 0) {
239 return MapStreamError(rv);
240 }
241
242 return HandleReadComplete(rv);
243 }
244
Close(bool)245 void QuicHttpStream::Close(bool /*not_reusable*/) {
246 session_error_ = ERR_ABORTED;
247 SaveResponseStatus();
248 // Note: the not_reusable flag has no meaning for QUIC streams.
249 if (stream_) {
250 stream_->Reset(quic::QUIC_STREAM_CANCELLED);
251 }
252 ResetStream();
253 }
254
IsResponseBodyComplete() const255 bool QuicHttpStream::IsResponseBodyComplete() const {
256 return next_state_ == STATE_OPEN && stream_->IsDoneReading();
257 }
258
IsConnectionReused() const259 bool QuicHttpStream::IsConnectionReused() const {
260 // TODO(rch): do something smarter here.
261 return stream_ && stream_->id() > 1;
262 }
263
GetTotalReceivedBytes() const264 int64_t QuicHttpStream::GetTotalReceivedBytes() const {
265 if (stream_) {
266 DCHECK_LE(stream_->NumBytesConsumed(), stream_->stream_bytes_read());
267 // Only count the uniquely received bytes.
268 return stream_->NumBytesConsumed();
269 }
270 return closed_stream_received_bytes_;
271 }
272
GetTotalSentBytes() const273 int64_t QuicHttpStream::GetTotalSentBytes() const {
274 if (stream_) {
275 return stream_->stream_bytes_written();
276 }
277 return closed_stream_sent_bytes_;
278 }
279
GetLoadTimingInfo(LoadTimingInfo * load_timing_info) const280 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
281 bool is_first_stream = closed_is_first_stream_;
282 if (stream_) {
283 load_timing_info->socket_log_id = stream_->net_log().source().id;
284 is_first_stream = stream_->IsFirstStream();
285 load_timing_info->first_early_hints_time =
286 stream_->first_early_hints_time();
287 load_timing_info->receive_non_informational_headers_start =
288 stream_->headers_received_start_time();
289 load_timing_info->receive_headers_start =
290 load_timing_info->first_early_hints_time.is_null()
291 ? load_timing_info->receive_non_informational_headers_start
292 : load_timing_info->first_early_hints_time;
293 }
294
295 if (is_first_stream) {
296 load_timing_info->socket_reused = false;
297 load_timing_info->connect_timing = connect_timing_;
298 } else {
299 load_timing_info->socket_reused = true;
300 }
301 return true;
302 }
303
GetAlternativeService(AlternativeService * alternative_service) const304 bool QuicHttpStream::GetAlternativeService(
305 AlternativeService* alternative_service) const {
306 alternative_service->protocol = kProtoQUIC;
307 const url::SchemeHostPort& destination = quic_session()->destination();
308 alternative_service->host = destination.host();
309 alternative_service->port = destination.port();
310 return true;
311 }
312
PopulateNetErrorDetails(NetErrorDetails * details)313 void QuicHttpStream::PopulateNetErrorDetails(NetErrorDetails* details) {
314 details->connection_info =
315 ConnectionInfoFromQuicVersion(quic_session()->GetQuicVersion());
316 quic_session()->PopulateNetErrorDetails(details);
317 if (quic_session()->OneRttKeysAvailable() && stream_ &&
318 stream_->connection_error() != quic::QUIC_NO_ERROR) {
319 details->quic_connection_error = stream_->connection_error();
320 }
321 }
322
SetPriority(RequestPriority priority)323 void QuicHttpStream::SetPriority(RequestPriority priority) {
324 priority_ = priority;
325 }
326
OnReadResponseHeadersComplete(int rv)327 void QuicHttpStream::OnReadResponseHeadersComplete(int rv) {
328 DCHECK(callback_);
329 DCHECK(!response_headers_received_);
330 if (rv > 0) {
331 headers_bytes_received_ += rv;
332 rv = ProcessResponseHeaders(response_header_block_);
333 }
334 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
335 DoCallback(rv);
336 }
337 }
338
GetDnsAliases() const339 const std::set<std::string>& QuicHttpStream::GetDnsAliases() const {
340 return dns_aliases_;
341 }
342
GetAcceptChViaAlps() const343 std::string_view QuicHttpStream::GetAcceptChViaAlps() const {
344 if (!request_info_) {
345 return {};
346 }
347
348 return session()->GetAcceptChViaAlps(url::SchemeHostPort(request_info_->url));
349 }
350
351 std::optional<HttpStream::QuicErrorDetails>
GetQuicErrorDetails() const352 QuicHttpStream::GetQuicErrorDetails() const {
353 QuicErrorDetails details;
354 if (stream_) {
355 details.connection_error = stream_->connection_error();
356 details.stream_error = stream_->stream_error();
357 details.connection_wire_error = stream_->connection_wire_error();
358 details.ietf_application_error = stream_->ietf_application_error();
359 } else {
360 details.connection_error = connection_error_;
361 details.stream_error = stream_error_;
362 details.connection_wire_error = connection_wire_error_;
363 details.ietf_application_error = ietf_application_error_;
364 }
365 return details;
366 }
367
ReadTrailingHeaders()368 void QuicHttpStream::ReadTrailingHeaders() {
369 int rv = stream_->ReadTrailingHeaders(
370 &trailing_header_block_,
371 base::BindOnce(&QuicHttpStream::OnReadTrailingHeadersComplete,
372 weak_factory_.GetWeakPtr()));
373
374 if (rv != ERR_IO_PENDING) {
375 OnReadTrailingHeadersComplete(rv);
376 }
377 }
378
OnReadTrailingHeadersComplete(int rv)379 void QuicHttpStream::OnReadTrailingHeadersComplete(int rv) {
380 DCHECK(response_headers_received_);
381 if (rv > 0) {
382 headers_bytes_received_ += rv;
383 }
384
385 // QuicHttpStream ignores trailers.
386 if (stream_->IsDoneReading()) {
387 // Close the read side. If the write side has been closed, this will
388 // invoke QuicHttpStream::OnClose to reset the stream.
389 stream_->OnFinRead();
390 SetResponseStatus(OK);
391 }
392 }
393
OnIOComplete(int rv)394 void QuicHttpStream::OnIOComplete(int rv) {
395 rv = DoLoop(rv);
396
397 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
398 DoCallback(rv);
399 }
400 }
401
DoCallback(int rv)402 void QuicHttpStream::DoCallback(int rv) {
403 CHECK_NE(rv, ERR_IO_PENDING);
404 CHECK(!callback_.is_null());
405 CHECK(!in_loop_);
406
407 // The client callback can do anything, including destroying this class,
408 // so any pending callback must be issued after everything else is done.
409 std::move(callback_).Run(MapStreamError(rv));
410 }
411
DoLoop(int rv)412 int QuicHttpStream::DoLoop(int rv) {
413 CHECK(!in_loop_);
414 base::AutoReset<bool> auto_reset_in_loop(&in_loop_, true);
415 std::unique_ptr<quic::QuicConnection::ScopedPacketFlusher> packet_flusher =
416 quic_session()->CreatePacketBundler();
417 do {
418 State state = next_state_;
419 next_state_ = STATE_NONE;
420 switch (state) {
421 case STATE_REQUEST_STREAM:
422 CHECK_EQ(OK, rv);
423 rv = DoRequestStream();
424 break;
425 case STATE_REQUEST_STREAM_COMPLETE:
426 rv = DoRequestStreamComplete(rv);
427 break;
428 case STATE_SET_REQUEST_PRIORITY:
429 CHECK_EQ(OK, rv);
430 rv = DoSetRequestPriority();
431 break;
432 case STATE_SEND_HEADERS:
433 CHECK_EQ(OK, rv);
434 rv = DoSendHeaders();
435 break;
436 case STATE_SEND_HEADERS_COMPLETE:
437 rv = DoSendHeadersComplete(rv);
438 break;
439 case STATE_READ_REQUEST_BODY:
440 CHECK_EQ(OK, rv);
441 rv = DoReadRequestBody();
442 break;
443 case STATE_READ_REQUEST_BODY_COMPLETE:
444 rv = DoReadRequestBodyComplete(rv);
445 break;
446 case STATE_SEND_BODY:
447 CHECK_EQ(OK, rv);
448 rv = DoSendBody();
449 break;
450 case STATE_SEND_BODY_COMPLETE:
451 rv = DoSendBodyComplete(rv);
452 break;
453 case STATE_OPEN:
454 CHECK_EQ(OK, rv);
455 break;
456 default:
457 NOTREACHED() << "next_state_: " << next_state_;
458 }
459 } while (next_state_ != STATE_NONE && next_state_ != STATE_OPEN &&
460 rv != ERR_IO_PENDING);
461
462 return rv;
463 }
464
DoRequestStream()465 int QuicHttpStream::DoRequestStream() {
466 next_state_ = STATE_REQUEST_STREAM_COMPLETE;
467
468 return quic_session()->RequestStream(
469 !can_send_early_,
470 base::BindOnce(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()),
471 NetworkTrafficAnnotationTag(request_info_->traffic_annotation));
472 }
473
DoRequestStreamComplete(int rv)474 int QuicHttpStream::DoRequestStreamComplete(int rv) {
475 DCHECK(rv == OK || !stream_);
476 if (rv != OK) {
477 session_error_ = rv;
478 return GetResponseStatus();
479 }
480
481 stream_ = quic_session()->ReleaseStream();
482 DCHECK(stream_);
483 if (!stream_->IsOpen()) {
484 session_error_ = ERR_CONNECTION_CLOSED;
485 return GetResponseStatus();
486 }
487
488 if (request_info_->load_flags &
489 LOAD_DISABLE_CONNECTION_MIGRATION_TO_CELLULAR) {
490 stream_->DisableConnectionMigrationToCellularNetwork();
491 }
492
493 DCHECK(response_info_ == nullptr);
494
495 return OK;
496 }
497
DoSetRequestPriority()498 int QuicHttpStream::DoSetRequestPriority() {
499 // Set priority according to request
500 DCHECK(stream_);
501 DCHECK(response_info_);
502 DCHECK(request_info_);
503
504 uint8_t urgency = ConvertRequestPriorityToQuicPriority(priority_);
505 bool incremental = request_info_->priority_incremental;
506 stream_->SetPriority(
507 quic::QuicStreamPriority(quic::HttpStreamPriority{urgency, incremental}));
508 next_state_ = STATE_SEND_HEADERS;
509 return OK;
510 }
511
DoSendHeaders()512 int QuicHttpStream::DoSendHeaders() {
513 uint8_t urgency = ConvertRequestPriorityToQuicPriority(priority_);
514 bool incremental = request_info_->priority_incremental;
515 quic::QuicStreamPriority priority(
516 quic::HttpStreamPriority{urgency, incremental});
517 // Log the actual request with the URL Request's net log.
518 stream_net_log_.AddEvent(
519 NetLogEventType::HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS,
520 [&](NetLogCaptureMode capture_mode) {
521 return QuicRequestNetLogParams(stream_->id(), &request_headers_,
522 priority, capture_mode);
523 });
524 DispatchRequestHeadersCallback(request_headers_);
525 bool has_upload_data = request_body_stream_ != nullptr;
526
527 next_state_ = STATE_SEND_HEADERS_COMPLETE;
528 int rv = stream_->WriteHeaders(std::move(request_headers_), !has_upload_data,
529 nullptr);
530 if (rv > 0) {
531 headers_bytes_sent_ += rv;
532 }
533
534 request_headers_ = quiche::HttpHeaderBlock();
535 return rv;
536 }
537
DoSendHeadersComplete(int rv)538 int QuicHttpStream::DoSendHeadersComplete(int rv) {
539 if (rv < 0) {
540 return rv;
541 }
542
543 next_state_ = request_body_stream_ ? STATE_READ_REQUEST_BODY : STATE_OPEN;
544
545 return OK;
546 }
547
DoReadRequestBody()548 int QuicHttpStream::DoReadRequestBody() {
549 next_state_ = STATE_READ_REQUEST_BODY_COMPLETE;
550 return request_body_stream_->Read(
551 raw_request_body_buf_.get(), raw_request_body_buf_->size(),
552 base::BindOnce(&QuicHttpStream::OnIOComplete,
553 weak_factory_.GetWeakPtr()));
554 }
555
DoReadRequestBodyComplete(int rv)556 int QuicHttpStream::DoReadRequestBodyComplete(int rv) {
557 // |rv| is the result of read from the request body from the last call to
558 // DoSendBody().
559 if (rv < 0) {
560 stream_->Reset(quic::QUIC_ERROR_PROCESSING_STREAM);
561 ResetStream();
562 return rv;
563 }
564
565 request_body_buf_ =
566 base::MakeRefCounted<DrainableIOBuffer>(raw_request_body_buf_, rv);
567 if (rv == 0) { // Reached the end.
568 DCHECK(request_body_stream_->IsEOF());
569 }
570
571 next_state_ = STATE_SEND_BODY;
572 return OK;
573 }
574
DoSendBody()575 int QuicHttpStream::DoSendBody() {
576 CHECK(request_body_stream_);
577 CHECK(request_body_buf_.get());
578 const bool eof = request_body_stream_->IsEOF();
579 int len = request_body_buf_->BytesRemaining();
580 if (len > 0 || eof) {
581 next_state_ = STATE_SEND_BODY_COMPLETE;
582 std::string_view data(request_body_buf_->data(), len);
583 return stream_->WriteStreamData(
584 data, eof,
585 base::BindOnce(&QuicHttpStream::OnIOComplete,
586 weak_factory_.GetWeakPtr()));
587 }
588
589 next_state_ = STATE_OPEN;
590 return OK;
591 }
592
DoSendBodyComplete(int rv)593 int QuicHttpStream::DoSendBodyComplete(int rv) {
594 if (rv < 0) {
595 return rv;
596 }
597
598 request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
599
600 if (!request_body_stream_->IsEOF()) {
601 next_state_ = STATE_READ_REQUEST_BODY;
602 return OK;
603 }
604
605 next_state_ = STATE_OPEN;
606 return OK;
607 }
608
ProcessResponseHeaders(const quiche::HttpHeaderBlock & headers)609 int QuicHttpStream::ProcessResponseHeaders(
610 const quiche::HttpHeaderBlock& headers) {
611 const int rv = SpdyHeadersToHttpResponse(headers, response_info_);
612 base::UmaHistogramBoolean("Net.QuicHttpStream.ProcessResponseHeaderSuccess",
613 rv == OK);
614 if (rv != OK) {
615 DLOG(WARNING) << "Invalid headers";
616 return ERR_QUIC_PROTOCOL_ERROR;
617 }
618
619 if (response_info_->headers->response_code() == HTTP_EARLY_HINTS) {
620 DCHECK(!response_headers_received_);
621 headers_bytes_received_ = 0;
622 return OK;
623 }
624
625 response_info_->connection_info =
626 ConnectionInfoFromQuicVersion(quic_session()->GetQuicVersion());
627 response_info_->was_alpn_negotiated = true;
628 response_info_->alpn_negotiated_protocol =
629 HttpConnectionInfoToString(response_info_->connection_info);
630 response_info_->response_time = response_info_->original_response_time =
631 base::Time::Now();
632 response_info_->request_time = request_time_;
633 response_headers_received_ = true;
634
635 // Populate |connect_timing_| when response headers are received. This should
636 // take care of 0-RTT where request is sent before handshake is confirmed.
637 connect_timing_ = quic_session()->GetConnectTiming();
638
639 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
640 FROM_HERE, base::BindOnce(&QuicHttpStream::ReadTrailingHeaders,
641 weak_factory_.GetWeakPtr()));
642
643 if (stream_->IsDoneReading()) {
644 session_error_ = OK;
645 SaveResponseStatus();
646 stream_->OnFinRead();
647 }
648
649 return OK;
650 }
651
OnReadBodyComplete(int rv)652 void QuicHttpStream::OnReadBodyComplete(int rv) {
653 CHECK(callback_);
654 user_buffer_ = nullptr;
655 user_buffer_len_ = 0;
656 rv = HandleReadComplete(rv);
657 DoCallback(rv);
658 }
659
HandleReadComplete(int rv)660 int QuicHttpStream::HandleReadComplete(int rv) {
661 if (stream_->IsDoneReading()) {
662 stream_->OnFinRead();
663 SetResponseStatus(OK);
664 ResetStream();
665 }
666 return rv;
667 }
668
ResetStream()669 void QuicHttpStream::ResetStream() {
670 // If |request_body_stream_| is non-NULL, Reset it, to abort any in progress
671 // read.
672 if (request_body_stream_) {
673 request_body_stream_->Reset();
674 }
675
676 if (!stream_) {
677 return;
678 }
679
680 DCHECK_LE(stream_->NumBytesConsumed(), stream_->stream_bytes_read());
681 // Only count the uniquely received bytes.
682 closed_stream_received_bytes_ = stream_->NumBytesConsumed();
683 closed_stream_sent_bytes_ = stream_->stream_bytes_written();
684 closed_is_first_stream_ = stream_->IsFirstStream();
685 connection_error_ = stream_->connection_error();
686 stream_error_ = stream_->stream_error();
687 connection_wire_error_ = stream_->connection_wire_error();
688 ietf_application_error_ = stream_->ietf_application_error();
689 }
690
MapStreamError(int rv)691 int QuicHttpStream::MapStreamError(int rv) {
692 if (rv == ERR_QUIC_PROTOCOL_ERROR && !quic_session()->OneRttKeysAvailable()) {
693 return ERR_QUIC_HANDSHAKE_FAILED;
694 }
695 return rv;
696 }
697
GetResponseStatus()698 int QuicHttpStream::GetResponseStatus() {
699 SaveResponseStatus();
700 return response_status_;
701 }
702
SaveResponseStatus()703 void QuicHttpStream::SaveResponseStatus() {
704 if (!has_response_status_) {
705 SetResponseStatus(ComputeResponseStatus());
706 }
707 }
708
SetResponseStatus(int response_status)709 void QuicHttpStream::SetResponseStatus(int response_status) {
710 has_response_status_ = true;
711 response_status_ = response_status;
712 }
713
ComputeResponseStatus() const714 int QuicHttpStream::ComputeResponseStatus() const {
715 DCHECK(!has_response_status_);
716
717 // If the handshake has failed this will be handled by the QuicSessionPool
718 // and HttpStreamFactory to mark QUIC as broken if TCP is actually working.
719 if (!quic_session()->OneRttKeysAvailable()) {
720 return ERR_QUIC_HANDSHAKE_FAILED;
721 }
722
723 // If the session was aborted by a higher layer, simply use that error code.
724 if (session_error_ != ERR_UNEXPECTED) {
725 return session_error_;
726 }
727
728 // If |response_info_| is null then the request has not been sent, so
729 // return ERR_CONNECTION_CLOSED to permit HttpNetworkTransaction to
730 // retry the request.
731 if (!response_info_) {
732 return ERR_CONNECTION_CLOSED;
733 }
734
735 base::UmaHistogramEnumeration("Net.QuicHttpStream.ResponseStatus",
736 stream_->stream_error(),
737 quic::QUIC_STREAM_LAST_ERROR);
738
739 return ERR_QUIC_PROTOCOL_ERROR;
740 }
741
SetRequestIdempotency(Idempotency idempotency)742 void QuicHttpStream::SetRequestIdempotency(Idempotency idempotency) {
743 if (stream_ == nullptr) {
744 return;
745 }
746 stream_->SetRequestIdempotency(idempotency);
747 }
748
749 } // namespace net
750