3ddfa062616075f59c765299036df94e9e4d10c4
[platform/framework/web/crosswalk.git] / src / net / quic / quic_http_stream.cc
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.
4
5 #include "net/quic/quic_http_stream.h"
6
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"
23
24 namespace net {
25
26 static const size_t kHeaderBufInitialSize = 4096;
27
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);
46 }
47
48 QuicHttpStream::~QuicHttpStream() {
49   Close(false);
50   if (session_)
51     session_->RemoveObserver(this);
52 }
53
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;
62
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;
70   }
71
72   stream_net_log_ = stream_net_log;
73   request_info_ = request_info;
74   request_time_ = base::Time::Now();
75   priority_ = priority;
76
77   int rv = stream_request_.StartRequest(
78       session_, &stream_, base::Bind(&QuicHttpStream::OnStreamReady,
79                                      weak_factory_.GetWeakPtr()));
80   if (rv == ERR_IO_PENDING) {
81     callback_ = callback;
82   } else if (rv == OK) {
83     stream_->SetDelegate(this);
84   } else if (!was_handshake_confirmed_) {
85     rv = ERR_QUIC_HANDSHAKE_FAILED;
86   }
87
88   return rv;
89 }
90
91 void QuicHttpStream::OnStreamReady(int rv) {
92   DCHECK(rv == OK || !stream_);
93   if (rv == OK) {
94     stream_->SetDelegate(this);
95   } else if (!was_handshake_confirmed_) {
96     rv = ERR_QUIC_HANDSHAKE_FAILED;
97   }
98
99   ResetAndReturn(&callback_).Run(rv);
100 }
101
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());
108   CHECK(response);
109
110    if (!stream_) {
111     return ERR_CONNECTION_CLOSED;
112   }
113
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_);
119
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);
133   }
134
135   // Store the response info.
136   response_info_ = response;
137
138   next_state_ = STATE_SEND_HEADERS;
139   int rv = DoLoop(OK);
140   if (rv == ERR_IO_PENDING)
141     callback_ = callback;
142
143   return rv > 0 ? OK : rv;
144 }
145
146 UploadProgress QuicHttpStream::GetUploadProgress() const {
147   if (!request_body_stream_)
148     return UploadProgress();
149
150   return UploadProgress(request_body_stream_->position(),
151                         request_body_stream_->size());
152 }
153
154 int QuicHttpStream::ReadResponseHeaders(const CompletionCallback& callback) {
155   CHECK(!callback.is_null());
156
157   if (stream_ == NULL)
158     return response_status_;
159
160   // Check if we already have the response headers. If so, return synchronously.
161   if (response_headers_received_)
162     return OK;
163
164   // Still waiting for the response, return IO_PENDING.
165   CHECK(callback_.is_null());
166   callback_ = callback;
167   return ERR_IO_PENDING;
168 }
169
170 int QuicHttpStream::ReadResponseBody(
171     IOBuffer* buf, int buf_len, const CompletionCallback& callback) {
172   CHECK(buf);
173   CHECK(buf_len);
174   CHECK(!callback.is_null());
175
176   // If we have data buffered, complete the IO immediately.
177   if (!response_body_.empty()) {
178     int bytes_read = 0;
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();
186       } else {
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]),
190                bytes_remaining);
191         response_body_.pop_front();
192         response_body_.push_front(make_scoped_refptr(new_buffer));
193       }
194       bytes_read += bytes_to_copy;
195     }
196     return bytes_read;
197   }
198
199   if (!stream_) {
200     // If the stream is already closed, there is no body to read.
201     return response_status_;
202   }
203
204   CHECK(callback_.is_null());
205   CHECK(!user_buffer_.get());
206   CHECK_EQ(0, user_buffer_len_);
207
208   callback_ = callback;
209   user_buffer_ = buf;
210   user_buffer_len_ = buf_len;
211   return ERR_IO_PENDING;
212 }
213
214 void QuicHttpStream::Close(bool not_reusable) {
215   // Note: the not_reusable flag has no meaning for SPDY streams.
216   if (stream_) {
217     closed_stream_received_bytes_ = stream_->stream_bytes_read();
218     stream_->SetDelegate(NULL);
219     stream_->Reset(QUIC_STREAM_CANCELLED);
220     stream_ = NULL;
221     response_status_ = was_handshake_confirmed_ ?
222         ERR_CONNECTION_CLOSED : ERR_QUIC_HANDSHAKE_FAILED;
223   }
224 }
225
226 HttpStream* QuicHttpStream::RenewStreamForAuth() {
227   return NULL;
228 }
229
230 bool QuicHttpStream::IsResponseBodyComplete() const {
231   return next_state_ == STATE_OPEN && !stream_;
232 }
233
234 bool QuicHttpStream::CanFindEndOfResponse() const {
235   return true;
236 }
237
238 bool QuicHttpStream::IsConnectionReused() const {
239   // TODO(rch): do something smarter here.
240   return stream_ && stream_->id() > 1;
241 }
242
243 void QuicHttpStream::SetConnectionReused() {
244   // QUIC doesn't need an indicator here.
245 }
246
247 bool QuicHttpStream::IsConnectionReusable() const {
248   // QUIC streams aren't considered reusable.
249   return false;
250 }
251
252 int64 QuicHttpStream::GetTotalReceivedBytes() const {
253   if (stream_) {
254     return stream_->stream_bytes_read();
255   }
256
257   return closed_stream_received_bytes_;
258 }
259
260 bool QuicHttpStream::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
261   // TODO(mmenke):  Figure out what to do here.
262   return true;
263 }
264
265 void QuicHttpStream::GetSSLInfo(SSLInfo* ssl_info) {
266   DCHECK(stream_);
267   stream_->GetSSLInfo(ssl_info);
268 }
269
270 void QuicHttpStream::GetSSLCertRequestInfo(
271     SSLCertRequestInfo* cert_request_info) {
272   DCHECK(stream_);
273   NOTIMPLEMENTED();
274 }
275
276 bool QuicHttpStream::IsSpdyHttpStream() const {
277   return false;
278 }
279
280 void QuicHttpStream::Drain(HttpNetworkSession* session) {
281   Close(false);
282   delete this;
283 }
284
285 void QuicHttpStream::SetPriority(RequestPriority priority) {
286   priority_ = priority;
287 }
288
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);
299     }
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()) {
304       DoCallback(rv);
305     }
306     return OK;
307   }
308
309   if (callback_.is_null()) {
310     BufferResponseBody(data, length);
311     return OK;
312   }
313
314   if (length <= user_buffer_len_) {
315     memcpy(user_buffer_->data(), data, length);
316   } else {
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_;
321   }
322
323   user_buffer_ = NULL;
324   user_buffer_len_ = 0;
325   DoCallback(length);
326   return OK;
327 }
328
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;
335   }
336
337   closed_stream_received_bytes_ = stream_->stream_bytes_read();
338   stream_ = NULL;
339   if (!callback_.is_null())
340     DoCallback(response_status_);
341 }
342
343 void QuicHttpStream::OnError(int error) {
344   stream_ = NULL;
345   response_status_ = was_handshake_confirmed_ ?
346       error : ERR_QUIC_HANDSHAKE_FAILED;
347   if (!callback_.is_null())
348     DoCallback(response_status_);
349 }
350
351 bool QuicHttpStream::HasSendHeadersComplete() {
352   return next_state_ > STATE_SEND_HEADERS_COMPLETE;
353 }
354
355 void QuicHttpStream::OnCryptoHandshakeConfirmed() {
356   was_handshake_confirmed_ = true;
357 }
358
359 void QuicHttpStream::OnSessionClosed(int error) {
360   Close(false);
361   session_error_ = error;
362   session_.reset();
363 }
364
365 void QuicHttpStream::OnIOComplete(int rv) {
366   rv = DoLoop(rv);
367
368   if (rv != ERR_IO_PENDING && !callback_.is_null()) {
369     DoCallback(rv);
370   }
371 }
372
373 void QuicHttpStream::DoCallback(int rv) {
374   CHECK_NE(rv, ERR_IO_PENDING);
375   CHECK(!callback_.is_null());
376
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);
380 }
381
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;
414     }
415   } while (next_state_ != STATE_NONE && next_state_ != STATE_OPEN &&
416            rv != ERR_IO_PENDING);
417
418   return rv;
419 }
420
421 int QuicHttpStream::DoSendHeaders() {
422   if (!stream_)
423     return ERR_UNEXPECTED;
424
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_,
429                  priority_));
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_,
434                  priority_));
435
436   bool has_upload_data = request_body_stream_ != NULL;
437
438   next_state_ = STATE_SEND_HEADERS_COMPLETE;
439   int rv = stream_->WriteHeaders(request_headers_, !has_upload_data, NULL);
440   request_headers_.clear();
441   return rv;
442 }
443
444 int QuicHttpStream::DoSendHeadersComplete(int rv) {
445   if (rv < 0)
446     return rv;
447
448   next_state_ = request_body_stream_ ?
449       STATE_READ_REQUEST_BODY : STATE_OPEN;
450
451   return OK;
452 }
453
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()));
460 }
461
462 int QuicHttpStream::DoReadRequestBodyComplete(int rv) {
463   // |rv| is the result of read from the request body from the last call to
464   // DoSendBody().
465   if (rv < 0)
466     return rv;
467
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());
471   }
472
473   next_state_ = STATE_SEND_BODY;
474   return OK;
475 }
476
477 int QuicHttpStream::DoSendBody() {
478   if (!stream_)
479     return ERR_UNEXPECTED;
480
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(
489         data, eof,
490         base::Bind(&QuicHttpStream::OnIOComplete, weak_factory_.GetWeakPtr()));
491   }
492
493   next_state_ = STATE_OPEN;
494   return OK;
495 }
496
497 int QuicHttpStream::DoSendBodyComplete(int rv) {
498   if (rv < 0)
499     return rv;
500
501   request_body_buf_->DidConsume(request_body_buf_->BytesRemaining());
502
503   if (!request_body_stream_->IsEOF()) {
504     next_state_ = STATE_READ_REQUEST_BODY;
505     return OK;
506   }
507
508   next_state_ = STATE_OPEN;
509   return OK;
510 }
511
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(),
518                                                &headers);
519
520   if (len == 0) {
521     return ERR_IO_PENDING;
522   }
523
524   // Save the remaining received data.
525   size_t delta = read_buf_len - len;
526   if (delta > 0) {
527     BufferResponseBody(data + len, delta);
528   }
529
530   // The URLRequest logs these headers, so only log to the QuicSession's
531   // net log.
532   stream_->net_log().AddEvent(
533       NetLog::TYPE_QUIC_HTTP_STREAM_READ_RESPONSE_HEADERS,
534       base::Bind(&SpdyHeaderBlockNetLogCallback, &headers));
535
536   if (!SpdyHeadersToHttpResponse(headers, SPDY3, response_info_)) {
537     DLOG(WARNING) << "Invalid headers";
538     return ERR_QUIC_PROTOCOL_ERROR;
539   }
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;
552
553   return OK;
554 }
555
556 void QuicHttpStream::BufferResponseBody(const char* data, int length) {
557   if (length == 0)
558     return;
559   IOBufferWithSize* io_buffer = new IOBufferWithSize(length);
560   memcpy(io_buffer->data(), data, length);
561   response_body_.push_back(make_scoped_refptr(io_buffer));
562 }
563
564 }  // namespace net