Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / net / quic / quic_http_stream.cc
blob87332f9a8f4d1de453fc14aada87482c4ed9a72f
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/quic/spdy_utils.h"
19 #include "net/socket/next_proto.h"
20 #include "net/spdy/spdy_frame_builder.h"
21 #include "net/spdy/spdy_framer.h"
22 #include "net/spdy/spdy_http_utils.h"
23 #include "net/ssl/ssl_info.h"
25 namespace net {
27 static const size_t kHeaderBufInitialSize = 4096;
29 QuicHttpStream::QuicHttpStream(const base::WeakPtr<QuicClientSession>& session)
30 : next_state_(STATE_NONE),
31 session_(session),
32 session_error_(OK),
33 was_handshake_confirmed_(session->IsCryptoHandshakeConfirmed()),
34 stream_(nullptr),
35 request_info_(nullptr),
36 request_body_stream_(nullptr),
37 priority_(MINIMUM_PRIORITY),
38 response_info_(nullptr),
39 response_status_(OK),
40 response_headers_received_(false),
41 read_buf_(new GrowableIOBuffer()),
42 closed_stream_received_bytes_(0),
43 user_buffer_len_(0),
44 weak_factory_(this) {
45 DCHECK(session_);
46 session_->AddObserver(this);
49 QuicHttpStream::~QuicHttpStream() {
50 Close(false);
51 if (session_)
52 session_->RemoveObserver(this);
55 int QuicHttpStream::InitializeStream(const HttpRequestInfo* request_info,
56 RequestPriority priority,
57 const BoundNetLog& stream_net_log,
58 const CompletionCallback& callback) {
59 DCHECK(!stream_);
60 if (!session_)
61 return was_handshake_confirmed_ ? ERR_CONNECTION_CLOSED :
62 ERR_QUIC_HANDSHAKE_FAILED;
64 stream_net_log.AddEvent(
65 NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_QUIC_SESSION,
66 session_->net_log().source().ToEventParametersCallback());
68 if (request_info->url.SchemeIsSecure()) {
69 SSLInfo ssl_info;
70 bool secure_session =
71 session_->GetSSLInfo(&ssl_info) && ssl_info.cert.get();
72 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.SecureResourceSecureSession",
73 secure_session);
74 if (!secure_session)
75 return ERR_REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC;
78 stream_net_log_ = stream_net_log;
79 request_info_ = request_info;
80 request_time_ = base::Time::Now();
81 priority_ = priority;
83 int rv = stream_request_.StartRequest(
84 session_, &stream_, base::Bind(&QuicHttpStream::OnStreamReady,
85 weak_factory_.GetWeakPtr()));
86 if (rv == ERR_IO_PENDING) {
87 callback_ = callback;
88 } else if (rv == OK) {
89 stream_->SetDelegate(this);
90 } else if (!was_handshake_confirmed_) {
91 rv = ERR_QUIC_HANDSHAKE_FAILED;
94 return rv;
97 void QuicHttpStream::OnStreamReady(int rv) {
98 DCHECK(rv == OK || !stream_);
99 if (rv == OK) {
100 stream_->SetDelegate(this);
101 } else if (!was_handshake_confirmed_) {
102 rv = ERR_QUIC_HANDSHAKE_FAILED;
105 ResetAndReturn(&callback_).Run(rv);
108 int QuicHttpStream::SendRequest(const HttpRequestHeaders& request_headers,
109 HttpResponseInfo* response,
110 const CompletionCallback& callback) {
111 CHECK(!request_body_stream_);
112 CHECK(!response_info_);
113 CHECK(!callback.is_null());
114 CHECK(response);
116 // TODO(rch): remove this once we figure out why channel ID is not being
117 // sent when it should be.
118 HostPortPair origin = HostPortPair::FromURL(request_info_->url);
119 if (origin.Equals(HostPortPair("accounts.google.com", 443)) &&
120 request_headers.HasHeader(HttpRequestHeaders::kCookie)) {
121 SSLInfo ssl_info;
122 bool secure_session =
123 session_->GetSSLInfo(&ssl_info) && ssl_info.cert.get();
124 DCHECK(secure_session);
125 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.CookieSentToAccountsOverChannelId",
126 ssl_info.channel_id_sent);
128 if (!stream_) {
129 return ERR_CONNECTION_CLOSED;
132 QuicPriority priority = ConvertRequestPriorityToQuicPriority(priority_);
133 stream_->set_priority(priority);
134 // Store the serialized request headers.
135 CreateSpdyHeadersFromHttpRequest(*request_info_, request_headers,
136 GetSpdyVersion(),
137 /*direct=*/true, &request_headers_);
139 // Store the request body.
140 request_body_stream_ = request_info_->upload_data_stream;
141 if (request_body_stream_) {
142 // TODO(rch): Can we be more precise about when to allocate
143 // raw_request_body_buf_. Removed the following check. DoReadRequestBody()
144 // was being called even if we didn't yet allocate raw_request_body_buf_.
145 // && (request_body_stream_->size() ||
146 // request_body_stream_->is_chunked()))
147 // Use 10 packets as the body buffer size to give enough space to
148 // help ensure we don't often send out partial packets.
149 raw_request_body_buf_ = new IOBufferWithSize(10 * kMaxPacketSize);
150 // The request body buffer is empty at first.
151 request_body_buf_ = new DrainableIOBuffer(raw_request_body_buf_.get(), 0);
154 // Store the response info.
155 response_info_ = response;
157 next_state_ = STATE_SEND_HEADERS;
158 int rv = DoLoop(OK);
159 if (rv == ERR_IO_PENDING)
160 callback_ = callback;
162 return rv > 0 ? OK : rv;
165 UploadProgress QuicHttpStream::GetUploadProgress() const {
166 if (!request_body_stream_)
167 return UploadProgress();
169 return UploadProgress(request_body_stream_->position(),
170 request_body_stream_->size());
173 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback& callback) {
174 CHECK(!callback.is_null());
176 if (stream_ == nullptr)
177 return response_status_;
179 // Check if we already have the response headers. If so, return synchronously.
180 if (response_headers_received_)
181 return OK;
183 // Still waiting for the response, return IO_PENDING.
184 CHECK(callback_.is_null());
185 callback_ = callback;
186 return ERR_IO_PENDING;
189 int QuicHttpStream::ReadResponseBody(
190 IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
191 CHECK(buf);
192 CHECK(buf_len);
193 CHECK(!callback.is_null());
195 // If we have data buffered, complete the IO immediately.
196 if (!response_body_.empty()) {
197 int bytes_read = 0;
198 while (!response_body_.empty() && buf_len > 0) {
199 scoped_refptr<IOBufferWithSize> data = response_body_.front();
200 const int bytes_to_copy = std::min(buf_len, data->size());
201 memcpy(&(buf->data()[bytes_read]), data->data(), bytes_to_copy);
202 buf_len -= bytes_to_copy;
203 if (bytes_to_copy == data->size()) {
204 response_body_.pop_front();
205 } else {
206 const int bytes_remaining = data->size() - bytes_to_copy;
207 IOBufferWithSize* new_buffer = new IOBufferWithSize(bytes_remaining);
208 memcpy(new_buffer->data(), &(data->data()[bytes_to_copy]),
209 bytes_remaining);
210 response_body_.pop_front();
211 response_body_.push_front(make_scoped_refptr(new_buffer));
213 bytes_read += bytes_to_copy;
215 return bytes_read;
218 if (!stream_) {
219 // If the stream is already closed, there is no body to read.
220 return response_status_;
223 CHECK(callback_.is_null());
224 CHECK(!user_buffer_.get());
225 CHECK_EQ(0, user_buffer_len_);
227 callback_ = callback;
228 user_buffer_ = buf;
229 user_buffer_len_ = buf_len;
230 return ERR_IO_PENDING;
233 void QuicHttpStream::Close(bool not_reusable) {
234 // Note: the not_reusable flag has no meaning for SPDY streams.
235 if (stream_) {
236 closed_stream_received_bytes_ = stream_->stream_bytes_read();
237 stream_->SetDelegate(nullptr);
238 stream_->Reset(QUIC_STREAM_CANCELLED);
239 stream_ = nullptr;
240 response_status_ = was_handshake_confirmed_ ?
241 ERR_CONNECTION_CLOSED : ERR_QUIC_HANDSHAKE_FAILED;
245 HttpStream* QuicHttpStream::RenewStreamForAuth() {
246 return nullptr;
249 bool QuicHttpStream::IsResponseBodyComplete() const {
250 return next_state_ == STATE_OPEN && !stream_;
253 bool QuicHttpStream::CanFindEndOfResponse() const {
254 return true;
257 bool QuicHttpStream::IsConnectionReused() const {
258 // TODO(rch): do something smarter here.
259 return stream_ && stream_->id() > 1;
262 void QuicHttpStream::SetConnectionReused() {
263 // QUIC doesn't need an indicator here.
266 bool QuicHttpStream::IsConnectionReusable() const {
267 // QUIC streams aren't considered reusable.
268 return false;
271 int64 QuicHttpStream::GetTotalReceivedBytes() const {
272 if (stream_) {
273 return stream_->stream_bytes_read();
276 return closed_stream_received_bytes_;
279 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
280 // TODO(mmenke): Figure out what to do here.
281 return true;
284 void QuicHttpStream::GetSSLInfo(SSLInfo* ssl_info) {
285 DCHECK(stream_);
286 session_->GetSSLInfo(ssl_info);
289 void QuicHttpStream::GetSSLCertRequestInfo(
290 SSLCertRequestInfo* cert_request_info) {
291 DCHECK(stream_);
292 NOTIMPLEMENTED();
295 bool QuicHttpStream::IsSpdyHttpStream() const {
296 return false;
299 void QuicHttpStream::Drain(HttpNetworkSession* session) {
300 Close(false);
301 delete this;
304 void QuicHttpStream::SetPriority(RequestPriority priority) {
305 priority_ = priority;
308 int QuicHttpStream::OnDataReceived(const char* data, int length) {
309 DCHECK_NE(0, length);
310 // Are we still reading the response headers.
311 if (!response_headers_received_) {
312 // Grow the read buffer if necessary.
313 if (read_buf_->RemainingCapacity() < length) {
314 size_t additional_capacity = length - read_buf_->RemainingCapacity();
315 if (additional_capacity < kHeaderBufInitialSize)
316 additional_capacity = kHeaderBufInitialSize;
317 read_buf_->SetCapacity(read_buf_->capacity() + additional_capacity);
319 memcpy(read_buf_->data(), data, length);
320 read_buf_->set_offset(read_buf_->offset() + length);
321 int rv = ParseResponseHeaders();
322 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
323 DoCallback(rv);
325 return OK;
328 if (callback_.is_null()) {
329 BufferResponseBody(data, length);
330 return OK;
333 if (length <= user_buffer_len_) {
334 memcpy(user_buffer_->data(), data, length);
335 } else {
336 memcpy(user_buffer_->data(), data, user_buffer_len_);
337 int delta = length - user_buffer_len_;
338 BufferResponseBody(data + user_buffer_len_, delta);
339 length = user_buffer_len_;
342 user_buffer_ = nullptr;
343 user_buffer_len_ = 0;
344 DoCallback(length);
345 return OK;
348 void QuicHttpStream::OnClose(QuicErrorCode error) {
349 if (error != QUIC_NO_ERROR) {
350 response_status_ = was_handshake_confirmed_ ?
351 ERR_QUIC_PROTOCOL_ERROR : ERR_QUIC_HANDSHAKE_FAILED;
352 } else if (!response_headers_received_) {
353 response_status_ = ERR_ABORTED;
356 closed_stream_received_bytes_ = stream_->stream_bytes_read();
357 stream_ = nullptr;
358 if (!callback_.is_null())
359 DoCallback(response_status_);
362 void QuicHttpStream::OnError(int error) {
363 stream_ = nullptr;
364 response_status_ = was_handshake_confirmed_ ?
365 error : ERR_QUIC_HANDSHAKE_FAILED;
366 if (!callback_.is_null())
367 DoCallback(response_status_);
370 bool QuicHttpStream::HasSendHeadersComplete() {
371 return next_state_ > STATE_SEND_HEADERS_COMPLETE;
374 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
375 was_handshake_confirmed_ = true;
378 void QuicHttpStream::OnSessionClosed(int error) {
379 Close(false);
380 session_error_ = error;
381 session_.reset();
384 void QuicHttpStream::OnIOComplete(int rv) {
385 rv = DoLoop(rv);
387 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
388 DoCallback(rv);
392 void QuicHttpStream::DoCallback(int rv) {
393 CHECK_NE(rv, ERR_IO_PENDING);
394 CHECK(!callback_.is_null());
396 // The client callback can do anything, including destroying this class,
397 // so any pending callback must be issued after everything else is done.
398 base::ResetAndReturn(&callback_).Run(rv);
401 int QuicHttpStream::DoLoop(int rv) {
402 do {
403 State state = next_state_;
404 next_state_ = STATE_NONE;
405 switch (state) {
406 case STATE_SEND_HEADERS:
407 CHECK_EQ(OK, rv);
408 rv = DoSendHeaders();
409 break;
410 case STATE_SEND_HEADERS_COMPLETE:
411 rv = DoSendHeadersComplete(rv);
412 break;
413 case STATE_READ_REQUEST_BODY:
414 CHECK_EQ(OK, rv);
415 rv = DoReadRequestBody();
416 break;
417 case STATE_READ_REQUEST_BODY_COMPLETE:
418 rv = DoReadRequestBodyComplete(rv);
419 break;
420 case STATE_SEND_BODY:
421 CHECK_EQ(OK, rv);
422 rv = DoSendBody();
423 break;
424 case STATE_SEND_BODY_COMPLETE:
425 rv = DoSendBodyComplete(rv);
426 break;
427 case STATE_OPEN:
428 CHECK_EQ(OK, rv);
429 break;
430 default:
431 NOTREACHED() << "next_state_: " << next_state_;
432 break;
434 } while (next_state_ != STATE_NONE && next_state_ != STATE_OPEN &&
435 rv != ERR_IO_PENDING);
437 return rv;
440 int QuicHttpStream::DoSendHeaders() {
441 if (!stream_)
442 return ERR_UNEXPECTED;
444 // Log the actual request with the URL Request's net log.
445 stream_net_log_.AddEvent(
446 NetLog::TYPE_HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS,
447 base::Bind(&QuicRequestNetLogCallback, stream_->id(), &request_headers_,
448 priority_));
449 // Also log to the QuicSession's net log.
450 stream_->net_log().AddEvent(
451 NetLog::TYPE_QUIC_HTTP_STREAM_SEND_REQUEST_HEADERS,
452 base::Bind(&QuicRequestNetLogCallback, stream_->id(), &request_headers_,
453 priority_));
455 bool has_upload_data = request_body_stream_ != nullptr;
457 next_state_ = STATE_SEND_HEADERS_COMPLETE;
458 int rv = stream_->WriteHeaders(request_headers_, !has_upload_data, nullptr);
459 request_headers_.clear();
460 return rv;
463 int QuicHttpStream::DoSendHeadersComplete(int rv) {
464 if (rv < 0)
465 return rv;
467 next_state_ = request_body_stream_ ?
468 STATE_READ_REQUEST_BODY : STATE_OPEN;
470 return OK;
473 int QuicHttpStream::DoReadRequestBody() {
474 next_state_ = STATE_READ_REQUEST_BODY_COMPLETE;
475 return request_body_stream_->Read(
476 raw_request_body_buf_.get(),
477 raw_request_body_buf_->size(),
478 base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
481 int QuicHttpStream::DoReadRequestBodyComplete(int rv) {
482 // |rv| is the result of read from the request body from the last call to
483 // DoSendBody().
484 if (rv < 0)
485 return rv;
487 request_body_buf_ = new DrainableIOBuffer(raw_request_body_buf_.get(), rv);
488 if (rv == 0) { // Reached the end.
489 DCHECK(request_body_stream_->IsEOF());
492 next_state_ = STATE_SEND_BODY;
493 return OK;
496 int QuicHttpStream::DoSendBody() {
497 if (!stream_)
498 return ERR_UNEXPECTED;
500 CHECK(request_body_stream_);
501 CHECK(request_body_buf_.get());
502 const bool eof = request_body_stream_->IsEOF();
503 int len = request_body_buf_->BytesRemaining();
504 if (len > 0 || eof) {
505 next_state_ = STATE_SEND_BODY_COMPLETE;
506 base::StringPiece data(request_body_buf_->data(), len);
507 return stream_->WriteStreamData(
508 data, eof,
509 base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
512 next_state_ = STATE_OPEN;
513 return OK;
516 int QuicHttpStream::DoSendBodyComplete(int rv) {
517 if (rv < 0)
518 return rv;
520 request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
522 if (!request_body_stream_->IsEOF()) {
523 next_state_ = STATE_READ_REQUEST_BODY;
524 return OK;
527 next_state_ = STATE_OPEN;
528 return OK;
531 int QuicHttpStream::ParseResponseHeaders() {
532 size_t read_buf_len = static_cast<size_t>(read_buf_->offset());
533 SpdyFramer framer(GetSpdyVersion());
534 SpdyHeaderBlock headers;
535 char* data = read_buf_->StartOfBuffer();
536 size_t len = framer.ParseHeaderBlockInBuffer(data, read_buf_->offset(),
537 &headers);
539 if (len == 0) {
540 return ERR_IO_PENDING;
543 // Save the remaining received data.
544 size_t delta = read_buf_len - len;
545 if (delta > 0) {
546 BufferResponseBody(data + len, delta);
549 // The URLRequest logs these headers, so only log to the QuicSession's
550 // net log.
551 stream_->net_log().AddEvent(
552 NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS,
553 base::Bind(&SpdyHeaderBlockNetLogCallback, &headers));
555 if (!SpdyHeadersToHttpResponse(headers, GetSpdyVersion(), response_info_)) {
556 DLOG(WARNING) << "Invalid headers";
557 return ERR_QUIC_PROTOCOL_ERROR;
559 // Put the peer's IP address and port into the response.
560 IPEndPoint address = session_->peer_address();
561 response_info_->socket_address = HostPortPair::FromIPEndPoint(address);
562 response_info_->connection_info =
563 HttpResponseInfo::CONNECTION_INFO_QUIC1_SPDY3;
564 response_info_->vary_data
565 .Init(*request_info_, *response_info_->headers.get());
566 response_info_->was_npn_negotiated = true;
567 response_info_->npn_negotiated_protocol = "quic/1+spdy/3";
568 response_info_->response_time = base::Time::Now();
569 response_info_->request_time = request_time_;
570 response_headers_received_ = true;
572 return OK;
575 void QuicHttpStream::BufferResponseBody(const char* data, int length) {
576 if (length == 0)
577 return;
578 IOBufferWithSize* io_buffer = new IOBufferWithSize(length);
579 memcpy(io_buffer->data(), data, length);
580 response_body_.push_back(make_scoped_refptr(io_buffer));
583 SpdyMajorVersion QuicHttpStream::GetSpdyVersion() {
584 return SpdyUtils::GetSpdyVersionForQuicVersion(stream_->version());
587 } // namespace net