xref: /aosp_15_r20/external/cronet/net/quic/quic_http_stream.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/quic/core/http/spdy_utils.h"
30 #include "net/third_party/quiche/src/quiche/quic/core/quic_stream_sequencer.h"
31 #include "net/third_party/quiche/src/quiche/quic/core/quic_utils.h"
32 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_frame_builder.h"
33 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_framer.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   return HttpConnectionInfo::kQUIC_UNKNOWN_VERSION;
71 }
72 
RegisterRequest(const HttpRequestInfo * request_info)73 void QuicHttpStream::RegisterRequest(const HttpRequestInfo* request_info) {
74   DCHECK(request_info);
75   DCHECK(request_info->traffic_annotation.is_valid());
76   request_info_ = request_info;
77 }
78 
InitializeStream(bool can_send_early,RequestPriority priority,const NetLogWithSource & stream_net_log,CompletionOnceCallback callback)79 int QuicHttpStream::InitializeStream(bool can_send_early,
80                                      RequestPriority priority,
81                                      const NetLogWithSource& stream_net_log,
82                                      CompletionOnceCallback callback) {
83   CHECK(callback_.is_null());
84   DCHECK(request_info_);
85   DCHECK(!stream_);
86 
87   // HttpNetworkTransaction will retry any request that fails with
88   // ERR_QUIC_HANDSHAKE_FAILED. It will retry any request with
89   // ERR_CONNECTION_CLOSED so long as the connection has been used for other
90   // streams first and headers have not yet been received.
91   if (!quic_session()->IsConnected()) {
92     return GetResponseStatus();
93   }
94 
95   stream_net_log.AddEventReferencingSource(
96       NetLogEventType::HTTP_STREAM_REQUEST_BOUND_TO_QUIC_SESSION,
97       quic_session()->net_log().source());
98   stream_net_log.AddEventWithIntParams(
99       NetLogEventType::QUIC_CONNECTION_MIGRATION_MODE,
100       "connection_migration_mode",
101       static_cast<int>(quic_session()->connection_migration_mode()));
102 
103   stream_net_log_ = stream_net_log;
104   can_send_early_ = can_send_early;
105   request_time_ = base::Time::Now();
106   priority_ = priority;
107 
108   SaveSSLInfo();
109 
110   next_state_ = STATE_REQUEST_STREAM;
111   int rv = DoLoop(OK);
112   if (rv == ERR_IO_PENDING) {
113     callback_ = std::move(callback);
114   }
115 
116   return MapStreamError(rv);
117 }
118 
SendRequest(const HttpRequestHeaders & request_headers,HttpResponseInfo * response,CompletionOnceCallback callback)119 int QuicHttpStream::SendRequest(const HttpRequestHeaders& request_headers,
120                                 HttpResponseInfo* response,
121                                 CompletionOnceCallback callback) {
122   CHECK(!request_body_stream_);
123   CHECK(!response_info_);
124   CHECK(callback_.is_null());
125   CHECK(!callback.is_null());
126   CHECK(response);
127 
128   if (!stream_ || !quic_session()->IsConnected()) {
129     return GetResponseStatus();
130   }
131 
132   // Store the serialized request headers.
133   CreateSpdyHeadersFromHttpRequest(*request_info_, priority_, request_headers,
134                                    &request_headers_);
135 
136   // Store the request body.
137   request_body_stream_ = request_info_->upload_data_stream;
138   if (request_body_stream_) {
139     // TODO(rch): Can we be more precise about when to allocate
140     // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
141     // was being called even if we didn't yet allocate raw_request_body_buf_.
142     //   && (request_body_stream_->size() ||
143     //       request_body_stream_->is_chunked()))
144     // Set the body buffer size to be the size of the body clamped
145     // into the range [10 * quic::kMaxOutgoingPacketSize, 256 *
146     // quic::kMaxOutgoingPacketSize]. With larger bodies, larger buffers reduce
147     // CPU usage.
148     raw_request_body_buf_ =
149         base::MakeRefCounted<IOBufferWithSize>(static_cast<size_t>(
150             std::max(10 * quic::kMaxOutgoingPacketSize,
151                      std::min(request_body_stream_->size(),
152                               256 * quic::kMaxOutgoingPacketSize))));
153     // The request body buffer is empty at first.
154     request_body_buf_ =
155         base::MakeRefCounted<DrainableIOBuffer>(raw_request_body_buf_, 0);
156   }
157 
158   // Store the response info.
159   response_info_ = response;
160 
161   // Put the peer's IP address and port into the response.
162   IPEndPoint address;
163   int rv = quic_session()->GetPeerAddress(&address);
164   if (rv != OK) {
165     return rv;
166   }
167   response_info_->remote_endpoint = address;
168 
169   next_state_ = STATE_SET_REQUEST_PRIORITY;
170   rv = DoLoop(OK);
171 
172   if (rv == ERR_IO_PENDING) {
173     callback_ = std::move(callback);
174   }
175 
176   return rv > 0 ? OK : MapStreamError(rv);
177 }
178 
ReadResponseHeaders(CompletionOnceCallback callback)179 int QuicHttpStream::ReadResponseHeaders(CompletionOnceCallback callback) {
180   CHECK(callback_.is_null());
181   CHECK(!callback.is_null());
182 
183   int rv = stream_->ReadInitialHeaders(
184       &response_header_block_,
185       base::BindOnce(&QuicHttpStream::OnReadResponseHeadersComplete,
186                      weak_factory_.GetWeakPtr()));
187 
188   if (rv == ERR_IO_PENDING) {
189     // Still waiting for the response, return IO_PENDING.
190     CHECK(callback_.is_null());
191     callback_ = std::move(callback);
192     return ERR_IO_PENDING;
193   }
194 
195   if (rv < 0) {
196     return MapStreamError(rv);
197   }
198 
199   // Check if we already have the response headers. If so, return synchronously.
200   if (response_headers_received_) {
201     return OK;
202   }
203 
204   headers_bytes_received_ += rv;
205   return ProcessResponseHeaders(response_header_block_);
206 }
207 
ReadResponseBody(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)208 int QuicHttpStream::ReadResponseBody(IOBuffer* buf,
209                                      int buf_len,
210                                      CompletionOnceCallback callback) {
211   CHECK(callback_.is_null());
212   CHECK(!callback.is_null());
213   CHECK(!user_buffer_.get());
214   CHECK_EQ(0, user_buffer_len_);
215 
216   // Invalidate HttpRequestInfo pointer. This is to allow the stream to be
217   // shared across multiple transactions which might require this
218   // stream to outlive the request_info_'s owner.
219   // Only allowed when Read state machine starts. It is safe to reset it at
220   // this point since request_info_->upload_data_stream is also not needed
221   // anymore.
222   request_info_ = nullptr;
223 
224   // If the stream is already closed, there is no body to read.
225   if (stream_->IsDoneReading()) {
226     return HandleReadComplete(OK);
227   }
228 
229   int rv = stream_->ReadBody(buf, buf_len,
230                              base::BindOnce(&QuicHttpStream::OnReadBodyComplete,
231                                             weak_factory_.GetWeakPtr()));
232   if (rv == ERR_IO_PENDING) {
233     callback_ = std::move(callback);
234     user_buffer_ = buf;
235     user_buffer_len_ = buf_len;
236     return ERR_IO_PENDING;
237   }
238 
239   if (rv < 0) {
240     return MapStreamError(rv);
241   }
242 
243   return HandleReadComplete(rv);
244 }
245 
Close(bool)246 void QuicHttpStream::Close(bool /*not_reusable*/) {
247   session_error_ = ERR_ABORTED;
248   SaveResponseStatus();
249   // Note: the not_reusable flag has no meaning for QUIC streams.
250   if (stream_) {
251     stream_->Reset(quic::QUIC_STREAM_CANCELLED);
252   }
253   ResetStream();
254 }
255 
IsResponseBodyComplete() const256 bool QuicHttpStream::IsResponseBodyComplete() const {
257   return next_state_ == STATE_OPEN && stream_->IsDoneReading();
258 }
259 
IsConnectionReused() const260 bool QuicHttpStream::IsConnectionReused() const {
261   // TODO(rch): do something smarter here.
262   return stream_ && stream_->id() > 1;
263 }
264 
GetTotalReceivedBytes() const265 int64_t QuicHttpStream::GetTotalReceivedBytes() const {
266   if (stream_) {
267     DCHECK_LE(stream_->NumBytesConsumed(), stream_->stream_bytes_read());
268     // Only count the uniquely received bytes.
269     return stream_->NumBytesConsumed();
270   }
271   return closed_stream_received_bytes_;
272 }
273 
GetTotalSentBytes() const274 int64_t QuicHttpStream::GetTotalSentBytes() const {
275   if (stream_) {
276     return stream_->stream_bytes_written();
277   }
278   return closed_stream_sent_bytes_;
279 }
280 
GetLoadTimingInfo(LoadTimingInfo * load_timing_info) const281 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
282   bool is_first_stream = closed_is_first_stream_;
283   if (stream_) {
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         break;
459     }
460   } while (next_state_ != STATE_NONE && next_state_ != STATE_OPEN &&
461            rv != ERR_IO_PENDING);
462 
463   return rv;
464 }
465 
DoRequestStream()466 int QuicHttpStream::DoRequestStream() {
467   next_state_ = STATE_REQUEST_STREAM_COMPLETE;
468 
469   return quic_session()->RequestStream(
470       !can_send_early_,
471       base::BindOnce(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()),
472       NetworkTrafficAnnotationTag(request_info_->traffic_annotation));
473 }
474 
DoRequestStreamComplete(int rv)475 int QuicHttpStream::DoRequestStreamComplete(int rv) {
476   DCHECK(rv == OK || !stream_);
477   if (rv != OK) {
478     session_error_ = rv;
479     return GetResponseStatus();
480   }
481 
482   stream_ = quic_session()->ReleaseStream();
483   DCHECK(stream_);
484   if (!stream_->IsOpen()) {
485     session_error_ = ERR_CONNECTION_CLOSED;
486     return GetResponseStatus();
487   }
488 
489   if (request_info_->load_flags &
490       LOAD_DISABLE_CONNECTION_MIGRATION_TO_CELLULAR) {
491     stream_->DisableConnectionMigrationToCellularNetwork();
492   }
493 
494   DCHECK(response_info_ == nullptr);
495 
496   return OK;
497 }
498 
DoSetRequestPriority()499 int QuicHttpStream::DoSetRequestPriority() {
500   // Set priority according to request
501   DCHECK(stream_);
502   DCHECK(response_info_);
503   DCHECK(request_info_);
504 
505   uint8_t urgency = ConvertRequestPriorityToQuicPriority(priority_);
506   bool incremental = request_info_->priority_incremental;
507   stream_->SetPriority(
508       quic::QuicStreamPriority(quic::HttpStreamPriority{urgency, incremental}));
509   next_state_ = STATE_SEND_HEADERS;
510   return OK;
511 }
512 
DoSendHeaders()513 int QuicHttpStream::DoSendHeaders() {
514   uint8_t urgency = ConvertRequestPriorityToQuicPriority(priority_);
515   bool incremental = request_info_->priority_incremental;
516   quic::QuicStreamPriority priority(
517       quic::HttpStreamPriority{urgency, incremental});
518   // Log the actual request with the URL Request's net log.
519   stream_net_log_.AddEvent(
520       NetLogEventType::HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS,
521       [&](NetLogCaptureMode capture_mode) {
522         return QuicRequestNetLogParams(stream_->id(), &request_headers_,
523                                        priority, capture_mode);
524       });
525   DispatchRequestHeadersCallback(request_headers_);
526   bool has_upload_data = request_body_stream_ != nullptr;
527 
528   next_state_ = STATE_SEND_HEADERS_COMPLETE;
529   int rv = stream_->WriteHeaders(std::move(request_headers_), !has_upload_data,
530                                  nullptr);
531   if (rv > 0) {
532     headers_bytes_sent_ += rv;
533   }
534 
535   request_headers_ = spdy::Http2HeaderBlock();
536   return rv;
537 }
538 
DoSendHeadersComplete(int rv)539 int QuicHttpStream::DoSendHeadersComplete(int rv) {
540   if (rv < 0) {
541     return rv;
542   }
543 
544   next_state_ = request_body_stream_ ? STATE_READ_REQUEST_BODY : STATE_OPEN;
545 
546   return OK;
547 }
548 
DoReadRequestBody()549 int QuicHttpStream::DoReadRequestBody() {
550   next_state_ = STATE_READ_REQUEST_BODY_COMPLETE;
551   return request_body_stream_->Read(
552       raw_request_body_buf_.get(), raw_request_body_buf_->size(),
553       base::BindOnce(&QuicHttpStream::OnIOComplete,
554                      weak_factory_.GetWeakPtr()));
555 }
556 
DoReadRequestBodyComplete(int rv)557 int QuicHttpStream::DoReadRequestBodyComplete(int rv) {
558   // |rv| is the result of read from the request body from the last call to
559   // DoSendBody().
560   if (rv < 0) {
561     stream_->Reset(quic::QUIC_ERROR_PROCESSING_STREAM);
562     ResetStream();
563     return rv;
564   }
565 
566   request_body_buf_ =
567       base::MakeRefCounted<DrainableIOBuffer>(raw_request_body_buf_, rv);
568   if (rv == 0) {  // Reached the end.
569     DCHECK(request_body_stream_->IsEOF());
570   }
571 
572   next_state_ = STATE_SEND_BODY;
573   return OK;
574 }
575 
DoSendBody()576 int QuicHttpStream::DoSendBody() {
577   CHECK(request_body_stream_);
578   CHECK(request_body_buf_.get());
579   const bool eof = request_body_stream_->IsEOF();
580   int len = request_body_buf_->BytesRemaining();
581   if (len > 0 || eof) {
582     next_state_ = STATE_SEND_BODY_COMPLETE;
583     std::string_view data(request_body_buf_->data(), len);
584     return stream_->WriteStreamData(
585         data, eof,
586         base::BindOnce(&QuicHttpStream::OnIOComplete,
587                        weak_factory_.GetWeakPtr()));
588   }
589 
590   next_state_ = STATE_OPEN;
591   return OK;
592 }
593 
DoSendBodyComplete(int rv)594 int QuicHttpStream::DoSendBodyComplete(int rv) {
595   if (rv < 0) {
596     return rv;
597   }
598 
599   request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
600 
601   if (!request_body_stream_->IsEOF()) {
602     next_state_ = STATE_READ_REQUEST_BODY;
603     return OK;
604   }
605 
606   next_state_ = STATE_OPEN;
607   return OK;
608 }
609 
ProcessResponseHeaders(const spdy::Http2HeaderBlock & headers)610 int QuicHttpStream::ProcessResponseHeaders(
611     const spdy::Http2HeaderBlock& headers) {
612   const int rv = SpdyHeadersToHttpResponse(headers, response_info_);
613   base::UmaHistogramBoolean("Net.QuicHttpStream.ProcessResponseHeaderSuccess",
614                             rv == OK);
615   if (rv != OK) {
616     DLOG(WARNING) << "Invalid headers";
617     return ERR_QUIC_PROTOCOL_ERROR;
618   }
619 
620   if (response_info_->headers->response_code() == HTTP_EARLY_HINTS) {
621     DCHECK(!response_headers_received_);
622     headers_bytes_received_ = 0;
623     return OK;
624   }
625 
626   response_info_->connection_info =
627       ConnectionInfoFromQuicVersion(quic_session()->GetQuicVersion());
628   response_info_->was_alpn_negotiated = true;
629   response_info_->alpn_negotiated_protocol =
630       HttpConnectionInfoToString(response_info_->connection_info);
631   response_info_->response_time = 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