1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_http_stream.h"
7 #include "base/callback_helpers.h"
8 #include "base/metrics/histogram.h"
9 #include "base/strings/stringprintf.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/net_errors.h"
12 #include "net/http/http_response_headers.h"
13 #include "net/http/http_util.h"
14 #include "net/quic/quic_client_session.h"
15 #include "net/quic/quic_http_utils.h"
16 #include "net/quic/quic_reliable_client_stream.h"
17 #include "net/quic/quic_utils.h"
18 #include "net/quic/spdy_utils.h"
19 #include "net/socket/next_proto.h"
20 #include "net/spdy/spdy_frame_builder.h"
21 #include "net/spdy/spdy_framer.h"
22 #include "net/spdy/spdy_http_utils.h"
23 #include "net/ssl/ssl_info.h"
27 static const size_t kHeaderBufInitialSize
= 4096;
29 QuicHttpStream::QuicHttpStream(const base::WeakPtr
<QuicClientSession
>& session
)
30 : next_state_(STATE_NONE
),
33 was_handshake_confirmed_(session
->IsCryptoHandshakeConfirmed()),
35 request_info_(nullptr),
36 request_body_stream_(nullptr),
37 priority_(MINIMUM_PRIORITY
),
38 response_info_(nullptr),
40 response_headers_received_(false),
41 read_buf_(new GrowableIOBuffer()),
42 closed_stream_received_bytes_(0),
46 session_
->AddObserver(this);
49 QuicHttpStream::~QuicHttpStream() {
52 session_
->RemoveObserver(this);
55 int QuicHttpStream::InitializeStream(const HttpRequestInfo
* request_info
,
56 RequestPriority priority
,
57 const BoundNetLog
& stream_net_log
,
58 const CompletionCallback
& callback
) {
61 return was_handshake_confirmed_
? ERR_CONNECTION_CLOSED
:
62 ERR_QUIC_HANDSHAKE_FAILED
;
64 stream_net_log
.AddEvent(
65 NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_QUIC_SESSION
,
66 session_
->net_log().source().ToEventParametersCallback());
68 if (request_info
->url
.SchemeIsSecure()) {
71 session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
.get();
72 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
75 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC
;
78 stream_net_log_
= stream_net_log
;
79 request_info_
= request_info
;
80 request_time_
= base::Time::Now();
83 int rv
= stream_request_
.StartRequest(
84 session_
, &stream_
, base::Bind(&QuicHttpStream::OnStreamReady
,
85 weak_factory_
.GetWeakPtr()));
86 if (rv
== ERR_IO_PENDING
) {
88 } else if (rv
== OK
) {
89 stream_
->SetDelegate(this);
90 } else if (!was_handshake_confirmed_
) {
91 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
97 void QuicHttpStream::OnStreamReady(int rv
) {
98 DCHECK(rv
== OK
|| !stream_
);
100 stream_
->SetDelegate(this);
101 } else if (!was_handshake_confirmed_
) {
102 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
105 ResetAndReturn(&callback_
).Run(rv
);
108 int QuicHttpStream::SendRequest(const HttpRequestHeaders
& request_headers
,
109 HttpResponseInfo
* response
,
110 const CompletionCallback
& callback
) {
111 CHECK(!request_body_stream_
);
112 CHECK(!response_info_
);
113 CHECK(!callback
.is_null());
116 // TODO(rch): remove this once we figure out why channel ID is not being
117 // sent when it should be.
118 HostPortPair origin
= HostPortPair::FromURL(request_info_
->url
);
119 if (origin
.Equals(HostPortPair("accounts.google.com", 443)) &&
120 request_headers
.HasHeader(HttpRequestHeaders::kCookie
)) {
122 bool secure_session
=
123 session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
.get();
124 DCHECK(secure_session
);
125 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.CookieSentToAccountsOverChannelId",
126 ssl_info
.channel_id_sent
);
129 return ERR_CONNECTION_CLOSED
;
132 QuicPriority priority
= ConvertRequestPriorityToQuicPriority(priority_
);
133 stream_
->set_priority(priority
);
134 // Store the serialized request headers.
135 CreateSpdyHeadersFromHttpRequest(*request_info_
, request_headers
,
137 /*direct=*/true, &request_headers_
);
139 // Store the request body.
140 request_body_stream_
= request_info_
->upload_data_stream
;
141 if (request_body_stream_
) {
142 // TODO(rch): Can we be more precise about when to allocate
143 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
144 // was being called even if we didn't yet allocate raw_request_body_buf_.
145 // && (request_body_stream_->size() ||
146 // request_body_stream_->is_chunked()))
147 // Use 10 packets as the body buffer size to give enough space to
148 // help ensure we don't often send out partial packets.
149 raw_request_body_buf_
= new IOBufferWithSize(10 * kMaxPacketSize
);
150 // The request body buffer is empty at first.
151 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), 0);
154 // Store the response info.
155 response_info_
= response
;
157 next_state_
= STATE_SEND_HEADERS
;
159 if (rv
== ERR_IO_PENDING
)
160 callback_
= callback
;
162 return rv
> 0 ? OK
: rv
;
165 UploadProgress
QuicHttpStream::GetUploadProgress() const {
166 if (!request_body_stream_
)
167 return UploadProgress();
169 return UploadProgress(request_body_stream_
->position(),
170 request_body_stream_
->size());
173 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback
& callback
) {
174 CHECK(!callback
.is_null());
176 if (stream_
== nullptr)
177 return response_status_
;
179 // Check if we already have the response headers. If so, return synchronously.
180 if (response_headers_received_
)
183 // Still waiting for the response, return IO_PENDING.
184 CHECK(callback_
.is_null());
185 callback_
= callback
;
186 return ERR_IO_PENDING
;
189 int QuicHttpStream::ReadResponseBody(
190 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
193 CHECK(!callback
.is_null());
195 // If we have data buffered, complete the IO immediately.
196 if (!response_body_
.empty()) {
198 while (!response_body_
.empty() && buf_len
> 0) {
199 scoped_refptr
<IOBufferWithSize
> data
= response_body_
.front();
200 const int bytes_to_copy
= std::min(buf_len
, data
->size());
201 memcpy(&(buf
->data()[bytes_read
]), data
->data(), bytes_to_copy
);
202 buf_len
-= bytes_to_copy
;
203 if (bytes_to_copy
== data
->size()) {
204 response_body_
.pop_front();
206 const int bytes_remaining
= data
->size() - bytes_to_copy
;
207 IOBufferWithSize
* new_buffer
= new IOBufferWithSize(bytes_remaining
);
208 memcpy(new_buffer
->data(), &(data
->data()[bytes_to_copy
]),
210 response_body_
.pop_front();
211 response_body_
.push_front(make_scoped_refptr(new_buffer
));
213 bytes_read
+= bytes_to_copy
;
219 // If the stream is already closed, there is no body to read.
220 return response_status_
;
223 CHECK(callback_
.is_null());
224 CHECK(!user_buffer_
.get());
225 CHECK_EQ(0, user_buffer_len_
);
227 callback_
= callback
;
229 user_buffer_len_
= buf_len
;
230 return ERR_IO_PENDING
;
233 void QuicHttpStream::Close(bool not_reusable
) {
234 // Note: the not_reusable flag has no meaning for SPDY streams.
236 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
237 stream_
->SetDelegate(nullptr);
238 stream_
->Reset(QUIC_STREAM_CANCELLED
);
240 response_status_
= was_handshake_confirmed_
?
241 ERR_CONNECTION_CLOSED
: ERR_QUIC_HANDSHAKE_FAILED
;
245 HttpStream
* QuicHttpStream::RenewStreamForAuth() {
249 bool QuicHttpStream::IsResponseBodyComplete() const {
250 return next_state_
== STATE_OPEN
&& !stream_
;
253 bool QuicHttpStream::CanFindEndOfResponse() const {
257 bool QuicHttpStream::IsConnectionReused() const {
258 // TODO(rch): do something smarter here.
259 return stream_
&& stream_
->id() > 1;
262 void QuicHttpStream::SetConnectionReused() {
263 // QUIC doesn't need an indicator here.
266 bool QuicHttpStream::IsConnectionReusable() const {
267 // QUIC streams aren't considered reusable.
271 int64
QuicHttpStream::GetTotalReceivedBytes() const {
273 return stream_
->stream_bytes_read();
276 return closed_stream_received_bytes_
;
279 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
280 // TODO(mmenke): Figure out what to do here.
284 void QuicHttpStream::GetSSLInfo(SSLInfo
* ssl_info
) {
286 session_
->GetSSLInfo(ssl_info
);
289 void QuicHttpStream::GetSSLCertRequestInfo(
290 SSLCertRequestInfo
* cert_request_info
) {
295 bool QuicHttpStream::IsSpdyHttpStream() const {
299 void QuicHttpStream::Drain(HttpNetworkSession
* session
) {
304 void QuicHttpStream::SetPriority(RequestPriority priority
) {
305 priority_
= priority
;
308 int QuicHttpStream::OnDataReceived(const char* data
, int length
) {
309 DCHECK_NE(0, length
);
310 // Are we still reading the response headers.
311 if (!response_headers_received_
) {
312 // Grow the read buffer if necessary.
313 if (read_buf_
->RemainingCapacity() < length
) {
314 size_t additional_capacity
= length
- read_buf_
->RemainingCapacity();
315 if (additional_capacity
< kHeaderBufInitialSize
)
316 additional_capacity
= kHeaderBufInitialSize
;
317 read_buf_
->SetCapacity(read_buf_
->capacity() + additional_capacity
);
319 memcpy(read_buf_
->data(), data
, length
);
320 read_buf_
->set_offset(read_buf_
->offset() + length
);
321 int rv
= ParseResponseHeaders();
322 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
328 if (callback_
.is_null()) {
329 BufferResponseBody(data
, length
);
333 if (length
<= user_buffer_len_
) {
334 memcpy(user_buffer_
->data(), data
, length
);
336 memcpy(user_buffer_
->data(), data
, user_buffer_len_
);
337 int delta
= length
- user_buffer_len_
;
338 BufferResponseBody(data
+ user_buffer_len_
, delta
);
339 length
= user_buffer_len_
;
342 user_buffer_
= nullptr;
343 user_buffer_len_
= 0;
348 void QuicHttpStream::OnClose(QuicErrorCode error
) {
349 if (error
!= QUIC_NO_ERROR
) {
350 response_status_
= was_handshake_confirmed_
?
351 ERR_QUIC_PROTOCOL_ERROR
: ERR_QUIC_HANDSHAKE_FAILED
;
352 } else if (!response_headers_received_
) {
353 response_status_
= ERR_ABORTED
;
356 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
358 if (!callback_
.is_null())
359 DoCallback(response_status_
);
362 void QuicHttpStream::OnError(int error
) {
364 response_status_
= was_handshake_confirmed_
?
365 error
: ERR_QUIC_HANDSHAKE_FAILED
;
366 if (!callback_
.is_null())
367 DoCallback(response_status_
);
370 bool QuicHttpStream::HasSendHeadersComplete() {
371 return next_state_
> STATE_SEND_HEADERS_COMPLETE
;
374 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
375 was_handshake_confirmed_
= true;
378 void QuicHttpStream::OnSessionClosed(int error
) {
380 session_error_
= error
;
384 void QuicHttpStream::OnIOComplete(int rv
) {
387 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
392 void QuicHttpStream::DoCallback(int rv
) {
393 CHECK_NE(rv
, ERR_IO_PENDING
);
394 CHECK(!callback_
.is_null());
396 // The client callback can do anything, including destroying this class,
397 // so any pending callback must be issued after everything else is done.
398 base::ResetAndReturn(&callback_
).Run(rv
);
401 int QuicHttpStream::DoLoop(int rv
) {
403 State state
= next_state_
;
404 next_state_
= STATE_NONE
;
406 case STATE_SEND_HEADERS
:
408 rv
= DoSendHeaders();
410 case STATE_SEND_HEADERS_COMPLETE
:
411 rv
= DoSendHeadersComplete(rv
);
413 case STATE_READ_REQUEST_BODY
:
415 rv
= DoReadRequestBody();
417 case STATE_READ_REQUEST_BODY_COMPLETE
:
418 rv
= DoReadRequestBodyComplete(rv
);
420 case STATE_SEND_BODY
:
424 case STATE_SEND_BODY_COMPLETE
:
425 rv
= DoSendBodyComplete(rv
);
431 NOTREACHED() << "next_state_: " << next_state_
;
434 } while (next_state_
!= STATE_NONE
&& next_state_
!= STATE_OPEN
&&
435 rv
!= ERR_IO_PENDING
);
440 int QuicHttpStream::DoSendHeaders() {
442 return ERR_UNEXPECTED
;
444 // Log the actual request with the URL Request's net log.
445 stream_net_log_
.AddEvent(
446 NetLog::TYPE_HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS
,
447 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
449 // Also log to the QuicSession's net log.
450 stream_
->net_log().AddEvent(
451 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS
,
452 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
455 bool has_upload_data
= request_body_stream_
!= nullptr;
457 next_state_
= STATE_SEND_HEADERS_COMPLETE
;
458 int rv
= stream_
->WriteHeaders(request_headers_
, !has_upload_data
, nullptr);
459 request_headers_
.clear();
463 int QuicHttpStream::DoSendHeadersComplete(int rv
) {
467 next_state_
= request_body_stream_
?
468 STATE_READ_REQUEST_BODY
: STATE_OPEN
;
473 int QuicHttpStream::DoReadRequestBody() {
474 next_state_
= STATE_READ_REQUEST_BODY_COMPLETE
;
475 return request_body_stream_
->Read(
476 raw_request_body_buf_
.get(),
477 raw_request_body_buf_
->size(),
478 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
481 int QuicHttpStream::DoReadRequestBodyComplete(int rv
) {
482 // |rv| is the result of read from the request body from the last call to
487 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), rv
);
488 if (rv
== 0) { // Reached the end.
489 DCHECK(request_body_stream_
->IsEOF());
492 next_state_
= STATE_SEND_BODY
;
496 int QuicHttpStream::DoSendBody() {
498 return ERR_UNEXPECTED
;
500 CHECK(request_body_stream_
);
501 CHECK(request_body_buf_
.get());
502 const bool eof
= request_body_stream_
->IsEOF();
503 int len
= request_body_buf_
->BytesRemaining();
504 if (len
> 0 || eof
) {
505 next_state_
= STATE_SEND_BODY_COMPLETE
;
506 base::StringPiece
data(request_body_buf_
->data(), len
);
507 return stream_
->WriteStreamData(
509 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
512 next_state_
= STATE_OPEN
;
516 int QuicHttpStream::DoSendBodyComplete(int rv
) {
520 request_body_buf_
->DidConsume(request_body_buf_
->BytesRemaining());
522 if (!request_body_stream_
->IsEOF()) {
523 next_state_
= STATE_READ_REQUEST_BODY
;
527 next_state_
= STATE_OPEN
;
531 int QuicHttpStream::ParseResponseHeaders() {
532 size_t read_buf_len
= static_cast<size_t>(read_buf_
->offset());
533 SpdyFramer
framer(GetSpdyVersion());
534 SpdyHeaderBlock headers
;
535 char* data
= read_buf_
->StartOfBuffer();
536 size_t len
= framer
.ParseHeaderBlockInBuffer(data
, read_buf_
->offset(),
540 return ERR_IO_PENDING
;
543 // Save the remaining received data.
544 size_t delta
= read_buf_len
- len
;
546 BufferResponseBody(data
+ len
, delta
);
549 // The URLRequest logs these headers, so only log to the QuicSession's
551 stream_
->net_log().AddEvent(
552 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS
,
553 base::Bind(&SpdyHeaderBlockNetLogCallback
, &headers
));
555 if (!SpdyHeadersToHttpResponse(headers
, GetSpdyVersion(), response_info_
)) {
556 DLOG(WARNING
) << "Invalid headers";
557 return ERR_QUIC_PROTOCOL_ERROR
;
559 // Put the peer's IP address and port into the response.
560 IPEndPoint address
= session_
->peer_address();
561 response_info_
->socket_address
= HostPortPair::FromIPEndPoint(address
);
562 response_info_
->connection_info
=
563 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3
;
564 response_info_
->vary_data
565 .Init(*request_info_
, *response_info_
->headers
.get());
566 response_info_
->was_npn_negotiated
= true;
567 response_info_
->npn_negotiated_protocol
= "quic/1+spdy/3";
568 response_info_
->response_time
= base::Time::Now();
569 response_info_
->request_time
= request_time_
;
570 response_headers_received_
= true;
575 void QuicHttpStream::BufferResponseBody(const char* data
, int length
) {
578 IOBufferWithSize
* io_buffer
= new IOBufferWithSize(length
);
579 memcpy(io_buffer
->data(), data
, length
);
580 response_body_
.push_back(make_scoped_refptr(io_buffer
));
583 SpdyMajorVersion
QuicHttpStream::GetSpdyVersion() {
584 return SpdyUtils::GetSpdyVersionForQuicVersion(stream_
->version());