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;
74 request_time_ = base::Time::Now();
77 int rv = stream_request_.StartRequest(
78 session_, &stream_, base::Bind(&QuicHttpStream::OnStreamReady,
79 weak_factory_.GetWeakPtr()));
80 if (rv == ERR_IO_PENDING) {
82 } else if (rv == OK) {
83 stream_->SetDelegate(this);
84 } else if (!was_handshake_confirmed_) {
85 rv = ERR_QUIC_HANDSHAKE_FAILED;
91 void QuicHttpStream::OnStreamReady(int rv) {
92 DCHECK(rv == OK || !stream_);
94 stream_->SetDelegate(this);
95 } else if (!was_handshake_confirmed_) {
96 rv = ERR_QUIC_HANDSHAKE_FAILED;
99 ResetAndReturn(&callback_).Run(rv);
102 int QuicHttpStream::SendRequest(const HttpRequestHeaders& request_headers,
103 HttpResponseInfo* response,
104 const CompletionCallback& callback) {
105 CHECK(!request_body_stream_);
106 CHECK(!response_info_);
107 CHECK(!callback.is_null());
111 return ERR_CONNECTION_CLOSED;
114 QuicPriority priority = ConvertRequestPriorityToQuicPriority(priority_);
115 stream_->set_priority(priority);
116 // Store the serialized request headers.
117 CreateSpdyHeadersFromHttpRequest(*request_info_, request_headers,
118 SPDY3, /*direct=*/true, &request_headers_);
120 // Store the request body.
121 request_body_stream_ = request_info_->upload_data_stream;
122 if (request_body_stream_) {
123 // TODO(rch): Can we be more precise about when to allocate
124 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
125 // was being called even if we didn't yet allocate raw_request_body_buf_.
126 // && (request_body_stream_->size() ||
127 // request_body_stream_->is_chunked()))
128 // Use 10 packets as the body buffer size to give enough space to
129 // help ensure we don't often send out partial packets.
130 raw_request_body_buf_ = new IOBufferWithSize(10 * kMaxPacketSize);
131 // The request body buffer is empty at first.
132 request_body_buf_ = new DrainableIOBuffer(raw_request_body_buf_.get(), 0);
135 // Store the response info.
136 response_info_ = response;
138 next_state_ = STATE_SEND_HEADERS;
140 if (rv == ERR_IO_PENDING)
141 callback_ = callback;
143 return rv > 0 ? OK : rv;
146 UploadProgress QuicHttpStream::GetUploadProgress() const {
147 if (!request_body_stream_)
148 return UploadProgress();
150 return UploadProgress(request_body_stream_->position(),
151 request_body_stream_->size());
154 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback& callback) {
155 CHECK(!callback.is_null());
158 return response_status_;
160 // Check if we already have the response headers. If so, return synchronously.
161 if (response_headers_received_)
164 // Still waiting for the response, return IO_PENDING.
165 CHECK(callback_.is_null());
166 callback_ = callback;
167 return ERR_IO_PENDING;
170 int QuicHttpStream::ReadResponseBody(
171 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
174 CHECK(!callback.is_null());
176 // If we have data buffered, complete the IO immediately.
177 if (!response_body_.empty()) {
179 while (!response_body_.empty() && buf_len > 0) {
180 scoped_refptr<IOBufferWithSize> data = response_body_.front();
181 const int bytes_to_copy = std::min(buf_len, data->size());
182 memcpy(&(buf->data()[bytes_read]), data->data(), bytes_to_copy);
183 buf_len -= bytes_to_copy;
184 if (bytes_to_copy == data->size()) {
185 response_body_.pop_front();
187 const int bytes_remaining = data->size() - bytes_to_copy;
188 IOBufferWithSize* new_buffer = new IOBufferWithSize(bytes_remaining);
189 memcpy(new_buffer->data(), &(data->data()[bytes_to_copy]),
191 response_body_.pop_front();
192 response_body_.push_front(make_scoped_refptr(new_buffer));
194 bytes_read += bytes_to_copy;
200 // If the stream is already closed, there is no body to read.
201 return response_status_;
204 CHECK(callback_.is_null());
205 CHECK(!user_buffer_.get());
206 CHECK_EQ(0, user_buffer_len_);
208 callback_ = callback;
210 user_buffer_len_ = buf_len;
211 return ERR_IO_PENDING;
214 void QuicHttpStream::Close(bool not_reusable) {
215 // Note: the not_reusable flag has no meaning for SPDY streams.
217 closed_stream_received_bytes_ = stream_->stream_bytes_read();
218 stream_->SetDelegate(NULL);
219 stream_->Reset(QUIC_STREAM_CANCELLED);
221 response_status_ = was_handshake_confirmed_ ?
222 ERR_CONNECTION_CLOSED : ERR_QUIC_HANDSHAKE_FAILED;
226 HttpStream* QuicHttpStream::RenewStreamForAuth() {
230 bool QuicHttpStream::IsResponseBodyComplete() const {
231 return next_state_ == STATE_OPEN && !stream_;
234 bool QuicHttpStream::CanFindEndOfResponse() const {
238 bool QuicHttpStream::IsConnectionReused() const {
239 // TODO(rch): do something smarter here.
240 return stream_ && stream_->id() > 1;
243 void QuicHttpStream::SetConnectionReused() {
244 // QUIC doesn't need an indicator here.
247 bool QuicHttpStream::IsConnectionReusable() const {
248 // QUIC streams aren't considered reusable.
252 int64 QuicHttpStream::GetTotalReceivedBytes() const {
254 return stream_->stream_bytes_read();
257 return closed_stream_received_bytes_;
260 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
261 // TODO(mmenke): Figure out what to do here.
265 void QuicHttpStream::GetSSLInfo(SSLInfo* ssl_info) {
267 stream_->GetSSLInfo(ssl_info);
270 void QuicHttpStream::GetSSLCertRequestInfo(
271 SSLCertRequestInfo* cert_request_info) {
276 bool QuicHttpStream::IsSpdyHttpStream() const {
280 void QuicHttpStream::Drain(HttpNetworkSession* session) {
285 void QuicHttpStream::SetPriority(RequestPriority priority) {
286 priority_ = priority;
289 int QuicHttpStream::OnDataReceived(const char* data, int length) {
290 DCHECK_NE(0, length);
291 // Are we still reading the response headers.
292 if (!response_headers_received_) {
293 // Grow the read buffer if necessary.
294 if (read_buf_->RemainingCapacity() < length) {
295 size_t additional_capacity = length - read_buf_->RemainingCapacity();
296 if (additional_capacity < kHeaderBufInitialSize)
297 additional_capacity = kHeaderBufInitialSize;
298 read_buf_->SetCapacity(read_buf_->capacity() + additional_capacity);
300 memcpy(read_buf_->data(), data, length);
301 read_buf_->set_offset(read_buf_->offset() + length);
302 int rv = ParseResponseHeaders();
303 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
309 if (callback_.is_null()) {
310 BufferResponseBody(data, length);
314 if (length <= user_buffer_len_) {
315 memcpy(user_buffer_->data(), data, length);
317 memcpy(user_buffer_->data(), data, user_buffer_len_);
318 int delta = length - user_buffer_len_;
319 BufferResponseBody(data + user_buffer_len_, delta);
320 length = user_buffer_len_;
324 user_buffer_len_ = 0;
329 void QuicHttpStream::OnClose(QuicErrorCode error) {
330 if (error != QUIC_NO_ERROR) {
331 response_status_ = was_handshake_confirmed_ ?
332 ERR_QUIC_PROTOCOL_ERROR : ERR_QUIC_HANDSHAKE_FAILED;
333 } else if (!response_headers_received_) {
334 response_status_ = ERR_ABORTED;
337 closed_stream_received_bytes_ = stream_->stream_bytes_read();
339 if (!callback_.is_null())
340 DoCallback(response_status_);
343 void QuicHttpStream::OnError(int error) {
345 response_status_ = was_handshake_confirmed_ ?
346 error : ERR_QUIC_HANDSHAKE_FAILED;
347 if (!callback_.is_null())
348 DoCallback(response_status_);
351 bool QuicHttpStream::HasSendHeadersComplete() {
352 return next_state_ > STATE_SEND_HEADERS_COMPLETE;
355 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
356 was_handshake_confirmed_ = true;
359 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, stream_->id(), &request_headers_,
430 // Also log to the QuicSession's net log.
431 stream_->net_log().AddEvent(
432 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS,
433 base::Bind(&QuicRequestNetLogCallback, stream_->id(), &request_headers_,
436 bool has_upload_data = request_body_stream_ != NULL;
438 next_state_ = STATE_SEND_HEADERS_COMPLETE;
439 int rv = stream_->WriteHeaders(request_headers_, !has_upload_data, NULL);
440 request_headers_.clear();
444 int QuicHttpStream::DoSendHeadersComplete(int rv) {
448 next_state_ = request_body_stream_ ?
449 STATE_READ_REQUEST_BODY : STATE_OPEN;
454 int QuicHttpStream::DoReadRequestBody() {
455 next_state_ = STATE_READ_REQUEST_BODY_COMPLETE;
456 return request_body_stream_->Read(
457 raw_request_body_buf_.get(),
458 raw_request_body_buf_->size(),
459 base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
462 int QuicHttpStream::DoReadRequestBodyComplete(int rv) {
463 // |rv| is the result of read from the request body from the last call to
468 request_body_buf_ = new DrainableIOBuffer(raw_request_body_buf_.get(), rv);
469 if (rv == 0) { // Reached the end.
470 DCHECK(request_body_stream_->IsEOF());
473 next_state_ = STATE_SEND_BODY;
477 int QuicHttpStream::DoSendBody() {
479 return ERR_UNEXPECTED;
481 CHECK(request_body_stream_);
482 CHECK(request_body_buf_.get());
483 const bool eof = request_body_stream_->IsEOF();
484 int len = request_body_buf_->BytesRemaining();
485 if (len > 0 || eof) {
486 next_state_ = STATE_SEND_BODY_COMPLETE;
487 base::StringPiece data(request_body_buf_->data(), len);
488 return stream_->WriteStreamData(
490 base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
493 next_state_ = STATE_OPEN;
497 int QuicHttpStream::DoSendBodyComplete(int rv) {
501 request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
503 if (!request_body_stream_->IsEOF()) {
504 next_state_ = STATE_READ_REQUEST_BODY;
508 next_state_ = STATE_OPEN;
512 int QuicHttpStream::ParseResponseHeaders() {
513 size_t read_buf_len = static_cast<size_t>(read_buf_->offset());
514 SpdyFramer framer(SPDY3);
515 SpdyHeaderBlock headers;
516 char* data = read_buf_->StartOfBuffer();
517 size_t len = framer.ParseHeaderBlockInBuffer(data, read_buf_->offset(),
521 return ERR_IO_PENDING;
524 // Save the remaining received data.
525 size_t delta = read_buf_len - len;
527 BufferResponseBody(data + len, delta);
530 // The URLRequest logs these headers, so only log to the QuicSession's
532 stream_->net_log().AddEvent(
533 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS,
534 base::Bind(&SpdyHeaderBlockNetLogCallback, &headers));
536 if (!SpdyHeadersToHttpResponse(headers, SPDY3, response_info_)) {
537 DLOG(WARNING) << "Invalid headers";
538 return ERR_QUIC_PROTOCOL_ERROR;
540 // Put the peer's IP address and port into the response.
541 IPEndPoint address = stream_->GetPeerAddress();
542 response_info_->socket_address = HostPortPair::FromIPEndPoint(address);
543 response_info_->connection_info =
544 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3;
545 response_info_->vary_data
546 .Init(*request_info_, *response_info_->headers.get());
547 response_info_->was_npn_negotiated = true;
548 response_info_->npn_negotiated_protocol = "quic/1+spdy/3";
549 response_info_->response_time = base::Time::Now();
550 response_info_->request_time = request_time_;
551 response_headers_received_ = true;
556 void QuicHttpStream::BufferResponseBody(const char* data, int length) {
559 IOBufferWithSize* io_buffer = new IOBufferWithSize(length);
560 memcpy(io_buffer->data(), data, length);
561 response_body_.push_back(make_scoped_refptr(io_buffer));