Remove PlatformFile from profile_browsertest
[chromium-blink-merge.git] / net / quic / quic_http_stream.cc
blob77bfc8de8096628df67f49e0a1c8f0ce23e4c8b5
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"
24 namespace net {
26 static const size_t kHeaderBufInitialSize = 4096;
28 QuicHttpStream::QuicHttpStream(const base::WeakPtr<QuicClientSession>& session)
29 : next_state_(STATE_NONE),
30 session_(session),
31 session_error_(OK),
32 was_handshake_confirmed_(session->IsCryptoHandshakeConfirmed()),
33 stream_(NULL),
34 request_info_(NULL),
35 request_body_stream_(NULL),
36 priority_(MINIMUM_PRIORITY),
37 response_info_(NULL),
38 response_status_(OK),
39 response_headers_received_(false),
40 read_buf_(new GrowableIOBuffer()),
41 closed_stream_received_bytes_(0),
42 user_buffer_len_(0),
43 weak_factory_(this) {
44 DCHECK(session_);
45 session_->AddObserver(this);
48 QuicHttpStream::~QuicHttpStream() {
49 Close(false);
50 if (session_)
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) {
58 DCHECK(!stream_);
59 if (!session_)
60 return was_handshake_confirmed_ ? ERR_CONNECTION_CLOSED :
61 ERR_QUIC_HANDSHAKE_FAILED;
63 if (request_info->url.SchemeIsSecure()) {
64 SSLInfo ssl_info;
65 bool secure_session = session_->GetSSLInfo(&ssl_info) && ssl_info.cert;
66 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
67 secure_session);
68 if (!secure_session)
69 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC;
72 stream_net_log_ = stream_net_log;
73 request_info_ = request_info;
74 priority_ = priority;
76 int rv = stream_request_.StartRequest(
77 session_, &stream_, base::Bind(&QuicHttpStream::OnStreamReady,
78 weak_factory_.GetWeakPtr()));
79 if (rv == ERR_IO_PENDING) {
80 callback_ = callback;
81 } else if (rv == OK) {
82 stream_->SetDelegate(this);
83 } else if (!was_handshake_confirmed_) {
84 rv = ERR_QUIC_HANDSHAKE_FAILED;
87 return rv;
90 void QuicHttpStream::OnStreamReady(int rv) {
91 DCHECK(rv == OK || !stream_);
92 if (rv == OK) {
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) {
104 CHECK(stream_);
105 CHECK(!request_body_stream_);
106 CHECK(!response_info_);
107 CHECK(!callback.is_null());
108 CHECK(response);
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;
138 int rv = DoLoop(OK);
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());
156 if (stream_ == NULL)
157 return response_status_;
159 // Check if we already have the response headers. If so, return synchronously.
160 if (response_headers_received_)
161 return OK;
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) {
175 CHECK(buf);
176 CHECK(buf_len);
177 CHECK(!callback.is_null());
179 // If we have data buffered, complete the IO immediately.
180 if (!response_body_.empty()) {
181 int bytes_read = 0;
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();
189 } else {
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]),
193 bytes_remaining);
194 response_body_.pop_front();
195 response_body_.push_front(make_scoped_refptr(new_buffer));
197 bytes_read += bytes_to_copy;
199 return bytes_read;
202 if (!stream_) {
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;
212 user_buffer_ = buf;
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.
219 if (stream_) {
220 closed_stream_received_bytes_ = stream_->stream_bytes_read();
221 stream_->SetDelegate(NULL);
222 stream_->Reset(QUIC_STREAM_CANCELLED);
223 stream_ = NULL;
227 HttpStream* QuicHttpStream::RenewStreamForAuth() {
228 return NULL;
231 bool QuicHttpStream::IsResponseBodyComplete() const {
232 return next_state_ == STATE_OPEN && !stream_;
235 bool QuicHttpStream::CanFindEndOfResponse() const {
236 return true;
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.
250 return false;
253 int64 QuicHttpStream::GetTotalReceivedBytes() const {
254 if (stream_) {
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.
263 return true;
266 void QuicHttpStream::GetSSLInfo(SSLInfo* ssl_info) {
267 DCHECK(stream_);
268 stream_->GetSSLInfo(ssl_info);
271 void QuicHttpStream::GetSSLCertRequestInfo(
272 SSLCertRequestInfo* cert_request_info) {
273 DCHECK(stream_);
274 NOTIMPLEMENTED();
277 bool QuicHttpStream::IsSpdyHttpStream() const {
278 return false;
281 void QuicHttpStream::Drain(HttpNetworkSession* session) {
282 Close(false);
283 delete this;
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()) {
305 DoCallback(rv);
307 return OK;
310 if (callback_.is_null()) {
311 BufferResponseBody(data, length);
312 return OK;
315 if (length <= user_buffer_len_) {
316 memcpy(user_buffer_->data(), data, length);
317 } else {
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_;
324 user_buffer_ = NULL;
325 user_buffer_len_ = 0;
326 DoCallback(length);
327 return OK;
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();
339 stream_ = NULL;
340 if (!callback_.is_null())
341 DoCallback(response_status_);
344 void QuicHttpStream::OnError(int error) {
345 stream_ = NULL;
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;
362 session_.reset();
365 void QuicHttpStream::OnIOComplete(int rv) {
366 rv = DoLoop(rv);
368 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
369 DoCallback(rv);
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) {
383 do {
384 State state = next_state_;
385 next_state_ = STATE_NONE;
386 switch (state) {
387 case STATE_SEND_HEADERS:
388 CHECK_EQ(OK, rv);
389 rv = DoSendHeaders();
390 break;
391 case STATE_SEND_HEADERS_COMPLETE:
392 rv = DoSendHeadersComplete(rv);
393 break;
394 case STATE_READ_REQUEST_BODY:
395 CHECK_EQ(OK, rv);
396 rv = DoReadRequestBody();
397 break;
398 case STATE_READ_REQUEST_BODY_COMPLETE:
399 rv = DoReadRequestBodyComplete(rv);
400 break;
401 case STATE_SEND_BODY:
402 CHECK_EQ(OK, rv);
403 rv = DoSendBody();
404 break;
405 case STATE_SEND_BODY_COMPLETE:
406 rv = DoSendBodyComplete(rv);
407 break;
408 case STATE_OPEN:
409 CHECK_EQ(OK, rv);
410 break;
411 default:
412 NOTREACHED() << "next_state_: " << next_state_;
413 break;
415 } while (next_state_ != STATE_NONE && next_state_ != STATE_OPEN &&
416 rv != ERR_IO_PENDING);
418 return rv;
421 int QuicHttpStream::DoSendHeaders() {
422 if (!stream_)
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();
439 return rv;
442 int QuicHttpStream::DoSendHeadersComplete(int rv) {
443 if (rv < 0)
444 return rv;
446 next_state_ = request_body_stream_ ?
447 STATE_READ_REQUEST_BODY : STATE_OPEN;
449 return OK;
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
462 // DoSendBody().
463 if (rv < 0)
464 return rv;
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;
472 return OK;
475 int QuicHttpStream::DoSendBody() {
476 if (!stream_)
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(
487 data, eof,
488 base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
491 next_state_ = STATE_OPEN;
492 return OK;
495 int QuicHttpStream::DoSendBodyComplete(int rv) {
496 if (rv < 0)
497 return rv;
499 request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
501 if (!request_body_stream_->IsEOF()) {
502 next_state_ = STATE_READ_REQUEST_BODY;
503 return OK;
506 next_state_ = STATE_OPEN;
507 return OK;
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(),
516 &headers);
518 if (len == 0) {
519 return ERR_IO_PENDING;
522 // Save the remaining received data.
523 size_t delta = read_buf_len - len;
524 if (delta > 0) {
525 BufferResponseBody(data + len, delta);
528 // The URLRequest logs these headers, so only log to the QuicSession's
529 // net log.
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;
549 return OK;
552 void QuicHttpStream::BufferResponseBody(const char* data, int length) {
553 if (length == 0)
554 return;
555 IOBufferWithSize* io_buffer = new IOBufferWithSize(length);
556 memcpy(io_buffer->data(), data, length);
557 response_body_.push_back(make_scoped_refptr(io_buffer));
560 } // namespace net