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"
8 #include "base/compiler_specific.h"
9 #include "base/logging.h"
10 #include "base/profiler/scoped_tracker.h"
11 #include "base/strings/string_util.h"
12 #include "base/values.h"
13 #include "net/base/io_buffer.h"
14 #include "net/base/ip_endpoint.h"
15 #include "net/base/upload_data_stream.h"
16 #include "net/http/http_chunked_decoder.h"
17 #include "net/http/http_request_headers.h"
18 #include "net/http/http_request_info.h"
19 #include "net/http/http_response_headers.h"
20 #include "net/http/http_util.h"
21 #include "net/socket/client_socket_handle.h"
22 #include "net/socket/ssl_client_socket.h"
28 const uint64 kMaxMergedHeaderAndBodySize
= 1400;
29 const size_t kRequestBodyBufferSize
= 1 << 14; // 16KB
31 std::string
GetResponseHeaderLines(const HttpResponseHeaders
& headers
) {
32 std::string raw_headers
= headers
.raw_headers();
33 const char* null_separated_headers
= raw_headers
.c_str();
34 const char* header_line
= null_separated_headers
;
35 std::string cr_separated_headers
;
36 while (header_line
[0] != 0) {
37 cr_separated_headers
+= header_line
;
38 cr_separated_headers
+= "\n";
39 header_line
+= strlen(header_line
) + 1;
41 return cr_separated_headers
;
44 // Return true if |headers| contain multiple |field_name| fields with different
46 bool HeadersContainMultipleCopiesOfField(const HttpResponseHeaders
& headers
,
47 const std::string
& field_name
) {
49 std::string field_value
;
50 if (!headers
.EnumerateHeader(&it
, field_name
, &field_value
))
52 // There's at least one |field_name| header. Check if there are any more
53 // such headers, and if so, return true if they have different values.
54 std::string field_value2
;
55 while (headers
.EnumerateHeader(&it
, field_name
, &field_value2
)) {
56 if (field_value
!= field_value2
)
62 base::Value
* NetLogSendRequestBodyCallback(uint64 length
,
65 NetLog::LogLevel
/* log_level */) {
66 base::DictionaryValue
* dict
= new base::DictionaryValue();
67 dict
->SetInteger("length", static_cast<int>(length
));
68 dict
->SetBoolean("is_chunked", is_chunked
);
69 dict
->SetBoolean("did_merge", did_merge
);
73 // Returns true if |error_code| is an error for which we give the server a
74 // chance to send a body containing error information, if the error was received
75 // while trying to upload a request body.
76 bool ShouldTryReadingOnUploadError(int error_code
) {
77 return (error_code
== ERR_CONNECTION_RESET
);
82 // Similar to DrainableIOBuffer(), but this version comes with its own
83 // storage. The motivation is to avoid repeated allocations of
88 // scoped_refptr<SeekableIOBuffer> buf = new SeekableIOBuffer(1024);
89 // // capacity() == 1024. size() == BytesRemaining() == BytesConsumed() == 0.
90 // // data() points to the beginning of the buffer.
92 // // Read() takes an IOBuffer.
93 // int bytes_read = some_reader->Read(buf, buf->capacity());
94 // buf->DidAppend(bytes_read);
95 // // size() == BytesRemaining() == bytes_read. data() is unaffected.
97 // while (buf->BytesRemaining() > 0) {
98 // // Write() takes an IOBuffer. If it takes const char*, we could
99 /// // simply use the regular IOBuffer like buf->data() + offset.
100 // int bytes_written = Write(buf, buf->BytesRemaining());
101 // buf->DidConsume(bytes_written);
103 // // BytesRemaining() == 0. BytesConsumed() == size().
104 // // data() points to the end of the consumed bytes (exclusive).
106 // // If you want to reuse the buffer, be sure to clear the buffer.
108 // // size() == BytesRemaining() == BytesConsumed() == 0.
109 // // data() points to the beginning of the buffer.
111 class HttpStreamParser::SeekableIOBuffer
: public IOBuffer
{
113 explicit SeekableIOBuffer(int capacity
)
114 : IOBuffer(capacity
),
121 // DidConsume() changes the |data_| pointer so that |data_| always points
122 // to the first unconsumed byte.
123 void DidConsume(int bytes
) {
124 SetOffset(used_
+ bytes
);
127 // Returns the number of unconsumed bytes.
128 int BytesRemaining() const {
129 return size_
- used_
;
132 // Seeks to an arbitrary point in the buffer. The notion of bytes consumed
133 // and remaining are updated appropriately.
134 void SetOffset(int bytes
) {
136 DCHECK_LE(bytes
, size_
);
138 data_
= real_data_
+ used_
;
141 // Called after data is added to the buffer. Adds |bytes| added to
142 // |size_|. data() is unaffected.
143 void DidAppend(int bytes
) {
145 DCHECK_GE(size_
+ bytes
, 0);
146 DCHECK_LE(size_
+ bytes
, capacity_
);
150 // Changes the logical size to 0, and the offset to 0.
156 // Returns the logical size of the buffer (i.e the number of bytes of data
158 int size() const { return size_
; }
160 // Returns the capacity of the buffer. The capacity is the size used when
161 // the object is created.
162 int capacity() const { return capacity_
; };
165 ~SeekableIOBuffer() override
{
166 // data_ will be deleted in IOBuffer::~IOBuffer().
176 // 2 CRLFs + max of 8 hex chars.
177 const size_t HttpStreamParser::kChunkHeaderFooterSize
= 12;
179 HttpStreamParser::HttpStreamParser(ClientSocketHandle
* connection
,
180 const HttpRequestInfo
* request
,
181 GrowableIOBuffer
* read_buffer
,
182 const BoundNetLog
& net_log
)
183 : io_state_(STATE_NONE
),
185 request_headers_(NULL
),
186 request_headers_length_(0),
187 read_buf_(read_buffer
),
188 read_buf_unused_offset_(0),
189 response_header_start_offset_(-1),
191 response_body_length_(-1),
192 response_body_read_(0),
193 user_read_buf_(NULL
),
194 user_read_buf_len_(0),
195 connection_(connection
),
197 sent_last_chunk_(false),
199 weak_ptr_factory_(this) {
200 io_callback_
= base::Bind(&HttpStreamParser::OnIOComplete
,
201 weak_ptr_factory_
.GetWeakPtr());
204 HttpStreamParser::~HttpStreamParser() {
207 int HttpStreamParser::SendRequest(const std::string
& request_line
,
208 const HttpRequestHeaders
& headers
,
209 HttpResponseInfo
* response
,
210 const CompletionCallback
& callback
) {
211 DCHECK_EQ(STATE_NONE
, io_state_
);
212 DCHECK(callback_
.is_null());
213 DCHECK(!callback
.is_null());
217 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS
,
218 base::Bind(&HttpRequestHeaders::NetLogCallback
,
219 base::Unretained(&headers
),
222 DVLOG(1) << __FUNCTION__
<< "()"
223 << " request_line = \"" << request_line
<< "\""
224 << " headers = \"" << headers
.ToString() << "\"";
225 response_
= response
;
227 // Put the peer's IP address and port into the response.
228 IPEndPoint ip_endpoint
;
229 int result
= connection_
->socket()->GetPeerAddress(&ip_endpoint
);
232 response_
->socket_address
= HostPortPair::FromIPEndPoint(ip_endpoint
);
234 std::string request
= request_line
+ headers
.ToString();
235 request_headers_length_
= request
.size();
237 if (request_
->upload_data_stream
!= NULL
) {
238 request_body_send_buf_
= new SeekableIOBuffer(kRequestBodyBufferSize
);
239 if (request_
->upload_data_stream
->is_chunked()) {
240 // Read buffer is adjusted to guarantee that |request_body_send_buf_| is
241 // large enough to hold the encoded chunk.
242 request_body_read_buf_
=
243 new SeekableIOBuffer(kRequestBodyBufferSize
- kChunkHeaderFooterSize
);
245 // No need to encode request body, just send the raw data.
246 request_body_read_buf_
= request_body_send_buf_
;
250 io_state_
= STATE_SEND_HEADERS
;
252 // If we have a small request body, then we'll merge with the headers into a
254 bool did_merge
= false;
255 if (ShouldMergeRequestHeadersAndBody(request
, request_
->upload_data_stream
)) {
256 int merged_size
= static_cast<int>(
257 request_headers_length_
+ request_
->upload_data_stream
->size());
258 scoped_refptr
<IOBuffer
> merged_request_headers_and_body(
259 new IOBuffer(merged_size
));
260 // We'll repurpose |request_headers_| to store the merged headers and
262 request_headers_
= new DrainableIOBuffer(
263 merged_request_headers_and_body
.get(), merged_size
);
265 memcpy(request_headers_
->data(), request
.data(), request_headers_length_
);
266 request_headers_
->DidConsume(request_headers_length_
);
268 uint64 todo
= request_
->upload_data_stream
->size();
270 int consumed
= request_
->upload_data_stream
->Read(
271 request_headers_
.get(), static_cast<int>(todo
), CompletionCallback());
272 DCHECK_GT(consumed
, 0); // Read() won't fail if not chunked.
273 request_headers_
->DidConsume(consumed
);
276 DCHECK(request_
->upload_data_stream
->IsEOF());
277 // Reset the offset, so the buffer can be read from the beginning.
278 request_headers_
->SetOffset(0);
282 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_BODY
,
283 base::Bind(&NetLogSendRequestBodyCallback
,
284 request_
->upload_data_stream
->size(),
285 false, /* not chunked */
290 // If we didn't merge the body with the headers, then |request_headers_|
291 // contains just the HTTP headers.
292 scoped_refptr
<StringIOBuffer
> headers_io_buf(new StringIOBuffer(request
));
294 new DrainableIOBuffer(headers_io_buf
.get(), headers_io_buf
->size());
298 if (result
== ERR_IO_PENDING
)
299 callback_
= callback
;
301 return result
> 0 ? OK
: result
;
304 int HttpStreamParser::ReadResponseHeaders(const CompletionCallback
& callback
) {
305 DCHECK(io_state_
== STATE_NONE
|| io_state_
== STATE_DONE
);
306 DCHECK(callback_
.is_null());
307 DCHECK(!callback
.is_null());
308 DCHECK_EQ(0, read_buf_unused_offset_
);
310 // This function can be called with io_state_ == STATE_DONE if the
311 // connection is closed after seeing just a 1xx response code.
312 if (io_state_
== STATE_DONE
)
313 return ERR_CONNECTION_CLOSED
;
316 io_state_
= STATE_READ_HEADERS
;
318 if (read_buf_
->offset() > 0) {
319 // Simulate the state where the data was just read from the socket.
320 result
= read_buf_
->offset();
321 read_buf_
->set_offset(0);
324 io_state_
= STATE_READ_HEADERS_COMPLETE
;
326 result
= DoLoop(result
);
327 if (result
== ERR_IO_PENDING
)
328 callback_
= callback
;
330 return result
> 0 ? OK
: result
;
333 void HttpStreamParser::Close(bool not_reusable
) {
334 if (not_reusable
&& connection_
->socket())
335 connection_
->socket()->Disconnect();
336 connection_
->Reset();
339 int HttpStreamParser::ReadResponseBody(IOBuffer
* buf
, int buf_len
,
340 const CompletionCallback
& callback
) {
341 DCHECK(io_state_
== STATE_NONE
|| io_state_
== STATE_DONE
);
342 DCHECK(callback_
.is_null());
343 DCHECK(!callback
.is_null());
344 DCHECK_LE(buf_len
, kMaxBufSize
);
346 if (io_state_
== STATE_DONE
)
349 user_read_buf_
= buf
;
350 user_read_buf_len_
= buf_len
;
351 io_state_
= STATE_READ_BODY
;
353 int result
= DoLoop(OK
);
354 if (result
== ERR_IO_PENDING
)
355 callback_
= callback
;
360 void HttpStreamParser::OnIOComplete(int result
) {
361 result
= DoLoop(result
);
363 // The client callback can do anything, including destroying this class,
364 // so any pending callback must be issued after everything else is done.
365 if (result
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
366 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
367 tracked_objects::ScopedTracker
tracking_profile(
368 FROM_HERE_WITH_EXPLICIT_FUNCTION(
369 "424359 HttpStreamParser::OnIOComplete callback"));
371 CompletionCallback c
= callback_
;
377 int HttpStreamParser::DoLoop(int result
) {
378 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
379 tracked_objects::ScopedTracker
tracking_profile(
380 FROM_HERE_WITH_EXPLICIT_FUNCTION("424359 HttpStreamParser::DoLoop"));
383 DCHECK_NE(ERR_IO_PENDING
, result
);
384 DCHECK_NE(STATE_DONE
, io_state_
);
385 DCHECK_NE(STATE_NONE
, io_state_
);
386 State state
= io_state_
;
387 io_state_
= STATE_NONE
;
389 case STATE_SEND_HEADERS
:
390 DCHECK_EQ(OK
, result
);
391 result
= DoSendHeaders();
393 case STATE_SEND_HEADERS_COMPLETE
:
394 result
= DoSendHeadersComplete(result
);
396 case STATE_SEND_BODY
:
397 DCHECK_EQ(OK
, result
);
398 result
= DoSendBody();
400 case STATE_SEND_BODY_COMPLETE
:
401 result
= DoSendBodyComplete(result
);
403 case STATE_SEND_REQUEST_READ_BODY_COMPLETE
:
404 result
= DoSendRequestReadBodyComplete(result
);
406 case STATE_READ_HEADERS
:
407 net_log_
.BeginEvent(NetLog::TYPE_HTTP_STREAM_PARSER_READ_HEADERS
);
408 DCHECK_GE(result
, 0);
409 result
= DoReadHeaders();
411 case STATE_READ_HEADERS_COMPLETE
:
412 result
= DoReadHeadersComplete(result
);
413 net_log_
.EndEventWithNetErrorCode(
414 NetLog::TYPE_HTTP_STREAM_PARSER_READ_HEADERS
, result
);
416 case STATE_READ_BODY
:
417 DCHECK_GE(result
, 0);
418 result
= DoReadBody();
420 case STATE_READ_BODY_COMPLETE
:
421 result
= DoReadBodyComplete(result
);
427 } while (result
!= ERR_IO_PENDING
&&
428 (io_state_
!= STATE_DONE
&& io_state_
!= STATE_NONE
));
433 int HttpStreamParser::DoSendHeaders() {
434 int bytes_remaining
= request_headers_
->BytesRemaining();
435 DCHECK_GT(bytes_remaining
, 0);
437 // Record our best estimate of the 'request time' as the time when we send
438 // out the first bytes of the request headers.
439 if (bytes_remaining
== request_headers_
->size())
440 response_
->request_time
= base::Time::Now();
442 io_state_
= STATE_SEND_HEADERS_COMPLETE
;
443 return connection_
->socket()
444 ->Write(request_headers_
.get(), bytes_remaining
, io_callback_
);
447 int HttpStreamParser::DoSendHeadersComplete(int result
) {
449 // In the unlikely case that the headers and body were merged, all the
450 // the headers were sent, but not all of the body way, and |result| is
451 // an error that this should try reading after, stash the error for now and
452 // act like the request was successfully sent.
453 if (request_headers_
->BytesConsumed() >= request_headers_length_
&&
454 ShouldTryReadingOnUploadError(result
)) {
455 upload_error_
= result
;
461 request_headers_
->DidConsume(result
);
462 if (request_headers_
->BytesRemaining() > 0) {
463 io_state_
= STATE_SEND_HEADERS
;
467 if (request_
->upload_data_stream
!= NULL
&&
468 (request_
->upload_data_stream
->is_chunked() ||
469 // !IsEOF() indicates that the body wasn't merged.
470 (request_
->upload_data_stream
->size() > 0 &&
471 !request_
->upload_data_stream
->IsEOF()))) {
473 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_BODY
,
474 base::Bind(&NetLogSendRequestBodyCallback
,
475 request_
->upload_data_stream
->size(),
476 request_
->upload_data_stream
->is_chunked(),
477 false /* not merged */));
478 io_state_
= STATE_SEND_BODY
;
482 // Finished sending the request.
486 int HttpStreamParser::DoSendBody() {
487 if (request_body_send_buf_
->BytesRemaining() > 0) {
488 io_state_
= STATE_SEND_BODY_COMPLETE
;
489 return connection_
->socket()
490 ->Write(request_body_send_buf_
.get(),
491 request_body_send_buf_
->BytesRemaining(),
495 if (request_
->upload_data_stream
->is_chunked() && sent_last_chunk_
) {
496 // Finished sending the request.
500 request_body_read_buf_
->Clear();
501 io_state_
= STATE_SEND_REQUEST_READ_BODY_COMPLETE
;
502 return request_
->upload_data_stream
->Read(request_body_read_buf_
.get(),
503 request_body_read_buf_
->capacity(),
507 int HttpStreamParser::DoSendBodyComplete(int result
) {
509 // If |result| is an error that this should try reading after, stash the
510 // error for now and act like the request was successfully sent.
511 if (ShouldTryReadingOnUploadError(result
)) {
512 upload_error_
= result
;
518 request_body_send_buf_
->DidConsume(result
);
520 io_state_
= STATE_SEND_BODY
;
524 int HttpStreamParser::DoSendRequestReadBodyComplete(int result
) {
525 // |result| is the result of read from the request body from the last call to
527 DCHECK_GE(result
, 0); // There won't be errors.
529 // Chunked data needs to be encoded.
530 if (request_
->upload_data_stream
->is_chunked()) {
531 if (result
== 0) { // Reached the end.
532 DCHECK(request_
->upload_data_stream
->IsEOF());
533 sent_last_chunk_
= true;
535 // Encode the buffer as 1 chunk.
536 const base::StringPiece
payload(request_body_read_buf_
->data(), result
);
537 request_body_send_buf_
->Clear();
538 result
= EncodeChunk(payload
,
539 request_body_send_buf_
->data(),
540 request_body_send_buf_
->capacity());
543 if (result
== 0) { // Reached the end.
544 // Reaching EOF means we can finish sending request body unless the data is
545 // chunked. (i.e. No need to send the terminal chunk.)
546 DCHECK(request_
->upload_data_stream
->IsEOF());
547 DCHECK(!request_
->upload_data_stream
->is_chunked());
548 // Finished sending the request.
549 } else if (result
> 0) {
550 request_body_send_buf_
->DidAppend(result
);
552 io_state_
= STATE_SEND_BODY
;
557 int HttpStreamParser::DoReadHeaders() {
558 io_state_
= STATE_READ_HEADERS_COMPLETE
;
560 // Grow the read buffer if necessary.
561 if (read_buf_
->RemainingCapacity() == 0)
562 read_buf_
->SetCapacity(read_buf_
->capacity() + kHeaderBufInitialSize
);
564 // http://crbug.com/16371: We're seeing |user_buf_->data()| return NULL.
565 // See if the user is passing in an IOBuffer with a NULL |data_|.
566 CHECK(read_buf_
->data());
568 return connection_
->socket()
569 ->Read(read_buf_
.get(), read_buf_
->RemainingCapacity(), io_callback_
);
572 int HttpStreamParser::DoReadHeadersComplete(int result
) {
573 result
= HandleReadHeaderResult(result
);
575 // TODO(mmenke): The code below is ugly and hacky. A much better and more
576 // flexible long term solution would be to separate out the read and write
577 // loops, though this would involve significant changes, both here and
578 // elsewhere (WebSockets, for instance).
580 // If still reading the headers, or there was no error uploading the request
581 // body, just return the result.
582 if (io_state_
== STATE_READ_HEADERS
|| upload_error_
== OK
)
585 // If the result is ERR_IO_PENDING, |io_state_| should be STATE_READ_HEADERS.
586 DCHECK_NE(ERR_IO_PENDING
, result
);
588 // On errors, use the original error received when sending the request.
589 // The main cases where these are different is when there's a header-related
590 // error code, or when there's an ERR_CONNECTION_CLOSED, which can result in
591 // special handling of partial responses and HTTP/0.9 responses.
593 // Nothing else to do. In the HTTP/0.9 or only partial headers received
594 // cases, can normally go to other states after an error reading headers.
595 io_state_
= STATE_DONE
;
596 // Don't let caller see the headers.
597 response_
->headers
= NULL
;
598 return upload_error_
;
601 // Skip over 1xx responses as usual, and allow 4xx/5xx error responses to
602 // override the error received while uploading the body.
603 int response_code_class
= response_
->headers
->response_code() / 100;
604 if (response_code_class
== 1 || response_code_class
== 4 ||
605 response_code_class
== 5) {
609 // All other status codes are not allowed after an error during upload, to
610 // make sure the consumer has some indication there was an error.
612 // Nothing else to do.
613 io_state_
= STATE_DONE
;
614 // Don't let caller see the headers.
615 response_
->headers
= NULL
;
616 return upload_error_
;
619 int HttpStreamParser::DoReadBody() {
620 io_state_
= STATE_READ_BODY_COMPLETE
;
622 // There may be some data left over from reading the response headers.
623 if (read_buf_
->offset()) {
624 int available
= read_buf_
->offset() - read_buf_unused_offset_
;
626 CHECK_GT(available
, 0);
627 int bytes_from_buffer
= std::min(available
, user_read_buf_len_
);
628 memcpy(user_read_buf_
->data(),
629 read_buf_
->StartOfBuffer() + read_buf_unused_offset_
,
631 read_buf_unused_offset_
+= bytes_from_buffer
;
632 if (bytes_from_buffer
== available
) {
633 read_buf_
->SetCapacity(0);
634 read_buf_unused_offset_
= 0;
636 return bytes_from_buffer
;
638 read_buf_
->SetCapacity(0);
639 read_buf_unused_offset_
= 0;
643 // Check to see if we're done reading.
644 if (IsResponseBodyComplete())
647 DCHECK_EQ(0, read_buf_
->offset());
648 return connection_
->socket()
649 ->Read(user_read_buf_
.get(), user_read_buf_len_
, io_callback_
);
652 int HttpStreamParser::DoReadBodyComplete(int result
) {
653 // When the connection is closed, there are numerous ways to interpret it.
655 // - If a Content-Length header is present and the body contains exactly that
656 // number of bytes at connection close, the response is successful.
658 // - If a Content-Length header is present and the body contains fewer bytes
659 // than promised by the header at connection close, it may indicate that
660 // the connection was closed prematurely, or it may indicate that the
661 // server sent an invalid Content-Length header. Unfortunately, the invalid
662 // Content-Length header case does occur in practice and other browsers are
663 // tolerant of it. We choose to treat it as an error for now, but the
664 // download system treats it as a non-error, and URLRequestHttpJob also
665 // treats it as OK if the Content-Length is the post-decoded body content
668 // - If chunked encoding is used and the terminating chunk has been processed
669 // when the connection is closed, the response is successful.
671 // - If chunked encoding is used and the terminating chunk has not been
672 // processed when the connection is closed, it may indicate that the
673 // connection was closed prematurely or it may indicate that the server
674 // sent an invalid chunked encoding. We choose to treat it as
675 // an invalid chunked encoding.
677 // - If a Content-Length is not present and chunked encoding is not used,
678 // connection close is the only way to signal that the response is
679 // complete. Unfortunately, this also means that there is no way to detect
680 // early close of a connection. No error is returned.
681 if (result
== 0 && !IsResponseBodyComplete() && CanFindEndOfResponse()) {
682 if (chunked_decoder_
.get())
683 result
= ERR_INCOMPLETE_CHUNKED_ENCODING
;
685 result
= ERR_CONTENT_LENGTH_MISMATCH
;
689 received_bytes_
+= result
;
691 // Filter incoming data if appropriate. FilterBuf may return an error.
692 if (result
> 0 && chunked_decoder_
.get()) {
693 result
= chunked_decoder_
->FilterBuf(user_read_buf_
->data(), result
);
694 if (result
== 0 && !chunked_decoder_
->reached_eof()) {
695 // Don't signal completion of the Read call yet or else it'll look like
696 // we received end-of-file. Wait for more data.
697 io_state_
= STATE_READ_BODY
;
703 response_body_read_
+= result
;
705 if (result
<= 0 || IsResponseBodyComplete()) {
706 io_state_
= STATE_DONE
;
708 // Save the overflow data, which can be in two places. There may be
709 // some left over in |user_read_buf_|, plus there may be more
710 // in |read_buf_|. But the part left over in |user_read_buf_| must have
711 // come from the |read_buf_|, so there's room to put it back at the
713 int additional_save_amount
= read_buf_
->offset() - read_buf_unused_offset_
;
715 if (chunked_decoder_
.get()) {
716 save_amount
= chunked_decoder_
->bytes_after_eof();
717 } else if (response_body_length_
>= 0) {
718 int64 extra_data_read
= response_body_read_
- response_body_length_
;
719 if (extra_data_read
> 0) {
720 save_amount
= static_cast<int>(extra_data_read
);
722 result
-= save_amount
;
726 CHECK_LE(save_amount
+ additional_save_amount
, kMaxBufSize
);
727 if (read_buf_
->capacity() < save_amount
+ additional_save_amount
) {
728 read_buf_
->SetCapacity(save_amount
+ additional_save_amount
);
732 received_bytes_
-= save_amount
;
733 memcpy(read_buf_
->StartOfBuffer(), user_read_buf_
->data() + result
,
736 read_buf_
->set_offset(save_amount
);
737 if (additional_save_amount
) {
738 memmove(read_buf_
->data(),
739 read_buf_
->StartOfBuffer() + read_buf_unused_offset_
,
740 additional_save_amount
);
741 read_buf_
->set_offset(save_amount
+ additional_save_amount
);
743 read_buf_unused_offset_
= 0;
745 // Now waiting for more of the body to be read.
746 user_read_buf_
= NULL
;
747 user_read_buf_len_
= 0;
753 int HttpStreamParser::HandleReadHeaderResult(int result
) {
754 DCHECK_EQ(0, read_buf_unused_offset_
);
757 result
= ERR_CONNECTION_CLOSED
;
759 if (result
< 0 && result
!= ERR_CONNECTION_CLOSED
) {
760 io_state_
= STATE_DONE
;
763 // If we've used the connection before, then we know it is not a HTTP/0.9
764 // response and return ERR_CONNECTION_CLOSED.
765 if (result
== ERR_CONNECTION_CLOSED
&& read_buf_
->offset() == 0 &&
766 connection_
->is_reused()) {
767 io_state_
= STATE_DONE
;
771 // Record our best estimate of the 'response time' as the time when we read
772 // the first bytes of the response headers.
773 if (read_buf_
->offset() == 0 && result
!= ERR_CONNECTION_CLOSED
)
774 response_
->response_time
= base::Time::Now();
776 if (result
== ERR_CONNECTION_CLOSED
) {
777 // The connection closed before we detected the end of the headers.
778 if (read_buf_
->offset() == 0) {
779 // The connection was closed before any data was sent. Likely an error
780 // rather than empty HTTP/0.9 response.
781 io_state_
= STATE_DONE
;
782 return ERR_EMPTY_RESPONSE
;
783 } else if (request_
->url
.SchemeIsSecure()) {
784 // The connection was closed in the middle of the headers. For HTTPS we
785 // don't parse partial headers. Return a different error code so that we
786 // know that we shouldn't attempt to retry the request.
787 io_state_
= STATE_DONE
;
788 return ERR_RESPONSE_HEADERS_TRUNCATED
;
790 // Parse things as well as we can and let the caller decide what to do.
792 if (response_header_start_offset_
>= 0) {
793 io_state_
= STATE_READ_BODY_COMPLETE
;
794 end_offset
= read_buf_
->offset();
796 // Now waiting for the body to be read.
799 int rv
= DoParseResponseHeaders(end_offset
);
805 read_buf_
->set_offset(read_buf_
->offset() + result
);
806 DCHECK_LE(read_buf_
->offset(), read_buf_
->capacity());
807 DCHECK_GE(result
, 0);
809 int end_of_header_offset
= ParseResponseHeaders();
811 // Note: -1 is special, it indicates we haven't found the end of headers.
812 // Anything less than -1 is a net::Error, so we bail out.
813 if (end_of_header_offset
< -1)
814 return end_of_header_offset
;
816 if (end_of_header_offset
== -1) {
817 io_state_
= STATE_READ_HEADERS
;
818 // Prevent growing the headers buffer indefinitely.
819 if (read_buf_
->offset() >= kMaxHeaderBufSize
) {
820 io_state_
= STATE_DONE
;
821 return ERR_RESPONSE_HEADERS_TOO_BIG
;
824 CalculateResponseBodySize();
825 // If the body is zero length, the caller may not call ReadResponseBody,
826 // which is where any extra data is copied to read_buf_, so we move the
828 if (response_body_length_
== 0) {
829 int extra_bytes
= read_buf_
->offset() - end_of_header_offset
;
831 CHECK_GT(extra_bytes
, 0);
832 memmove(read_buf_
->StartOfBuffer(),
833 read_buf_
->StartOfBuffer() + end_of_header_offset
,
836 read_buf_
->SetCapacity(extra_bytes
);
837 if (response_
->headers
->response_code() / 100 == 1) {
838 // After processing a 1xx response, the caller will ask for the next
839 // header, so reset state to support that. We don't completely ignore a
840 // 1xx response because it cannot be returned in reply to a CONNECT
841 // request so we return OK here, which lets the caller inspect the
842 // response and reject it in the event that we're setting up a CONNECT
844 response_header_start_offset_
= -1;
845 response_body_length_
= -1;
846 // Now waiting for the second set of headers to be read.
848 io_state_
= STATE_DONE
;
853 // Note where the headers stop.
854 read_buf_unused_offset_
= end_of_header_offset
;
855 // Now waiting for the body to be read.
860 int HttpStreamParser::ParseResponseHeaders() {
862 DCHECK_EQ(0, read_buf_unused_offset_
);
864 // Look for the start of the status line, if it hasn't been found yet.
865 if (response_header_start_offset_
< 0) {
866 response_header_start_offset_
= HttpUtil::LocateStartOfStatusLine(
867 read_buf_
->StartOfBuffer(), read_buf_
->offset());
870 if (response_header_start_offset_
>= 0) {
871 end_offset
= HttpUtil::LocateEndOfHeaders(read_buf_
->StartOfBuffer(),
873 response_header_start_offset_
);
874 } else if (read_buf_
->offset() >= 8) {
875 // Enough data to decide that this is an HTTP/0.9 response.
876 // 8 bytes = (4 bytes of junk) + "http".length()
880 if (end_offset
== -1)
883 int rv
= DoParseResponseHeaders(end_offset
);
889 int HttpStreamParser::DoParseResponseHeaders(int end_offset
) {
890 scoped_refptr
<HttpResponseHeaders
> headers
;
891 DCHECK_EQ(0, read_buf_unused_offset_
);
893 if (response_header_start_offset_
>= 0) {
894 received_bytes_
+= end_offset
;
895 headers
= new HttpResponseHeaders(HttpUtil::AssembleRawHeaders(
896 read_buf_
->StartOfBuffer(), end_offset
));
898 // Enough data was read -- there is no status line.
899 headers
= new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
902 // Check for multiple Content-Length headers with no Transfer-Encoding header.
903 // If they exist, and have distinct values, it's a potential response
905 if (!headers
->HasHeader("Transfer-Encoding")) {
906 if (HeadersContainMultipleCopiesOfField(*headers
.get(), "Content-Length"))
907 return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH
;
910 // Check for multiple Content-Disposition or Location headers. If they exist,
911 // it's also a potential response smuggling attack.
912 if (HeadersContainMultipleCopiesOfField(*headers
.get(),
913 "Content-Disposition"))
914 return ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
;
915 if (HeadersContainMultipleCopiesOfField(*headers
.get(), "Location"))
916 return ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION
;
918 response_
->headers
= headers
;
919 response_
->connection_info
= HttpResponseInfo::CONNECTION_INFO_HTTP1
;
920 response_
->vary_data
.Init(*request_
, *response_
->headers
.get());
921 DVLOG(1) << __FUNCTION__
<< "()"
922 << " content_length = \"" << response_
->headers
->GetContentLength()
925 << GetResponseHeaderLines(*response_
->headers
.get()) << "\"";
929 void HttpStreamParser::CalculateResponseBodySize() {
930 // Figure how to determine EOF:
932 // For certain responses, we know the content length is always 0. From
933 // RFC 2616 Section 4.3 Message Body:
935 // For response messages, whether or not a message-body is included with
936 // a message is dependent on both the request method and the response
937 // status code (section 6.1.1). All responses to the HEAD request method
938 // MUST NOT include a message-body, even though the presence of entity-
939 // header fields might lead one to believe they do. All 1xx
940 // (informational), 204 (no content), and 304 (not modified) responses
941 // MUST NOT include a message-body. All other responses do include a
942 // message-body, although it MAY be of zero length.
943 if (response_
->headers
->response_code() / 100 == 1) {
944 response_body_length_
= 0;
946 switch (response_
->headers
->response_code()) {
947 case 204: // No Content
948 case 205: // Reset Content
949 case 304: // Not Modified
950 response_body_length_
= 0;
954 if (request_
->method
== "HEAD")
955 response_body_length_
= 0;
957 if (response_body_length_
== -1) {
958 // "Transfer-Encoding: chunked" trumps "Content-Length: N"
959 if (response_
->headers
->IsChunkEncoded()) {
960 chunked_decoder_
.reset(new HttpChunkedDecoder());
962 response_body_length_
= response_
->headers
->GetContentLength();
963 // If response_body_length_ is still -1, then we have to wait
964 // for the server to close the connection.
969 UploadProgress
HttpStreamParser::GetUploadProgress() const {
970 if (!request_
->upload_data_stream
)
971 return UploadProgress();
973 return UploadProgress(request_
->upload_data_stream
->position(),
974 request_
->upload_data_stream
->size());
977 bool HttpStreamParser::IsResponseBodyComplete() const {
978 if (chunked_decoder_
.get())
979 return chunked_decoder_
->reached_eof();
980 if (response_body_length_
!= -1)
981 return response_body_read_
>= response_body_length_
;
983 return false; // Must read to EOF.
986 bool HttpStreamParser::CanFindEndOfResponse() const {
987 return chunked_decoder_
.get() || response_body_length_
>= 0;
990 bool HttpStreamParser::IsMoreDataBuffered() const {
991 return read_buf_
->offset() > read_buf_unused_offset_
;
994 bool HttpStreamParser::IsConnectionReused() const {
995 ClientSocketHandle::SocketReuseType reuse_type
= connection_
->reuse_type();
996 return connection_
->is_reused() ||
997 reuse_type
== ClientSocketHandle::UNUSED_IDLE
;
1000 void HttpStreamParser::SetConnectionReused() {
1001 connection_
->set_reuse_type(ClientSocketHandle::REUSED_IDLE
);
1004 bool HttpStreamParser::IsConnectionReusable() const {
1005 return connection_
->socket() && connection_
->socket()->IsConnectedAndIdle();
1008 void HttpStreamParser::GetSSLInfo(SSLInfo
* ssl_info
) {
1009 if (request_
->url
.SchemeIsSecure() && connection_
->socket()) {
1010 SSLClientSocket
* ssl_socket
=
1011 static_cast<SSLClientSocket
*>(connection_
->socket());
1012 ssl_socket
->GetSSLInfo(ssl_info
);
1016 void HttpStreamParser::GetSSLCertRequestInfo(
1017 SSLCertRequestInfo
* cert_request_info
) {
1018 if (request_
->url
.SchemeIsSecure() && connection_
->socket()) {
1019 SSLClientSocket
* ssl_socket
=
1020 static_cast<SSLClientSocket
*>(connection_
->socket());
1021 ssl_socket
->GetSSLCertRequestInfo(cert_request_info
);
1025 int HttpStreamParser::EncodeChunk(const base::StringPiece
& payload
,
1027 size_t output_size
) {
1028 if (output_size
< payload
.size() + kChunkHeaderFooterSize
)
1029 return ERR_INVALID_ARGUMENT
;
1031 char* cursor
= output
;
1033 const int num_chars
= base::snprintf(output
, output_size
,
1035 static_cast<int>(payload
.size()));
1036 cursor
+= num_chars
;
1037 // Add the payload if any.
1038 if (payload
.size() > 0) {
1039 memcpy(cursor
, payload
.data(), payload
.size());
1040 cursor
+= payload
.size();
1042 // Add the trailing CRLF.
1043 memcpy(cursor
, "\r\n", 2);
1046 return cursor
- output
;
1050 bool HttpStreamParser::ShouldMergeRequestHeadersAndBody(
1051 const std::string
& request_headers
,
1052 const UploadDataStream
* request_body
) {
1053 if (request_body
!= NULL
&&
1054 // IsInMemory() ensures that the request body is not chunked.
1055 request_body
->IsInMemory() &&
1056 request_body
->size() > 0) {
1057 uint64 merged_size
= request_headers
.size() + request_body
->size();
1058 if (merged_size
<= kMaxMergedHeaderAndBodySize
)