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()) {
65 bool secure_session
= session_
->GetSSLInfo(&ssl_info
) && ssl_info
.cert
;
66 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
69 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC
;
72 stream_net_log_
= stream_net_log
;
73 request_info_
= request_info
;
76 int rv
= stream_request_
.StartRequest(
77 session_
, &stream_
, base::Bind(&QuicHttpStream::OnStreamReady
,
78 weak_factory_
.GetWeakPtr()));
79 if (rv
== ERR_IO_PENDING
) {
81 } else if (rv
== OK
) {
82 stream_
->SetDelegate(this);
83 } else if (!was_handshake_confirmed_
) {
84 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
90 void QuicHttpStream::OnStreamReady(int rv
) {
91 DCHECK(rv
== OK
|| !stream_
);
93 stream_
->SetDelegate(this);
94 } else if (!was_handshake_confirmed_
) {
95 rv
= ERR_QUIC_HANDSHAKE_FAILED
;
98 ResetAndReturn(&callback_
).Run(rv
);
101 int QuicHttpStream::SendRequest(const HttpRequestHeaders
& request_headers
,
102 HttpResponseInfo
* response
,
103 const CompletionCallback
& callback
) {
105 CHECK(!request_body_stream_
);
106 CHECK(!response_info_
);
107 CHECK(!callback
.is_null());
110 QuicPriority priority
= ConvertRequestPriorityToQuicPriority(priority_
);
111 stream_
->set_priority(priority
);
112 // Store the serialized request headers.
113 CreateSpdyHeadersFromHttpRequest(*request_info_
, request_headers
,
114 &request_headers_
, SPDY3
, /*direct=*/true);
116 // Store the request body.
117 request_body_stream_
= request_info_
->upload_data_stream
;
118 if (request_body_stream_
) {
119 // TODO(rch): Can we be more precise about when to allocate
120 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
121 // was being called even if we didn't yet allocate raw_request_body_buf_.
122 // && (request_body_stream_->size() ||
123 // request_body_stream_->is_chunked()))
125 // Use kMaxPacketSize as the buffer size, since the request
126 // body data is written with this size at a time.
127 // TODO(rch): use a smarter value since we can't write an entire
128 // packet due to overhead.
129 raw_request_body_buf_
= new IOBufferWithSize(kMaxPacketSize
);
130 // The request body buffer is empty at first.
131 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), 0);
134 // Store the response info.
135 response_info_
= response
;
137 next_state_
= STATE_SEND_HEADERS
;
139 if (rv
== ERR_IO_PENDING
)
140 callback_
= callback
;
142 return rv
> 0 ? OK
: rv
;
145 UploadProgress
QuicHttpStream::GetUploadProgress() const {
146 if (!request_body_stream_
)
147 return UploadProgress();
149 return UploadProgress(request_body_stream_
->position(),
150 request_body_stream_
->size());
153 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback
& callback
) {
154 CHECK(!callback
.is_null());
157 return response_status_
;
159 // Check if we already have the response headers. If so, return synchronously.
160 if (response_headers_received_
)
163 // Still waiting for the response, return IO_PENDING.
164 CHECK(callback_
.is_null());
165 callback_
= callback
;
166 return ERR_IO_PENDING
;
169 const HttpResponseInfo
* QuicHttpStream::GetResponseInfo() const {
170 return response_info_
;
173 int QuicHttpStream::ReadResponseBody(
174 IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
) {
177 CHECK(!callback
.is_null());
179 // If we have data buffered, complete the IO immediately.
180 if (!response_body_
.empty()) {
182 while (!response_body_
.empty() && buf_len
> 0) {
183 scoped_refptr
<IOBufferWithSize
> data
= response_body_
.front();
184 const int bytes_to_copy
= std::min(buf_len
, data
->size());
185 memcpy(&(buf
->data()[bytes_read
]), data
->data(), bytes_to_copy
);
186 buf_len
-= bytes_to_copy
;
187 if (bytes_to_copy
== data
->size()) {
188 response_body_
.pop_front();
190 const int bytes_remaining
= data
->size() - bytes_to_copy
;
191 IOBufferWithSize
* new_buffer
= new IOBufferWithSize(bytes_remaining
);
192 memcpy(new_buffer
->data(), &(data
->data()[bytes_to_copy
]),
194 response_body_
.pop_front();
195 response_body_
.push_front(make_scoped_refptr(new_buffer
));
197 bytes_read
+= bytes_to_copy
;
203 // If the stream is already closed, there is no body to read.
204 return response_status_
;
207 CHECK(callback_
.is_null());
208 CHECK(!user_buffer_
.get());
209 CHECK_EQ(0, user_buffer_len_
);
211 callback_
= callback
;
213 user_buffer_len_
= buf_len
;
214 return ERR_IO_PENDING
;
217 void QuicHttpStream::Close(bool not_reusable
) {
218 // Note: the not_reusable flag has no meaning for SPDY streams.
220 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
221 stream_
->SetDelegate(NULL
);
222 stream_
->Reset(QUIC_STREAM_CANCELLED
);
227 HttpStream
* QuicHttpStream::RenewStreamForAuth() {
231 bool QuicHttpStream::IsResponseBodyComplete() const {
232 return next_state_
== STATE_OPEN
&& !stream_
;
235 bool QuicHttpStream::CanFindEndOfResponse() const {
239 bool QuicHttpStream::IsConnectionReused() const {
240 // TODO(rch): do something smarter here.
241 return stream_
&& stream_
->id() > 1;
244 void QuicHttpStream::SetConnectionReused() {
245 // QUIC doesn't need an indicator here.
248 bool QuicHttpStream::IsConnectionReusable() const {
249 // QUIC streams aren't considered reusable.
253 int64
QuicHttpStream::GetTotalReceivedBytes() const {
255 return stream_
->stream_bytes_read();
258 return closed_stream_received_bytes_
;
261 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
262 // TODO(mmenke): Figure out what to do here.
266 void QuicHttpStream::GetSSLInfo(SSLInfo
* ssl_info
) {
268 stream_
->GetSSLInfo(ssl_info
);
271 void QuicHttpStream::GetSSLCertRequestInfo(
272 SSLCertRequestInfo
* cert_request_info
) {
277 bool QuicHttpStream::IsSpdyHttpStream() const {
281 void QuicHttpStream::Drain(HttpNetworkSession
* session
) {
286 void QuicHttpStream::SetPriority(RequestPriority priority
) {
287 priority_
= priority
;
290 int QuicHttpStream::OnDataReceived(const char* data
, int length
) {
291 DCHECK_NE(0, length
);
292 // Are we still reading the response headers.
293 if (!response_headers_received_
) {
294 // Grow the read buffer if necessary.
295 if (read_buf_
->RemainingCapacity() < length
) {
296 size_t additional_capacity
= length
- read_buf_
->RemainingCapacity();
297 if (additional_capacity
< kHeaderBufInitialSize
)
298 additional_capacity
= kHeaderBufInitialSize
;
299 read_buf_
->SetCapacity(read_buf_
->capacity() + additional_capacity
);
301 memcpy(read_buf_
->data(), data
, length
);
302 read_buf_
->set_offset(read_buf_
->offset() + length
);
303 int rv
= ParseResponseHeaders();
304 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
310 if (callback_
.is_null()) {
311 BufferResponseBody(data
, length
);
315 if (length
<= user_buffer_len_
) {
316 memcpy(user_buffer_
->data(), data
, length
);
318 memcpy(user_buffer_
->data(), data
, user_buffer_len_
);
319 int delta
= length
- user_buffer_len_
;
320 BufferResponseBody(data
+ user_buffer_len_
, delta
);
321 length
= user_buffer_len_
;
325 user_buffer_len_
= 0;
330 void QuicHttpStream::OnClose(QuicErrorCode error
) {
331 if (error
!= QUIC_NO_ERROR
) {
332 response_status_
= was_handshake_confirmed_
?
333 ERR_QUIC_PROTOCOL_ERROR
: ERR_QUIC_HANDSHAKE_FAILED
;
334 } else if (!response_headers_received_
) {
335 response_status_
= ERR_ABORTED
;
338 closed_stream_received_bytes_
= stream_
->stream_bytes_read();
340 if (!callback_
.is_null())
341 DoCallback(response_status_
);
344 void QuicHttpStream::OnError(int error
) {
346 response_status_
= was_handshake_confirmed_
?
347 error
: ERR_QUIC_HANDSHAKE_FAILED
;
348 if (!callback_
.is_null())
349 DoCallback(response_status_
);
352 bool QuicHttpStream::HasSendHeadersComplete() {
353 return next_state_
> STATE_SEND_HEADERS_COMPLETE
;
356 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
357 was_handshake_confirmed_
= true;
360 void QuicHttpStream::OnSessionClosed(int error
) {
361 session_error_
= error
;
365 void QuicHttpStream::OnIOComplete(int rv
) {
368 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
373 void QuicHttpStream::DoCallback(int rv
) {
374 CHECK_NE(rv
, ERR_IO_PENDING
);
375 CHECK(!callback_
.is_null());
377 // The client callback can do anything, including destroying this class,
378 // so any pending callback must be issued after everything else is done.
379 base::ResetAndReturn(&callback_
).Run(rv
);
382 int QuicHttpStream::DoLoop(int rv
) {
384 State state
= next_state_
;
385 next_state_
= STATE_NONE
;
387 case STATE_SEND_HEADERS
:
389 rv
= DoSendHeaders();
391 case STATE_SEND_HEADERS_COMPLETE
:
392 rv
= DoSendHeadersComplete(rv
);
394 case STATE_READ_REQUEST_BODY
:
396 rv
= DoReadRequestBody();
398 case STATE_READ_REQUEST_BODY_COMPLETE
:
399 rv
= DoReadRequestBodyComplete(rv
);
401 case STATE_SEND_BODY
:
405 case STATE_SEND_BODY_COMPLETE
:
406 rv
= DoSendBodyComplete(rv
);
412 NOTREACHED() << "next_state_: " << next_state_
;
415 } while (next_state_
!= STATE_NONE
&& next_state_
!= STATE_OPEN
&&
416 rv
!= ERR_IO_PENDING
);
421 int QuicHttpStream::DoSendHeaders() {
423 return ERR_UNEXPECTED
;
425 // Log the actual request with the URL Request's net log.
426 stream_net_log_
.AddEvent(
427 NetLog::TYPE_HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS
,
428 base::Bind(&QuicRequestNetLogCallback
, &request_headers_
, priority_
));
429 // Also log to the QuicSession's net log.
430 stream_
->net_log().AddEvent(
431 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS
,
432 base::Bind(&QuicRequestNetLogCallback
, &request_headers_
, priority_
));
434 bool has_upload_data
= request_body_stream_
!= NULL
;
436 next_state_
= STATE_SEND_HEADERS_COMPLETE
;
437 int rv
= stream_
->WriteHeaders(request_headers_
, !has_upload_data
, NULL
);
438 request_headers_
.clear();
442 int QuicHttpStream::DoSendHeadersComplete(int rv
) {
446 next_state_
= request_body_stream_
?
447 STATE_READ_REQUEST_BODY
: STATE_OPEN
;
452 int QuicHttpStream::DoReadRequestBody() {
453 next_state_
= STATE_READ_REQUEST_BODY_COMPLETE
;
454 return request_body_stream_
->Read(
455 raw_request_body_buf_
.get(),
456 raw_request_body_buf_
->size(),
457 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
460 int QuicHttpStream::DoReadRequestBodyComplete(int rv
) {
461 // |rv| is the result of read from the request body from the last call to
466 request_body_buf_
= new DrainableIOBuffer(raw_request_body_buf_
.get(), rv
);
467 if (rv
== 0) { // Reached the end.
468 DCHECK(request_body_stream_
->IsEOF());
471 next_state_
= STATE_SEND_BODY
;
475 int QuicHttpStream::DoSendBody() {
477 return ERR_UNEXPECTED
;
479 CHECK(request_body_stream_
);
480 CHECK(request_body_buf_
.get());
481 const bool eof
= request_body_stream_
->IsEOF();
482 int len
= request_body_buf_
->BytesRemaining();
483 if (len
> 0 || eof
) {
484 next_state_
= STATE_SEND_BODY_COMPLETE
;
485 base::StringPiece
data(request_body_buf_
->data(), len
);
486 return stream_
->WriteStreamData(
488 base::Bind(&QuicHttpStream::OnIOComplete
, weak_factory_
.GetWeakPtr()));
491 next_state_
= STATE_OPEN
;
495 int QuicHttpStream::DoSendBodyComplete(int rv
) {
499 request_body_buf_
->DidConsume(request_body_buf_
->BytesRemaining());
501 if (!request_body_stream_
->IsEOF()) {
502 next_state_
= STATE_READ_REQUEST_BODY
;
506 next_state_
= STATE_OPEN
;
510 int QuicHttpStream::ParseResponseHeaders() {
511 size_t read_buf_len
= static_cast<size_t>(read_buf_
->offset());
512 SpdyFramer
framer(SPDY3
);
513 SpdyHeaderBlock headers
;
514 char* data
= read_buf_
->StartOfBuffer();
515 size_t len
= framer
.ParseHeaderBlockInBuffer(data
, read_buf_
->offset(),
519 return ERR_IO_PENDING
;
522 // Save the remaining received data.
523 size_t delta
= read_buf_len
- len
;
525 BufferResponseBody(data
+ len
, delta
);
528 // The URLRequest logs these headers, so only log to the QuicSession's
530 stream_
->net_log().AddEvent(
531 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS
,
532 base::Bind(&SpdyHeaderBlockNetLogCallback
, &headers
));
534 if (!SpdyHeadersToHttpResponse(headers
, SPDY3
, response_info_
)) {
535 DLOG(WARNING
) << "Invalid headers";
536 return ERR_QUIC_PROTOCOL_ERROR
;
538 // Put the peer's IP address and port into the response.
539 IPEndPoint address
= stream_
->GetPeerAddress();
540 response_info_
->socket_address
= HostPortPair::FromIPEndPoint(address
);
541 response_info_
->connection_info
=
542 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3
;
543 response_info_
->vary_data
544 .Init(*request_info_
, *response_info_
->headers
.get());
545 response_info_
->was_npn_negotiated
= true;
546 response_info_
->npn_negotiated_protocol
= "quic/1+spdy/3";
547 response_headers_received_
= true;
552 void QuicHttpStream::BufferResponseBody(const char* data
, int length
) {
555 IOBufferWithSize
* io_buffer
= new IOBufferWithSize(length
);
556 memcpy(io_buffer
->data(), data
, length
);
557 response_body_
.push_back(make_scoped_refptr(io_buffer
));