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()),
35 request_body_stream_(NULL
),
36 priority_(MINIMUM_PRIORITY
),
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 if (request_info
->url
.SchemeIsSecure()) {
66 session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
.get();
67 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
70 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC
;
73 stream_net_log_
= stream_net_log
;
74 request_info_
= request_info
;
75 request_time_
= base::Time::Now();
78 int rv
= stream_request_
.StartRequest(
79 session_
, &stream_
, base::Bind(&QuicHttpStream::OnStreamReady
,
80 weak_factory_
.GetWeakPtr()));
81 if (rv
== ERR_IO_PENDING
) {
83 } else if (rv
== OK
) {
84 stream_
->SetDelegate(this);
85 } else if (!was_handshake_confirmed_
) {
86 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
92 void QuicHttpStream::OnStreamReady(int rv
) {
93 DCHECK(rv
== OK
|| !stream_
);
95 stream_
->SetDelegate(this);
96 } else if (!was_handshake_confirmed_
) {
97 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
100 ResetAndReturn(&callback_
).Run(rv
);
103 int QuicHttpStream::SendRequest(const HttpRequestHeaders
& request_headers
,
104 HttpResponseInfo
* response
,
105 const CompletionCallback
& callback
) {
107 CHECK(!request_body_stream_
);
108 CHECK(!response_info_
);
109 CHECK(!callback
.is_null());
112 QuicPriority priority
= ConvertRequestPriorityToQuicPriority(priority_
);
113 stream_
->set_priority(priority
);
114 // Store the serialized request headers.
115 CreateSpdyHeadersFromHttpRequest(*request_info_
, request_headers
,
116 SPDY3
, /*direct=*/true, &request_headers_
);
118 // Store the request body.
119 request_body_stream_
= request_info_
->upload_data_stream
;
120 if (request_body_stream_
) {
121 // TODO(rch): Can we be more precise about when to allocate
122 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
123 // was being called even if we didn't yet allocate raw_request_body_buf_.
124 // && (request_body_stream_->size() ||
125 // request_body_stream_->is_chunked()))
126 // Use 10 packets as the body buffer size to give enough space to
127 // help ensure we don't often send out partial packets.
128 raw_request_body_buf_
= new IOBufferWithSize(10 * kMaxPacketSize
);
129 // The request body buffer is empty at first.
130 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), 0);
133 // Store the response info.
134 response_info_
= response
;
136 next_state_
= STATE_SEND_HEADERS
;
138 if (rv
== ERR_IO_PENDING
)
139 callback_
= callback
;
141 return rv
> 0 ? OK
: rv
;
144 UploadProgress
QuicHttpStream::GetUploadProgress() const {
145 if (!request_body_stream_
)
146 return UploadProgress();
148 return UploadProgress(request_body_stream_
->position(),
149 request_body_stream_
->size());
152 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback
& callback
) {
153 CHECK(!callback
.is_null());
156 return response_status_
;
158 // Check if we already have the response headers. If so, return synchronously.
159 if (response_headers_received_
)
162 // Still waiting for the response, return IO_PENDING.
163 CHECK(callback_
.is_null());
164 callback_
= callback
;
165 return ERR_IO_PENDING
;
168 int QuicHttpStream::ReadResponseBody(
169 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
172 CHECK(!callback
.is_null());
174 // If we have data buffered, complete the IO immediately.
175 if (!response_body_
.empty()) {
177 while (!response_body_
.empty() && buf_len
> 0) {
178 scoped_refptr
<IOBufferWithSize
> data
= response_body_
.front();
179 const int bytes_to_copy
= std::min(buf_len
, data
->size());
180 memcpy(&(buf
->data()[bytes_read
]), data
->data(), bytes_to_copy
);
181 buf_len
-= bytes_to_copy
;
182 if (bytes_to_copy
== data
->size()) {
183 response_body_
.pop_front();
185 const int bytes_remaining
= data
->size() - bytes_to_copy
;
186 IOBufferWithSize
* new_buffer
= new IOBufferWithSize(bytes_remaining
);
187 memcpy(new_buffer
->data(), &(data
->data()[bytes_to_copy
]),
189 response_body_
.pop_front();
190 response_body_
.push_front(make_scoped_refptr(new_buffer
));
192 bytes_read
+= bytes_to_copy
;
198 // If the stream is already closed, there is no body to read.
199 return response_status_
;
202 CHECK(callback_
.is_null());
203 CHECK(!user_buffer_
.get());
204 CHECK_EQ(0, user_buffer_len_
);
206 callback_
= callback
;
208 user_buffer_len_
= buf_len
;
209 return ERR_IO_PENDING
;
212 void QuicHttpStream::Close(bool not_reusable
) {
213 // Note: the not_reusable flag has no meaning for SPDY streams.
215 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
216 stream_
->SetDelegate(NULL
);
217 stream_
->Reset(QUIC_STREAM_CANCELLED
);
222 HttpStream
* QuicHttpStream::RenewStreamForAuth() {
226 bool QuicHttpStream::IsResponseBodyComplete() const {
227 return next_state_
== STATE_OPEN
&& !stream_
;
230 bool QuicHttpStream::CanFindEndOfResponse() const {
234 bool QuicHttpStream::IsConnectionReused() const {
235 // TODO(rch): do something smarter here.
236 return stream_
&& stream_
->id() > 1;
239 void QuicHttpStream::SetConnectionReused() {
240 // QUIC doesn't need an indicator here.
243 bool QuicHttpStream::IsConnectionReusable() const {
244 // QUIC streams aren't considered reusable.
248 int64
QuicHttpStream::GetTotalReceivedBytes() const {
250 return stream_
->stream_bytes_read();
253 return closed_stream_received_bytes_
;
256 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
257 // TODO(mmenke): Figure out what to do here.
261 void QuicHttpStream::GetSSLInfo(SSLInfo
* ssl_info
) {
263 stream_
->GetSSLInfo(ssl_info
);
266 void QuicHttpStream::GetSSLCertRequestInfo(
267 SSLCertRequestInfo
* cert_request_info
) {
272 bool QuicHttpStream::IsSpdyHttpStream() const {
276 void QuicHttpStream::Drain(HttpNetworkSession
* session
) {
281 void QuicHttpStream::SetPriority(RequestPriority priority
) {
282 priority_
= priority
;
285 int QuicHttpStream::OnDataReceived(const char* data
, int length
) {
286 DCHECK_NE(0, length
);
287 // Are we still reading the response headers.
288 if (!response_headers_received_
) {
289 // Grow the read buffer if necessary.
290 if (read_buf_
->RemainingCapacity() < length
) {
291 size_t additional_capacity
= length
- read_buf_
->RemainingCapacity();
292 if (additional_capacity
< kHeaderBufInitialSize
)
293 additional_capacity
= kHeaderBufInitialSize
;
294 read_buf_
->SetCapacity(read_buf_
->capacity() + additional_capacity
);
296 memcpy(read_buf_
->data(), data
, length
);
297 read_buf_
->set_offset(read_buf_
->offset() + length
);
298 int rv
= ParseResponseHeaders();
299 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
305 if (callback_
.is_null()) {
306 BufferResponseBody(data
, length
);
310 if (length
<= user_buffer_len_
) {
311 memcpy(user_buffer_
->data(), data
, length
);
313 memcpy(user_buffer_
->data(), data
, user_buffer_len_
);
314 int delta
= length
- user_buffer_len_
;
315 BufferResponseBody(data
+ user_buffer_len_
, delta
);
316 length
= user_buffer_len_
;
320 user_buffer_len_
= 0;
325 void QuicHttpStream::OnClose(QuicErrorCode error
) {
326 if (error
!= QUIC_NO_ERROR
) {
327 response_status_
= was_handshake_confirmed_
?
328 ERR_QUIC_PROTOCOL_ERROR
: ERR_QUIC_HANDSHAKE_FAILED
;
329 } else if (!response_headers_received_
) {
330 response_status_
= ERR_ABORTED
;
333 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
335 if (!callback_
.is_null())
336 DoCallback(response_status_
);
339 void QuicHttpStream::OnError(int error
) {
341 response_status_
= was_handshake_confirmed_
?
342 error
: ERR_QUIC_HANDSHAKE_FAILED
;
343 if (!callback_
.is_null())
344 DoCallback(response_status_
);
347 bool QuicHttpStream::HasSendHeadersComplete() {
348 return next_state_
> STATE_SEND_HEADERS_COMPLETE
;
351 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
352 was_handshake_confirmed_
= true;
355 void QuicHttpStream::OnSessionClosed(int error
) {
356 session_error_
= error
;
360 void QuicHttpStream::OnIOComplete(int rv
) {
363 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
368 void QuicHttpStream::DoCallback(int rv
) {
369 CHECK_NE(rv
, ERR_IO_PENDING
);
370 CHECK(!callback_
.is_null());
372 // The client callback can do anything, including destroying this class,
373 // so any pending callback must be issued after everything else is done.
374 base::ResetAndReturn(&callback_
).Run(rv
);
377 int QuicHttpStream::DoLoop(int rv
) {
379 State state
= next_state_
;
380 next_state_
= STATE_NONE
;
382 case STATE_SEND_HEADERS
:
384 rv
= DoSendHeaders();
386 case STATE_SEND_HEADERS_COMPLETE
:
387 rv
= DoSendHeadersComplete(rv
);
389 case STATE_READ_REQUEST_BODY
:
391 rv
= DoReadRequestBody();
393 case STATE_READ_REQUEST_BODY_COMPLETE
:
394 rv
= DoReadRequestBodyComplete(rv
);
396 case STATE_SEND_BODY
:
400 case STATE_SEND_BODY_COMPLETE
:
401 rv
= DoSendBodyComplete(rv
);
407 NOTREACHED() << "next_state_: " << next_state_
;
410 } while (next_state_
!= STATE_NONE
&& next_state_
!= STATE_OPEN
&&
411 rv
!= ERR_IO_PENDING
);
416 int QuicHttpStream::DoSendHeaders() {
418 return ERR_UNEXPECTED
;
420 // Log the actual request with the URL Request's net log.
421 stream_net_log_
.AddEvent(
422 NetLog::TYPE_HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS
,
423 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
425 // Also log to the QuicSession's net log.
426 stream_
->net_log().AddEvent(
427 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS
,
428 base::Bind(&QuicRequestNetLogCallback
, stream_
->id(), &request_headers_
,
431 bool has_upload_data
= request_body_stream_
!= NULL
;
433 next_state_
= STATE_SEND_HEADERS_COMPLETE
;
434 int rv
= stream_
->WriteHeaders(request_headers_
, !has_upload_data
, NULL
);
435 request_headers_
.clear();
439 int QuicHttpStream::DoSendHeadersComplete(int rv
) {
443 next_state_
= request_body_stream_
?
444 STATE_READ_REQUEST_BODY
: STATE_OPEN
;
449 int QuicHttpStream::DoReadRequestBody() {
450 next_state_
= STATE_READ_REQUEST_BODY_COMPLETE
;
451 return request_body_stream_
->Read(
452 raw_request_body_buf_
.get(),
453 raw_request_body_buf_
->size(),
454 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
457 int QuicHttpStream::DoReadRequestBodyComplete(int rv
) {
458 // |rv| is the result of read from the request body from the last call to
463 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), rv
);
464 if (rv
== 0) { // Reached the end.
465 DCHECK(request_body_stream_
->IsEOF());
468 next_state_
= STATE_SEND_BODY
;
472 int QuicHttpStream::DoSendBody() {
474 return ERR_UNEXPECTED
;
476 CHECK(request_body_stream_
);
477 CHECK(request_body_buf_
.get());
478 const bool eof
= request_body_stream_
->IsEOF();
479 int len
= request_body_buf_
->BytesRemaining();
480 if (len
> 0 || eof
) {
481 next_state_
= STATE_SEND_BODY_COMPLETE
;
482 base::StringPiece
data(request_body_buf_
->data(), len
);
483 return stream_
->WriteStreamData(
485 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
488 next_state_
= STATE_OPEN
;
492 int QuicHttpStream::DoSendBodyComplete(int rv
) {
496 request_body_buf_
->DidConsume(request_body_buf_
->BytesRemaining());
498 if (!request_body_stream_
->IsEOF()) {
499 next_state_
= STATE_READ_REQUEST_BODY
;
503 next_state_
= STATE_OPEN
;
507 int QuicHttpStream::ParseResponseHeaders() {
508 size_t read_buf_len
= static_cast<size_t>(read_buf_
->offset());
509 SpdyFramer
framer(SPDY3
);
510 SpdyHeaderBlock headers
;
511 char* data
= read_buf_
->StartOfBuffer();
512 size_t len
= framer
.ParseHeaderBlockInBuffer(data
, read_buf_
->offset(),
516 return ERR_IO_PENDING
;
519 // Save the remaining received data.
520 size_t delta
= read_buf_len
- len
;
522 BufferResponseBody(data
+ len
, delta
);
525 // The URLRequest logs these headers, so only log to the QuicSession's
527 stream_
->net_log().AddEvent(
528 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS
,
529 base::Bind(&SpdyHeaderBlockNetLogCallback
, &headers
));
531 if (!SpdyHeadersToHttpResponse(headers
, SPDY3
, response_info_
)) {
532 DLOG(WARNING
) << "Invalid headers";
533 return ERR_QUIC_PROTOCOL_ERROR
;
535 // Put the peer's IP address and port into the response.
536 IPEndPoint address
= stream_
->GetPeerAddress();
537 response_info_
->socket_address
= HostPortPair::FromIPEndPoint(address
);
538 response_info_
->connection_info
=
539 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3
;
540 response_info_
->vary_data
541 .Init(*request_info_
, *response_info_
->headers
.get());
542 response_info_
->was_npn_negotiated
= true;
543 response_info_
->npn_negotiated_protocol
= "quic/1+spdy/3";
544 response_info_
->response_time
= base::Time::Now();
545 response_info_
->request_time
= request_time_
;
546 response_headers_received_
= true;
551 void QuicHttpStream::BufferResponseBody(const char* data
, int length
) {
554 IOBufferWithSize
* io_buffer
= new IOBufferWithSize(length
);
555 memcpy(io_buffer
->data(), data
, length
);
556 response_body_
.push_back(make_scoped_refptr(io_buffer
));