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/socket/next_proto.h"
19 #include "net/spdy/spdy_frame_builder.h"
20 #include "net/spdy/spdy_framer.h"
21 #include "net/spdy/spdy_http_utils.h"
22 #include "net/ssl/ssl_info.h"
26 static const size_t kHeaderBufInitialSize
= 4096;
28 QuicHttpStream::QuicHttpStream(const base::WeakPtr
<QuicClientSession
>& session
)
29 : next_state_(STATE_NONE
),
32 was_handshake_confirmed_(session
->IsCryptoHandshakeConfirmed()),
34 request_info_(nullptr),
35 request_body_stream_(nullptr),
36 priority_(MINIMUM_PRIORITY
),
37 response_info_(nullptr),
39 response_headers_received_(false),
40 read_buf_(new GrowableIOBuffer()),
41 closed_stream_received_bytes_(0),
45 session_
->AddObserver(this);
48 QuicHttpStream::~QuicHttpStream() {
51 session_
->RemoveObserver(this);
54 int QuicHttpStream::InitializeStream(const HttpRequestInfo
* request_info
,
55 RequestPriority priority
,
56 const BoundNetLog
& stream_net_log
,
57 const CompletionCallback
& callback
) {
60 return was_handshake_confirmed_
? ERR_CONNECTION_CLOSED
:
61 ERR_QUIC_HANDSHAKE_FAILED
;
63 stream_net_log
.AddEvent(
64 NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_QUIC_SESSION
,
65 session_
->net_log().source().ToEventParametersCallback());
67 if (request_info
->url
.SchemeIsSecure()) {
70 session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
.get();
71 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
74 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC
;
77 stream_net_log_
= stream_net_log
;
78 request_info_
= request_info
;
79 request_time_
= base::Time::Now();
82 int rv
= stream_request_
.StartRequest(
83 session_
, &stream_
, base::Bind(&QuicHttpStream::OnStreamReady
,
84 weak_factory_
.GetWeakPtr()));
85 if (rv
== ERR_IO_PENDING
) {
87 } else if (rv
== OK
) {
88 stream_
->SetDelegate(this);
89 } else if (!was_handshake_confirmed_
) {
90 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
96 void QuicHttpStream::OnStreamReady(int rv
) {
97 DCHECK(rv
== OK
|| !stream_
);
99 stream_
->SetDelegate(this);
100 } else if (!was_handshake_confirmed_
) {
101 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
104 ResetAndReturn(&callback_
).Run(rv
);
107 int QuicHttpStream::SendRequest(const HttpRequestHeaders
& request_headers
,
108 HttpResponseInfo
* response
,
109 const CompletionCallback
& callback
) {
110 CHECK(!request_body_stream_
);
111 CHECK(!response_info_
);
112 CHECK(!callback
.is_null());
115 // TODO(rch): remove this once we figure out why channel ID is not being
116 // sent when it should be.
117 HostPortPair origin
= HostPortPair::FromURL(request_info_
->url
);
118 if (origin
.Equals(HostPortPair("accounts.google.com", 443)) &&
119 request_headers
.HasHeader(HttpRequestHeaders::kCookie
)) {
121 bool secure_session
=
122 session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
.get();
123 DCHECK(secure_session
);
124 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.CookieSentToAccountsOverChannelId",
125 ssl_info
.channel_id_sent
);
128 return ERR_CONNECTION_CLOSED
;
131 QuicPriority priority
= ConvertRequestPriorityToQuicPriority(priority_
);
132 stream_
->set_priority(priority
);
133 // Store the serialized request headers.
134 CreateSpdyHeadersFromHttpRequest(*request_info_
, request_headers
,
135 SPDY3
, /*direct=*/true, &request_headers_
);
137 // Store the request body.
138 request_body_stream_
= request_info_
->upload_data_stream
;
139 if (request_body_stream_
) {
140 // TODO(rch): Can we be more precise about when to allocate
141 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
142 // was being called even if we didn't yet allocate raw_request_body_buf_.
143 // && (request_body_stream_->size() ||
144 // request_body_stream_->is_chunked()))
145 // Use 10 packets as the body buffer size to give enough space to
146 // help ensure we don't often send out partial packets.
147 raw_request_body_buf_
= new IOBufferWithSize(10 * kMaxPacketSize
);
148 // The request body buffer is empty at first.
149 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), 0);
152 // Store the response info.
153 response_info_
= response
;
155 next_state_
= STATE_SEND_HEADERS
;
157 if (rv
== ERR_IO_PENDING
)
158 callback_
= callback
;
160 return rv
> 0 ? OK
: rv
;
163 UploadProgress
QuicHttpStream::GetUploadProgress() const {
164 if (!request_body_stream_
)
165 return UploadProgress();
167 return UploadProgress(request_body_stream_
->position(),
168 request_body_stream_
->size());
171 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback
& callback
) {
172 CHECK(!callback
.is_null());
174 if (stream_
== nullptr)
175 return response_status_
;
177 // Check if we already have the response headers. If so, return synchronously.
178 if (response_headers_received_
)
181 // Still waiting for the response, return IO_PENDING.
182 CHECK(callback_
.is_null());
183 callback_
= callback
;
184 return ERR_IO_PENDING
;
187 int QuicHttpStream::ReadResponseBody(
188 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
191 CHECK(!callback
.is_null());
193 // If we have data buffered, complete the IO immediately.
194 if (!response_body_
.empty()) {
196 while (!response_body_
.empty() && buf_len
> 0) {
197 scoped_refptr
<IOBufferWithSize
> data
= response_body_
.front();
198 const int bytes_to_copy
= std::min(buf_len
, data
->size());
199 memcpy(&(buf
->data()[bytes_read
]), data
->data(), bytes_to_copy
);
200 buf_len
-= bytes_to_copy
;
201 if (bytes_to_copy
== data
->size()) {
202 response_body_
.pop_front();
204 const int bytes_remaining
= data
->size() - bytes_to_copy
;
205 IOBufferWithSize
* new_buffer
= new IOBufferWithSize(bytes_remaining
);
206 memcpy(new_buffer
->data(), &(data
->data()[bytes_to_copy
]),
208 response_body_
.pop_front();
209 response_body_
.push_front(make_scoped_refptr(new_buffer
));
211 bytes_read
+= bytes_to_copy
;
217 // If the stream is already closed, there is no body to read.
218 return response_status_
;
221 CHECK(callback_
.is_null());
222 CHECK(!user_buffer_
.get());
223 CHECK_EQ(0, user_buffer_len_
);
225 callback_
= callback
;
227 user_buffer_len_
= buf_len
;
228 return ERR_IO_PENDING
;
231 void QuicHttpStream::Close(bool not_reusable
) {
232 // Note: the not_reusable flag has no meaning for SPDY streams.
234 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
235 stream_
->SetDelegate(nullptr);
236 stream_
->Reset(QUIC_STREAM_CANCELLED
);
238 response_status_
= was_handshake_confirmed_
?
239 ERR_CONNECTION_CLOSED
: ERR_QUIC_HANDSHAKE_FAILED
;
243 HttpStream
* QuicHttpStream::RenewStreamForAuth() {
247 bool QuicHttpStream::IsResponseBodyComplete() const {
248 return next_state_
== STATE_OPEN
&& !stream_
;
251 bool QuicHttpStream::CanFindEndOfResponse() const {
255 bool QuicHttpStream::IsConnectionReused() const {
256 // TODO(rch): do something smarter here.
257 return stream_
&& stream_
->id() > 1;
260 void QuicHttpStream::SetConnectionReused() {
261 // QUIC doesn't need an indicator here.
264 bool QuicHttpStream::IsConnectionReusable() const {
265 // QUIC streams aren't considered reusable.
269 int64
QuicHttpStream::GetTotalReceivedBytes() const {
271 return stream_
->stream_bytes_read();
274 return closed_stream_received_bytes_
;
277 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
278 // TODO(mmenke): Figure out what to do here.
282 void QuicHttpStream::GetSSLInfo(SSLInfo
* ssl_info
) {
284 session_
->GetSSLInfo(ssl_info
);
287 void QuicHttpStream::GetSSLCertRequestInfo(
288 SSLCertRequestInfo
* cert_request_info
) {
293 bool QuicHttpStream::IsSpdyHttpStream() const {
297 void QuicHttpStream::Drain(HttpNetworkSession
* session
) {
302 void QuicHttpStream::SetPriority(RequestPriority priority
) {
303 priority_
= priority
;
306 int QuicHttpStream::OnDataReceived(const char* data
, int length
) {
307 DCHECK_NE(0, length
);
308 // Are we still reading the response headers.
309 if (!response_headers_received_
) {
310 // Grow the read buffer if necessary.
311 if (read_buf_
->RemainingCapacity() < length
) {
312 size_t additional_capacity
= length
- read_buf_
->RemainingCapacity();
313 if (additional_capacity
< kHeaderBufInitialSize
)
314 additional_capacity
= kHeaderBufInitialSize
;
315 read_buf_
->SetCapacity(read_buf_
->capacity() + additional_capacity
);
317 memcpy(read_buf_
->data(), data
, length
);
318 read_buf_
->set_offset(read_buf_
->offset() + length
);
319 int rv
= ParseResponseHeaders();
320 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
326 if (callback_
.is_null()) {
327 BufferResponseBody(data
, length
);
331 if (length
<= user_buffer_len_
) {
332 memcpy(user_buffer_
->data(), data
, length
);
334 memcpy(user_buffer_
->data(), data
, user_buffer_len_
);
335 int delta
= length
- user_buffer_len_
;
336 BufferResponseBody(data
+ user_buffer_len_
, delta
);
337 length
= user_buffer_len_
;
340 user_buffer_
= nullptr;
341 user_buffer_len_
= 0;
346 void QuicHttpStream::OnClose(QuicErrorCode error
) {
347 if (error
!= QUIC_NO_ERROR
) {
348 response_status_
= was_handshake_confirmed_
?
349 ERR_QUIC_PROTOCOL_ERROR
: ERR_QUIC_HANDSHAKE_FAILED
;
350 } else if (!response_headers_received_
) {
351 response_status_
= ERR_ABORTED
;
354 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
356 if (!callback_
.is_null())
357 DoCallback(response_status_
);
360 void QuicHttpStream::OnError(int error
) {
362 response_status_
= was_handshake_confirmed_
?
363 error
: ERR_QUIC_HANDSHAKE_FAILED
;
364 if (!callback_
.is_null())
365 DoCallback(response_status_
);
368 bool QuicHttpStream::HasSendHeadersComplete() {
369 return next_state_
> STATE_SEND_HEADERS_COMPLETE
;
372 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
373 was_handshake_confirmed_
= true;
376 void QuicHttpStream::OnSessionClosed(int error
) {
378 session_error_
= error
;
382 void QuicHttpStream::OnIOComplete(int rv
) {
385 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
390 void QuicHttpStream::DoCallback(int rv
) {
391 CHECK_NE(rv
, ERR_IO_PENDING
);
392 CHECK(!callback_
.is_null());
394 // The client callback can do anything, including destroying this class,
395 // so any pending callback must be issued after everything else is done.
396 base::ResetAndReturn(&callback_
).Run(rv
);
399 int QuicHttpStream::DoLoop(int rv
) {
401 State state
= next_state_
;
402 next_state_
= STATE_NONE
;
404 case STATE_SEND_HEADERS
:
406 rv
= DoSendHeaders();
408 case STATE_SEND_HEADERS_COMPLETE
:
409 rv
= DoSendHeadersComplete(rv
);
411 case STATE_READ_REQUEST_BODY
:
413 rv
= DoReadRequestBody();
415 case STATE_READ_REQUEST_BODY_COMPLETE
:
416 rv
= DoReadRequestBodyComplete(rv
);
418 case STATE_SEND_BODY
:
422 case STATE_SEND_BODY_COMPLETE
:
423 rv
= DoSendBodyComplete(rv
);
429 NOTREACHED() << "next_state_: " << next_state_
;
432 } while (next_state_
!= STATE_NONE
&& next_state_
!= STATE_OPEN
&&
433 rv
!= ERR_IO_PENDING
);
438 int QuicHttpStream::DoSendHeaders() {
440 return ERR_UNEXPECTED
;
442 // Log the actual request with the URL Request's net log.
443 stream_net_log_
.AddEvent(
444 NetLog::TYPE_HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS
,
445 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
447 // Also log to the QuicSession's net log.
448 stream_
->net_log().AddEvent(
449 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS
,
450 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
453 bool has_upload_data
= request_body_stream_
!= nullptr;
455 next_state_
= STATE_SEND_HEADERS_COMPLETE
;
456 int rv
= stream_
->WriteHeaders(request_headers_
, !has_upload_data
, nullptr);
457 request_headers_
.clear();
461 int QuicHttpStream::DoSendHeadersComplete(int rv
) {
465 next_state_
= request_body_stream_
?
466 STATE_READ_REQUEST_BODY
: STATE_OPEN
;
471 int QuicHttpStream::DoReadRequestBody() {
472 next_state_
= STATE_READ_REQUEST_BODY_COMPLETE
;
473 return request_body_stream_
->Read(
474 raw_request_body_buf_
.get(),
475 raw_request_body_buf_
->size(),
476 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
479 int QuicHttpStream::DoReadRequestBodyComplete(int rv
) {
480 // |rv| is the result of read from the request body from the last call to
485 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), rv
);
486 if (rv
== 0) { // Reached the end.
487 DCHECK(request_body_stream_
->IsEOF());
490 next_state_
= STATE_SEND_BODY
;
494 int QuicHttpStream::DoSendBody() {
496 return ERR_UNEXPECTED
;
498 CHECK(request_body_stream_
);
499 CHECK(request_body_buf_
.get());
500 const bool eof
= request_body_stream_
->IsEOF();
501 int len
= request_body_buf_
->BytesRemaining();
502 if (len
> 0 || eof
) {
503 next_state_
= STATE_SEND_BODY_COMPLETE
;
504 base::StringPiece
data(request_body_buf_
->data(), len
);
505 return stream_
->WriteStreamData(
507 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
510 next_state_
= STATE_OPEN
;
514 int QuicHttpStream::DoSendBodyComplete(int rv
) {
518 request_body_buf_
->DidConsume(request_body_buf_
->BytesRemaining());
520 if (!request_body_stream_
->IsEOF()) {
521 next_state_
= STATE_READ_REQUEST_BODY
;
525 next_state_
= STATE_OPEN
;
529 int QuicHttpStream::ParseResponseHeaders() {
530 size_t read_buf_len
= static_cast<size_t>(read_buf_
->offset());
531 SpdyFramer
framer(SPDY3
);
532 SpdyHeaderBlock headers
;
533 char* data
= read_buf_
->StartOfBuffer();
534 size_t len
= framer
.ParseHeaderBlockInBuffer(data
, read_buf_
->offset(),
538 return ERR_IO_PENDING
;
541 // Save the remaining received data.
542 size_t delta
= read_buf_len
- len
;
544 BufferResponseBody(data
+ len
, delta
);
547 // The URLRequest logs these headers, so only log to the QuicSession's
549 stream_
->net_log().AddEvent(
550 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS
,
551 base::Bind(&SpdyHeaderBlockNetLogCallback
, &headers
));
553 if (!SpdyHeadersToHttpResponse(headers
, SPDY3
, response_info_
)) {
554 DLOG(WARNING
) << "Invalid headers";
555 return ERR_QUIC_PROTOCOL_ERROR
;
557 // Put the peer's IP address and port into the response.
558 IPEndPoint address
= stream_
->GetPeerAddress();
559 response_info_
->socket_address
= HostPortPair::FromIPEndPoint(address
);
560 response_info_
->connection_info
=
561 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3
;
562 response_info_
->vary_data
563 .Init(*request_info_
, *response_info_
->headers
.get());
564 response_info_
->was_npn_negotiated
= true;
565 response_info_
->npn_negotiated_protocol
= "quic/1+spdy/3";
566 response_info_
->response_time
= base::Time::Now();
567 response_info_
->request_time
= request_time_
;
568 response_headers_received_
= true;
573 void QuicHttpStream::BufferResponseBody(const char* data
, int length
) {
576 IOBufferWithSize
* io_buffer
= new IOBufferWithSize(length
);
577 memcpy(io_buffer
->data(), data
, length
);
578 response_body_
.push_back(make_scoped_refptr(io_buffer
));