Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / http / http_stream_parser.cc
blob3c3b88d76d93dfed25087181b31c58f9aed250c7
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/http/http_stream_parser.h"
7 #include "base/bind.h"
8 #include "base/compiler_specific.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram_macros.h"
11 #include "base/profiler/scoped_tracker.h"
12 #include "base/strings/string_util.h"
13 #include "base/values.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/ip_endpoint.h"
16 #include "net/base/upload_data_stream.h"
17 #include "net/http/http_chunked_decoder.h"
18 #include "net/http/http_request_headers.h"
19 #include "net/http/http_request_info.h"
20 #include "net/http/http_response_headers.h"
21 #include "net/http/http_util.h"
22 #include "net/socket/client_socket_handle.h"
23 #include "net/socket/ssl_client_socket.h"
25 namespace net {
27 namespace {
29 enum HttpHeaderParserEvent {
30 HEADER_PARSER_INVOKED = 0,
31 HEADER_HTTP_09_RESPONSE = 1,
32 HEADER_ALLOWED_TRUNCATED_HEADERS = 2,
33 HEADER_SKIPPED_WS_PREFIX = 3,
34 HEADER_SKIPPED_NON_WS_PREFIX = 4,
35 NUM_HEADER_EVENTS
38 void RecordHeaderParserEvent(HttpHeaderParserEvent header_event) {
39 UMA_HISTOGRAM_ENUMERATION("Net.HttpHeaderParserEvent", header_event,
40 NUM_HEADER_EVENTS);
43 const uint64 kMaxMergedHeaderAndBodySize = 1400;
44 const size_t kRequestBodyBufferSize = 1 << 14; // 16KB
46 std::string GetResponseHeaderLines(const HttpResponseHeaders& headers) {
47 std::string raw_headers = headers.raw_headers();
48 const char* null_separated_headers = raw_headers.c_str();
49 const char* header_line = null_separated_headers;
50 std::string cr_separated_headers;
51 while (header_line[0] != 0) {
52 cr_separated_headers += header_line;
53 cr_separated_headers += "\n";
54 header_line += strlen(header_line) + 1;
56 return cr_separated_headers;
59 // Return true if |headers| contain multiple |field_name| fields with different
60 // values.
61 bool HeadersContainMultipleCopiesOfField(const HttpResponseHeaders& headers,
62 const std::string& field_name) {
63 void* it = NULL;
64 std::string field_value;
65 if (!headers.EnumerateHeader(&it, field_name, &field_value))
66 return false;
67 // There's at least one |field_name| header. Check if there are any more
68 // such headers, and if so, return true if they have different values.
69 std::string field_value2;
70 while (headers.EnumerateHeader(&it, field_name, &field_value2)) {
71 if (field_value != field_value2)
72 return true;
74 return false;
77 scoped_ptr<base::Value> NetLogSendRequestBodyCallback(
78 uint64 length,
79 bool is_chunked,
80 bool did_merge,
81 NetLogCaptureMode /* capture_mode */) {
82 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
83 dict->SetInteger("length", static_cast<int>(length));
84 dict->SetBoolean("is_chunked", is_chunked);
85 dict->SetBoolean("did_merge", did_merge);
86 return dict.Pass();
89 // Returns true if |error_code| is an error for which we give the server a
90 // chance to send a body containing error information, if the error was received
91 // while trying to upload a request body.
92 bool ShouldTryReadingOnUploadError(int error_code) {
93 return (error_code == ERR_CONNECTION_RESET);
96 } // namespace
98 // Similar to DrainableIOBuffer(), but this version comes with its own
99 // storage. The motivation is to avoid repeated allocations of
100 // DrainableIOBuffer.
102 // Example:
104 // scoped_refptr<SeekableIOBuffer> buf = new SeekableIOBuffer(1024);
105 // // capacity() == 1024. size() == BytesRemaining() == BytesConsumed() == 0.
106 // // data() points to the beginning of the buffer.
108 // // Read() takes an IOBuffer.
109 // int bytes_read = some_reader->Read(buf, buf->capacity());
110 // buf->DidAppend(bytes_read);
111 // // size() == BytesRemaining() == bytes_read. data() is unaffected.
113 // while (buf->BytesRemaining() > 0) {
114 // // Write() takes an IOBuffer. If it takes const char*, we could
115 /// // simply use the regular IOBuffer like buf->data() + offset.
116 // int bytes_written = Write(buf, buf->BytesRemaining());
117 // buf->DidConsume(bytes_written);
118 // }
119 // // BytesRemaining() == 0. BytesConsumed() == size().
120 // // data() points to the end of the consumed bytes (exclusive).
122 // // If you want to reuse the buffer, be sure to clear the buffer.
123 // buf->Clear();
124 // // size() == BytesRemaining() == BytesConsumed() == 0.
125 // // data() points to the beginning of the buffer.
127 class HttpStreamParser::SeekableIOBuffer : public IOBuffer {
128 public:
129 explicit SeekableIOBuffer(int capacity)
130 : IOBuffer(capacity),
131 real_data_(data_),
132 capacity_(capacity),
133 size_(0),
134 used_(0) {
137 // DidConsume() changes the |data_| pointer so that |data_| always points
138 // to the first unconsumed byte.
139 void DidConsume(int bytes) {
140 SetOffset(used_ + bytes);
143 // Returns the number of unconsumed bytes.
144 int BytesRemaining() const {
145 return size_ - used_;
148 // Seeks to an arbitrary point in the buffer. The notion of bytes consumed
149 // and remaining are updated appropriately.
150 void SetOffset(int bytes) {
151 DCHECK_GE(bytes, 0);
152 DCHECK_LE(bytes, size_);
153 used_ = bytes;
154 data_ = real_data_ + used_;
157 // Called after data is added to the buffer. Adds |bytes| added to
158 // |size_|. data() is unaffected.
159 void DidAppend(int bytes) {
160 DCHECK_GE(bytes, 0);
161 DCHECK_GE(size_ + bytes, 0);
162 DCHECK_LE(size_ + bytes, capacity_);
163 size_ += bytes;
166 // Changes the logical size to 0, and the offset to 0.
167 void Clear() {
168 size_ = 0;
169 SetOffset(0);
172 // Returns the logical size of the buffer (i.e the number of bytes of data
173 // in the buffer).
174 int size() const { return size_; }
176 // Returns the capacity of the buffer. The capacity is the size used when
177 // the object is created.
178 int capacity() const { return capacity_; };
180 private:
181 ~SeekableIOBuffer() override {
182 // data_ will be deleted in IOBuffer::~IOBuffer().
183 data_ = real_data_;
186 char* real_data_;
187 const int capacity_;
188 int size_;
189 int used_;
192 // 2 CRLFs + max of 8 hex chars.
193 const size_t HttpStreamParser::kChunkHeaderFooterSize = 12;
195 HttpStreamParser::HttpStreamParser(ClientSocketHandle* connection,
196 const HttpRequestInfo* request,
197 GrowableIOBuffer* read_buffer,
198 const BoundNetLog& net_log)
199 : io_state_(STATE_NONE),
200 request_(request),
201 request_headers_(NULL),
202 request_headers_length_(0),
203 read_buf_(read_buffer),
204 read_buf_unused_offset_(0),
205 response_header_start_offset_(-1),
206 received_bytes_(0),
207 response_body_length_(-1),
208 response_body_read_(0),
209 user_read_buf_(NULL),
210 user_read_buf_len_(0),
211 connection_(connection),
212 net_log_(net_log),
213 sent_last_chunk_(false),
214 upload_error_(OK),
215 weak_ptr_factory_(this) {
216 io_callback_ = base::Bind(&HttpStreamParser::OnIOComplete,
217 weak_ptr_factory_.GetWeakPtr());
220 HttpStreamParser::~HttpStreamParser() {
223 int HttpStreamParser::SendRequest(const std::string& request_line,
224 const HttpRequestHeaders& headers,
225 HttpResponseInfo* response,
226 const CompletionCallback& callback) {
227 DCHECK_EQ(STATE_NONE, io_state_);
228 DCHECK(callback_.is_null());
229 DCHECK(!callback.is_null());
230 DCHECK(response);
232 net_log_.AddEvent(
233 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
234 base::Bind(&HttpRequestHeaders::NetLogCallback,
235 base::Unretained(&headers),
236 &request_line));
238 DVLOG(1) << __FUNCTION__ << "()"
239 << " request_line = \"" << request_line << "\""
240 << " headers = \"" << headers.ToString() << "\"";
241 response_ = response;
243 // Put the peer's IP address and port into the response.
244 IPEndPoint ip_endpoint;
245 int result = connection_->socket()->GetPeerAddress(&ip_endpoint);
246 if (result != OK)
247 return result;
248 response_->socket_address = HostPortPair::FromIPEndPoint(ip_endpoint);
250 std::string request = request_line + headers.ToString();
251 request_headers_length_ = request.size();
253 if (request_->upload_data_stream != NULL) {
254 request_body_send_buf_ = new SeekableIOBuffer(kRequestBodyBufferSize);
255 if (request_->upload_data_stream->is_chunked()) {
256 // Read buffer is adjusted to guarantee that |request_body_send_buf_| is
257 // large enough to hold the encoded chunk.
258 request_body_read_buf_ =
259 new SeekableIOBuffer(kRequestBodyBufferSize - kChunkHeaderFooterSize);
260 } else {
261 // No need to encode request body, just send the raw data.
262 request_body_read_buf_ = request_body_send_buf_;
266 io_state_ = STATE_SEND_HEADERS;
268 // If we have a small request body, then we'll merge with the headers into a
269 // single write.
270 bool did_merge = false;
271 if (ShouldMergeRequestHeadersAndBody(request, request_->upload_data_stream)) {
272 int merged_size = static_cast<int>(
273 request_headers_length_ + request_->upload_data_stream->size());
274 scoped_refptr<IOBuffer> merged_request_headers_and_body(
275 new IOBuffer(merged_size));
276 // We'll repurpose |request_headers_| to store the merged headers and
277 // body.
278 request_headers_ = new DrainableIOBuffer(
279 merged_request_headers_and_body.get(), merged_size);
281 memcpy(request_headers_->data(), request.data(), request_headers_length_);
282 request_headers_->DidConsume(request_headers_length_);
284 uint64 todo = request_->upload_data_stream->size();
285 while (todo) {
286 int consumed = request_->upload_data_stream->Read(
287 request_headers_.get(), static_cast<int>(todo), CompletionCallback());
288 DCHECK_GT(consumed, 0); // Read() won't fail if not chunked.
289 request_headers_->DidConsume(consumed);
290 todo -= consumed;
292 DCHECK(request_->upload_data_stream->IsEOF());
293 // Reset the offset, so the buffer can be read from the beginning.
294 request_headers_->SetOffset(0);
295 did_merge = true;
297 net_log_.AddEvent(
298 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_BODY,
299 base::Bind(&NetLogSendRequestBodyCallback,
300 request_->upload_data_stream->size(),
301 false, /* not chunked */
302 true /* merged */));
305 if (!did_merge) {
306 // If we didn't merge the body with the headers, then |request_headers_|
307 // contains just the HTTP headers.
308 scoped_refptr<StringIOBuffer> headers_io_buf(new StringIOBuffer(request));
309 request_headers_ =
310 new DrainableIOBuffer(headers_io_buf.get(), headers_io_buf->size());
313 result = DoLoop(OK);
314 if (result == ERR_IO_PENDING)
315 callback_ = callback;
317 return result > 0 ? OK : result;
320 int HttpStreamParser::ReadResponseHeaders(const CompletionCallback& callback) {
321 DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
322 DCHECK(callback_.is_null());
323 DCHECK(!callback.is_null());
324 DCHECK_EQ(0, read_buf_unused_offset_);
326 // This function can be called with io_state_ == STATE_DONE if the
327 // connection is closed after seeing just a 1xx response code.
328 if (io_state_ == STATE_DONE)
329 return ERR_CONNECTION_CLOSED;
331 int result = OK;
332 io_state_ = STATE_READ_HEADERS;
334 if (read_buf_->offset() > 0) {
335 // Simulate the state where the data was just read from the socket.
336 result = read_buf_->offset();
337 read_buf_->set_offset(0);
339 if (result > 0)
340 io_state_ = STATE_READ_HEADERS_COMPLETE;
342 result = DoLoop(result);
343 if (result == ERR_IO_PENDING)
344 callback_ = callback;
346 return result > 0 ? OK : result;
349 void HttpStreamParser::Close(bool not_reusable) {
350 if (not_reusable && connection_->socket())
351 connection_->socket()->Disconnect();
352 connection_->Reset();
355 int HttpStreamParser::ReadResponseBody(IOBuffer* buf, int buf_len,
356 const CompletionCallback& callback) {
357 DCHECK(io_state_ == STATE_NONE || io_state_ == STATE_DONE);
358 DCHECK(callback_.is_null());
359 DCHECK(!callback.is_null());
360 DCHECK_LE(buf_len, kMaxBufSize);
362 if (io_state_ == STATE_DONE)
363 return OK;
365 user_read_buf_ = buf;
366 user_read_buf_len_ = buf_len;
367 io_state_ = STATE_READ_BODY;
369 int result = DoLoop(OK);
370 if (result == ERR_IO_PENDING)
371 callback_ = callback;
373 return result;
376 void HttpStreamParser::OnIOComplete(int result) {
377 result = DoLoop(result);
379 // The client callback can do anything, including destroying this class,
380 // so any pending callback must be issued after everything else is done.
381 if (result != ERR_IO_PENDING && !callback_.is_null()) {
382 CompletionCallback c = callback_;
383 callback_.Reset();
384 c.Run(result);
388 int HttpStreamParser::DoLoop(int result) {
389 do {
390 DCHECK_NE(ERR_IO_PENDING, result);
391 DCHECK_NE(STATE_DONE, io_state_);
392 DCHECK_NE(STATE_NONE, io_state_);
393 State state = io_state_;
394 io_state_ = STATE_NONE;
395 switch (state) {
396 case STATE_SEND_HEADERS:
397 DCHECK_EQ(OK, result);
398 result = DoSendHeaders();
399 break;
400 case STATE_SEND_HEADERS_COMPLETE:
401 result = DoSendHeadersComplete(result);
402 break;
403 case STATE_SEND_BODY:
404 DCHECK_EQ(OK, result);
405 result = DoSendBody();
406 break;
407 case STATE_SEND_BODY_COMPLETE:
408 result = DoSendBodyComplete(result);
409 break;
410 case STATE_SEND_REQUEST_READ_BODY_COMPLETE:
411 result = DoSendRequestReadBodyComplete(result);
412 break;
413 case STATE_READ_HEADERS:
414 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_PARSER_READ_HEADERS);
415 DCHECK_GE(result, 0);
416 result = DoReadHeaders();
417 break;
418 case STATE_READ_HEADERS_COMPLETE:
419 result = DoReadHeadersComplete(result);
420 net_log_.EndEventWithNetErrorCode(
421 NetLog::TYPE_HTTP_STREAM_PARSER_READ_HEADERS, result);
422 break;
423 case STATE_READ_BODY:
424 DCHECK_GE(result, 0);
425 result = DoReadBody();
426 break;
427 case STATE_READ_BODY_COMPLETE:
428 result = DoReadBodyComplete(result);
429 break;
430 default:
431 NOTREACHED();
432 break;
434 } while (result != ERR_IO_PENDING &&
435 (io_state_ != STATE_DONE && io_state_ != STATE_NONE));
437 return result;
440 int HttpStreamParser::DoSendHeaders() {
441 // TODO(mmenke): Remove ScopedTracker below once crbug.com/424359 is fixed.
442 tracked_objects::ScopedTracker tracking_profile(
443 FROM_HERE_WITH_EXPLICIT_FUNCTION(
444 "424359 HttpStreamParser::DoSendHeaders"));
446 int bytes_remaining = request_headers_->BytesRemaining();
447 DCHECK_GT(bytes_remaining, 0);
449 // Record our best estimate of the 'request time' as the time when we send
450 // out the first bytes of the request headers.
451 if (bytes_remaining == request_headers_->size())
452 response_->request_time = base::Time::Now();
454 io_state_ = STATE_SEND_HEADERS_COMPLETE;
455 return connection_->socket()
456 ->Write(request_headers_.get(), bytes_remaining, io_callback_);
459 int HttpStreamParser::DoSendHeadersComplete(int result) {
460 if (result < 0) {
461 // In the unlikely case that the headers and body were merged, all the
462 // the headers were sent, but not all of the body way, and |result| is
463 // an error that this should try reading after, stash the error for now and
464 // act like the request was successfully sent.
465 if (request_headers_->BytesConsumed() >= request_headers_length_ &&
466 ShouldTryReadingOnUploadError(result)) {
467 upload_error_ = result;
468 return OK;
470 return result;
473 request_headers_->DidConsume(result);
474 if (request_headers_->BytesRemaining() > 0) {
475 io_state_ = STATE_SEND_HEADERS;
476 return OK;
479 if (request_->upload_data_stream != NULL &&
480 (request_->upload_data_stream->is_chunked() ||
481 // !IsEOF() indicates that the body wasn't merged.
482 (request_->upload_data_stream->size() > 0 &&
483 !request_->upload_data_stream->IsEOF()))) {
484 net_log_.AddEvent(
485 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_BODY,
486 base::Bind(&NetLogSendRequestBodyCallback,
487 request_->upload_data_stream->size(),
488 request_->upload_data_stream->is_chunked(),
489 false /* not merged */));
490 io_state_ = STATE_SEND_BODY;
491 return OK;
494 // Finished sending the request.
495 return OK;
498 int HttpStreamParser::DoSendBody() {
499 if (request_body_send_buf_->BytesRemaining() > 0) {
500 io_state_ = STATE_SEND_BODY_COMPLETE;
501 return connection_->socket()
502 ->Write(request_body_send_buf_.get(),
503 request_body_send_buf_->BytesRemaining(),
504 io_callback_);
507 if (request_->upload_data_stream->is_chunked() && sent_last_chunk_) {
508 // Finished sending the request.
509 return OK;
512 request_body_read_buf_->Clear();
513 io_state_ = STATE_SEND_REQUEST_READ_BODY_COMPLETE;
514 return request_->upload_data_stream->Read(request_body_read_buf_.get(),
515 request_body_read_buf_->capacity(),
516 io_callback_);
519 int HttpStreamParser::DoSendBodyComplete(int result) {
520 if (result < 0) {
521 // If |result| is an error that this should try reading after, stash the
522 // error for now and act like the request was successfully sent.
523 if (ShouldTryReadingOnUploadError(result)) {
524 upload_error_ = result;
525 return OK;
527 return result;
530 request_body_send_buf_->DidConsume(result);
532 io_state_ = STATE_SEND_BODY;
533 return OK;
536 int HttpStreamParser::DoSendRequestReadBodyComplete(int result) {
537 // |result| is the result of read from the request body from the last call to
538 // DoSendBody().
539 DCHECK_GE(result, 0); // There won't be errors.
541 // Chunked data needs to be encoded.
542 if (request_->upload_data_stream->is_chunked()) {
543 if (result == 0) { // Reached the end.
544 DCHECK(request_->upload_data_stream->IsEOF());
545 sent_last_chunk_ = true;
547 // Encode the buffer as 1 chunk.
548 const base::StringPiece payload(request_body_read_buf_->data(), result);
549 request_body_send_buf_->Clear();
550 result = EncodeChunk(payload,
551 request_body_send_buf_->data(),
552 request_body_send_buf_->capacity());
555 if (result == 0) { // Reached the end.
556 // Reaching EOF means we can finish sending request body unless the data is
557 // chunked. (i.e. No need to send the terminal chunk.)
558 DCHECK(request_->upload_data_stream->IsEOF());
559 DCHECK(!request_->upload_data_stream->is_chunked());
560 // Finished sending the request.
561 } else if (result > 0) {
562 request_body_send_buf_->DidAppend(result);
563 result = 0;
564 io_state_ = STATE_SEND_BODY;
566 return result;
569 int HttpStreamParser::DoReadHeaders() {
570 io_state_ = STATE_READ_HEADERS_COMPLETE;
572 // Grow the read buffer if necessary.
573 if (read_buf_->RemainingCapacity() == 0)
574 read_buf_->SetCapacity(read_buf_->capacity() + kHeaderBufInitialSize);
576 // http://crbug.com/16371: We're seeing |user_buf_->data()| return NULL.
577 // See if the user is passing in an IOBuffer with a NULL |data_|.
578 CHECK(read_buf_->data());
580 return connection_->socket()
581 ->Read(read_buf_.get(), read_buf_->RemainingCapacity(), io_callback_);
584 int HttpStreamParser::DoReadHeadersComplete(int result) {
585 result = HandleReadHeaderResult(result);
587 // TODO(mmenke): The code below is ugly and hacky. A much better and more
588 // flexible long term solution would be to separate out the read and write
589 // loops, though this would involve significant changes, both here and
590 // elsewhere (WebSockets, for instance).
592 // If still reading the headers, or there was no error uploading the request
593 // body, just return the result.
594 if (io_state_ == STATE_READ_HEADERS || upload_error_ == OK)
595 return result;
597 // If the result is ERR_IO_PENDING, |io_state_| should be STATE_READ_HEADERS.
598 DCHECK_NE(ERR_IO_PENDING, result);
600 // On errors, use the original error received when sending the request.
601 // The main cases where these are different is when there's a header-related
602 // error code, or when there's an ERR_CONNECTION_CLOSED, which can result in
603 // special handling of partial responses and HTTP/0.9 responses.
604 if (result < 0) {
605 // Nothing else to do. In the HTTP/0.9 or only partial headers received
606 // cases, can normally go to other states after an error reading headers.
607 io_state_ = STATE_DONE;
608 // Don't let caller see the headers.
609 response_->headers = NULL;
610 return upload_error_;
613 // Skip over 1xx responses as usual, and allow 4xx/5xx error responses to
614 // override the error received while uploading the body.
615 int response_code_class = response_->headers->response_code() / 100;
616 if (response_code_class == 1 || response_code_class == 4 ||
617 response_code_class == 5) {
618 return result;
621 // All other status codes are not allowed after an error during upload, to
622 // make sure the consumer has some indication there was an error.
624 // Nothing else to do.
625 io_state_ = STATE_DONE;
626 // Don't let caller see the headers.
627 response_->headers = NULL;
628 return upload_error_;
631 int HttpStreamParser::DoReadBody() {
632 io_state_ = STATE_READ_BODY_COMPLETE;
634 // There may be some data left over from reading the response headers.
635 if (read_buf_->offset()) {
636 int available = read_buf_->offset() - read_buf_unused_offset_;
637 if (available) {
638 CHECK_GT(available, 0);
639 int bytes_from_buffer = std::min(available, user_read_buf_len_);
640 memcpy(user_read_buf_->data(),
641 read_buf_->StartOfBuffer() + read_buf_unused_offset_,
642 bytes_from_buffer);
643 read_buf_unused_offset_ += bytes_from_buffer;
644 if (bytes_from_buffer == available) {
645 read_buf_->SetCapacity(0);
646 read_buf_unused_offset_ = 0;
648 return bytes_from_buffer;
649 } else {
650 read_buf_->SetCapacity(0);
651 read_buf_unused_offset_ = 0;
655 // Check to see if we're done reading.
656 if (IsResponseBodyComplete())
657 return 0;
659 DCHECK_EQ(0, read_buf_->offset());
660 return connection_->socket()
661 ->Read(user_read_buf_.get(), user_read_buf_len_, io_callback_);
664 int HttpStreamParser::DoReadBodyComplete(int result) {
665 // When the connection is closed, there are numerous ways to interpret it.
667 // - If a Content-Length header is present and the body contains exactly that
668 // number of bytes at connection close, the response is successful.
670 // - If a Content-Length header is present and the body contains fewer bytes
671 // than promised by the header at connection close, it may indicate that
672 // the connection was closed prematurely, or it may indicate that the
673 // server sent an invalid Content-Length header. Unfortunately, the invalid
674 // Content-Length header case does occur in practice and other browsers are
675 // tolerant of it. We choose to treat it as an error for now, but the
676 // download system treats it as a non-error, and URLRequestHttpJob also
677 // treats it as OK if the Content-Length is the post-decoded body content
678 // length.
680 // - If chunked encoding is used and the terminating chunk has been processed
681 // when the connection is closed, the response is successful.
683 // - If chunked encoding is used and the terminating chunk has not been
684 // processed when the connection is closed, it may indicate that the
685 // connection was closed prematurely or it may indicate that the server
686 // sent an invalid chunked encoding. We choose to treat it as
687 // an invalid chunked encoding.
689 // - If a Content-Length is not present and chunked encoding is not used,
690 // connection close is the only way to signal that the response is
691 // complete. Unfortunately, this also means that there is no way to detect
692 // early close of a connection. No error is returned.
693 if (result == 0 && !IsResponseBodyComplete() && CanFindEndOfResponse()) {
694 if (chunked_decoder_.get())
695 result = ERR_INCOMPLETE_CHUNKED_ENCODING;
696 else
697 result = ERR_CONTENT_LENGTH_MISMATCH;
700 if (result > 0)
701 received_bytes_ += result;
703 // Filter incoming data if appropriate. FilterBuf may return an error.
704 if (result > 0 && chunked_decoder_.get()) {
705 result = chunked_decoder_->FilterBuf(user_read_buf_->data(), result);
706 if (result == 0 && !chunked_decoder_->reached_eof()) {
707 // Don't signal completion of the Read call yet or else it'll look like
708 // we received end-of-file. Wait for more data.
709 io_state_ = STATE_READ_BODY;
710 return OK;
714 if (result > 0)
715 response_body_read_ += result;
717 if (result <= 0 || IsResponseBodyComplete()) {
718 io_state_ = STATE_DONE;
720 // Save the overflow data, which can be in two places. There may be
721 // some left over in |user_read_buf_|, plus there may be more
722 // in |read_buf_|. But the part left over in |user_read_buf_| must have
723 // come from the |read_buf_|, so there's room to put it back at the
724 // start first.
725 int additional_save_amount = read_buf_->offset() - read_buf_unused_offset_;
726 int save_amount = 0;
727 if (chunked_decoder_.get()) {
728 save_amount = chunked_decoder_->bytes_after_eof();
729 } else if (response_body_length_ >= 0) {
730 int64 extra_data_read = response_body_read_ - response_body_length_;
731 if (extra_data_read > 0) {
732 save_amount = static_cast<int>(extra_data_read);
733 if (result > 0)
734 result -= save_amount;
738 CHECK_LE(save_amount + additional_save_amount, kMaxBufSize);
739 if (read_buf_->capacity() < save_amount + additional_save_amount) {
740 read_buf_->SetCapacity(save_amount + additional_save_amount);
743 if (save_amount) {
744 received_bytes_ -= save_amount;
745 memcpy(read_buf_->StartOfBuffer(), user_read_buf_->data() + result,
746 save_amount);
748 read_buf_->set_offset(save_amount);
749 if (additional_save_amount) {
750 memmove(read_buf_->data(),
751 read_buf_->StartOfBuffer() + read_buf_unused_offset_,
752 additional_save_amount);
753 read_buf_->set_offset(save_amount + additional_save_amount);
755 read_buf_unused_offset_ = 0;
756 } else {
757 // Now waiting for more of the body to be read.
758 user_read_buf_ = NULL;
759 user_read_buf_len_ = 0;
762 return result;
765 int HttpStreamParser::HandleReadHeaderResult(int result) {
766 DCHECK_EQ(0, read_buf_unused_offset_);
768 if (result == 0)
769 result = ERR_CONNECTION_CLOSED;
771 if (result < 0 && result != ERR_CONNECTION_CLOSED) {
772 io_state_ = STATE_DONE;
773 return result;
775 // If we've used the connection before, then we know it is not a HTTP/0.9
776 // response and return ERR_CONNECTION_CLOSED.
777 if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 &&
778 connection_->is_reused()) {
779 io_state_ = STATE_DONE;
780 return result;
783 // Record our best estimate of the 'response time' as the time when we read
784 // the first bytes of the response headers.
785 if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED)
786 response_->response_time = base::Time::Now();
788 if (result == ERR_CONNECTION_CLOSED) {
789 // The connection closed before we detected the end of the headers.
790 if (read_buf_->offset() == 0) {
791 // The connection was closed before any data was sent. Likely an error
792 // rather than empty HTTP/0.9 response.
793 io_state_ = STATE_DONE;
794 return ERR_EMPTY_RESPONSE;
795 } else if (request_->url.SchemeIsCryptographic()) {
796 // The connection was closed in the middle of the headers. For HTTPS we
797 // don't parse partial headers. Return a different error code so that we
798 // know that we shouldn't attempt to retry the request.
799 io_state_ = STATE_DONE;
800 return ERR_RESPONSE_HEADERS_TRUNCATED;
802 // Parse things as well as we can and let the caller decide what to do.
803 int end_offset;
804 if (response_header_start_offset_ >= 0) {
805 // The response looks to be a truncated set of HTTP headers.
806 io_state_ = STATE_READ_BODY_COMPLETE;
807 end_offset = read_buf_->offset();
808 RecordHeaderParserEvent(HEADER_ALLOWED_TRUNCATED_HEADERS);
809 } else {
810 // The response is apparently using HTTP/0.9. Treat the entire response
811 // the body.
812 end_offset = 0;
814 int rv = ParseResponseHeaders(end_offset);
815 if (rv < 0)
816 return rv;
817 return result;
820 read_buf_->set_offset(read_buf_->offset() + result);
821 DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
822 DCHECK_GE(result, 0);
824 int end_of_header_offset = FindAndParseResponseHeaders();
826 // Note: -1 is special, it indicates we haven't found the end of headers.
827 // Anything less than -1 is a net::Error, so we bail out.
828 if (end_of_header_offset < -1)
829 return end_of_header_offset;
831 if (end_of_header_offset == -1) {
832 io_state_ = STATE_READ_HEADERS;
833 // Prevent growing the headers buffer indefinitely.
834 if (read_buf_->offset() >= kMaxHeaderBufSize) {
835 io_state_ = STATE_DONE;
836 return ERR_RESPONSE_HEADERS_TOO_BIG;
838 } else {
839 CalculateResponseBodySize();
840 // If the body is zero length, the caller may not call ReadResponseBody,
841 // which is where any extra data is copied to read_buf_, so we move the
842 // data here.
843 if (response_body_length_ == 0) {
844 int extra_bytes = read_buf_->offset() - end_of_header_offset;
845 if (extra_bytes) {
846 CHECK_GT(extra_bytes, 0);
847 memmove(read_buf_->StartOfBuffer(),
848 read_buf_->StartOfBuffer() + end_of_header_offset,
849 extra_bytes);
851 read_buf_->SetCapacity(extra_bytes);
852 if (response_->headers->response_code() / 100 == 1) {
853 // After processing a 1xx response, the caller will ask for the next
854 // header, so reset state to support that. We don't completely ignore a
855 // 1xx response because it cannot be returned in reply to a CONNECT
856 // request so we return OK here, which lets the caller inspect the
857 // response and reject it in the event that we're setting up a CONNECT
858 // tunnel.
859 response_header_start_offset_ = -1;
860 response_body_length_ = -1;
861 // Now waiting for the second set of headers to be read.
862 } else {
863 io_state_ = STATE_DONE;
865 return OK;
868 // Note where the headers stop.
869 read_buf_unused_offset_ = end_of_header_offset;
870 // Now waiting for the body to be read.
872 return result;
875 int HttpStreamParser::FindAndParseResponseHeaders() {
876 int end_offset = -1;
877 DCHECK_EQ(0, read_buf_unused_offset_);
879 // Look for the start of the status line, if it hasn't been found yet.
880 if (response_header_start_offset_ < 0) {
881 response_header_start_offset_ = HttpUtil::LocateStartOfStatusLine(
882 read_buf_->StartOfBuffer(), read_buf_->offset());
885 if (response_header_start_offset_ >= 0) {
886 end_offset = HttpUtil::LocateEndOfHeaders(read_buf_->StartOfBuffer(),
887 read_buf_->offset(),
888 response_header_start_offset_);
889 } else if (read_buf_->offset() >= 8) {
890 // Enough data to decide that this is an HTTP/0.9 response.
891 // 8 bytes = (4 bytes of junk) + "http".length()
892 end_offset = 0;
895 if (end_offset == -1)
896 return -1;
898 int rv = ParseResponseHeaders(end_offset);
899 if (rv < 0)
900 return rv;
901 return end_offset;
904 int HttpStreamParser::ParseResponseHeaders(int end_offset) {
905 scoped_refptr<HttpResponseHeaders> headers;
906 DCHECK_EQ(0, read_buf_unused_offset_);
908 RecordHeaderParserEvent(HEADER_PARSER_INVOKED);
910 if (response_header_start_offset_ > 0) {
911 bool has_non_whitespace_in_prefix = false;
912 for (int i = 0; i < response_header_start_offset_; ++i) {
913 if (!strchr(" \t\r\n", read_buf_->StartOfBuffer()[i])) {
914 has_non_whitespace_in_prefix = true;
915 break;
918 if (has_non_whitespace_in_prefix) {
919 RecordHeaderParserEvent(HEADER_SKIPPED_NON_WS_PREFIX);
920 } else {
921 RecordHeaderParserEvent(HEADER_SKIPPED_WS_PREFIX);
925 if (response_header_start_offset_ >= 0) {
926 received_bytes_ += end_offset;
927 headers = new HttpResponseHeaders(HttpUtil::AssembleRawHeaders(
928 read_buf_->StartOfBuffer(), end_offset));
929 } else {
930 // Enough data was read -- there is no status line.
931 headers = new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
932 RecordHeaderParserEvent(HEADER_HTTP_09_RESPONSE);
935 // Check for multiple Content-Length headers with no Transfer-Encoding header.
936 // If they exist, and have distinct values, it's a potential response
937 // smuggling attack.
938 if (!headers->HasHeader("Transfer-Encoding")) {
939 if (HeadersContainMultipleCopiesOfField(*headers.get(), "Content-Length"))
940 return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH;
943 // Check for multiple Content-Disposition or Location headers. If they exist,
944 // it's also a potential response smuggling attack.
945 if (HeadersContainMultipleCopiesOfField(*headers.get(),
946 "Content-Disposition"))
947 return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION;
948 if (HeadersContainMultipleCopiesOfField(*headers.get(), "Location"))
949 return ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION;
951 response_->headers = headers;
952 response_->connection_info = HttpResponseInfo::CONNECTION_INFO_HTTP1;
953 response_->vary_data.Init(*request_, *response_->headers.get());
954 DVLOG(1) << __FUNCTION__ << "()"
955 << " content_length = \"" << response_->headers->GetContentLength()
956 << "\n\""
957 << " headers = \""
958 << GetResponseHeaderLines(*response_->headers.get()) << "\"";
959 return OK;
962 void HttpStreamParser::CalculateResponseBodySize() {
963 // Figure how to determine EOF:
965 // For certain responses, we know the content length is always 0. From
966 // RFC 7230 Section 3.3 Message Body:
968 // The presence of a message body in a response depends on both the
969 // request method to which it is responding and the response status code
970 // (Section 3.1.2). Responses to the HEAD request method (Section 4.3.2
971 // of [RFC7231]) never include a message body because the associated
972 // response header fields (e.g., Transfer-Encoding, Content-Length,
973 // etc.), if present, indicate only what their values would have been if
974 // the request method had been GET (Section 4.3.1 of [RFC7231]). 2xx
975 // (Successful) responses to a CONNECT request method (Section 4.3.6 of
976 // [RFC7231]) switch to tunnel mode instead of having a message body.
977 // All 1xx (Informational), 204 (No Content), and 304 (Not Modified)
978 // responses do not include a message body. All other responses do
979 // include a message body, although the body might be of zero length.
981 // From RFC 7231 Section 6.3.6 205 Reset Content:
983 // Since the 205 status code implies that no additional content will be
984 // provided, a server MUST NOT generate a payload in a 205 response.
985 if (response_->headers->response_code() / 100 == 1) {
986 response_body_length_ = 0;
987 } else {
988 switch (response_->headers->response_code()) {
989 case 204: // No Content
990 case 205: // Reset Content
991 case 304: // Not Modified
992 response_body_length_ = 0;
993 break;
996 if (request_->method == "HEAD")
997 response_body_length_ = 0;
999 if (response_body_length_ == -1) {
1000 // "Transfer-Encoding: chunked" trumps "Content-Length: N"
1001 if (response_->headers->IsChunkEncoded()) {
1002 chunked_decoder_.reset(new HttpChunkedDecoder());
1003 } else {
1004 response_body_length_ = response_->headers->GetContentLength();
1005 // If response_body_length_ is still -1, then we have to wait
1006 // for the server to close the connection.
1011 UploadProgress HttpStreamParser::GetUploadProgress() const {
1012 if (!request_->upload_data_stream)
1013 return UploadProgress();
1015 return UploadProgress(request_->upload_data_stream->position(),
1016 request_->upload_data_stream->size());
1019 bool HttpStreamParser::IsResponseBodyComplete() const {
1020 if (chunked_decoder_.get())
1021 return chunked_decoder_->reached_eof();
1022 if (response_body_length_ != -1)
1023 return response_body_read_ >= response_body_length_;
1025 return false; // Must read to EOF.
1028 bool HttpStreamParser::CanFindEndOfResponse() const {
1029 return chunked_decoder_.get() || response_body_length_ >= 0;
1032 bool HttpStreamParser::IsMoreDataBuffered() const {
1033 return read_buf_->offset() > read_buf_unused_offset_;
1036 bool HttpStreamParser::IsConnectionReused() const {
1037 ClientSocketHandle::SocketReuseType reuse_type = connection_->reuse_type();
1038 return connection_->is_reused() ||
1039 reuse_type == ClientSocketHandle::UNUSED_IDLE;
1042 void HttpStreamParser::SetConnectionReused() {
1043 connection_->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
1046 bool HttpStreamParser::IsConnectionReusable() const {
1047 return connection_->socket() && connection_->socket()->IsConnectedAndIdle();
1050 void HttpStreamParser::GetSSLInfo(SSLInfo* ssl_info) {
1051 if (request_->url.SchemeIsCryptographic() && connection_->socket()) {
1052 SSLClientSocket* ssl_socket =
1053 static_cast<SSLClientSocket*>(connection_->socket());
1054 ssl_socket->GetSSLInfo(ssl_info);
1058 void HttpStreamParser::GetSSLCertRequestInfo(
1059 SSLCertRequestInfo* cert_request_info) {
1060 if (request_->url.SchemeIsCryptographic() && connection_->socket()) {
1061 SSLClientSocket* ssl_socket =
1062 static_cast<SSLClientSocket*>(connection_->socket());
1063 ssl_socket->GetSSLCertRequestInfo(cert_request_info);
1067 int HttpStreamParser::EncodeChunk(const base::StringPiece& payload,
1068 char* output,
1069 size_t output_size) {
1070 if (output_size < payload.size() + kChunkHeaderFooterSize)
1071 return ERR_INVALID_ARGUMENT;
1073 char* cursor = output;
1074 // Add the header.
1075 const int num_chars = base::snprintf(output, output_size,
1076 "%X\r\n",
1077 static_cast<int>(payload.size()));
1078 cursor += num_chars;
1079 // Add the payload if any.
1080 if (payload.size() > 0) {
1081 memcpy(cursor, payload.data(), payload.size());
1082 cursor += payload.size();
1084 // Add the trailing CRLF.
1085 memcpy(cursor, "\r\n", 2);
1086 cursor += 2;
1088 return cursor - output;
1091 // static
1092 bool HttpStreamParser::ShouldMergeRequestHeadersAndBody(
1093 const std::string& request_headers,
1094 const UploadDataStream* request_body) {
1095 if (request_body != NULL &&
1096 // IsInMemory() ensures that the request body is not chunked.
1097 request_body->IsInMemory() &&
1098 request_body->size() > 0) {
1099 uint64 merged_size = request_headers.size() + request_body->size();
1100 if (merged_size <= kMaxMergedHeaderAndBodySize)
1101 return true;
1103 return false;
1106 } // namespace net