Don't close the socket in the HttpNetworkTransaction
destructor if we can and should keep the connection alive.
This is necessary because in some situations, DoReadBodyComplete
never gets called; this can happen, for example, when the response
body length is zero, and the caller would be the cache transaction.

BUG=47191
TEST=Added unit test. Existing net_unittests pass.

Review URL: http://codereview.chromium.org/2807014

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@50740 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc
old mode 100644
new mode 100755
index d65a892..016cd58
--- a/net/http/http_network_transaction.cc
+++ b/net/http/http_network_transaction.cc
@@ -542,9 +542,19 @@
 
 HttpNetworkTransaction::~HttpNetworkTransaction() {
   // If we still have an open socket, then make sure to disconnect it so it
-  // won't call us back and we don't try to reuse it later on.
-  if (connection_.get() && connection_->is_initialized())
-    connection_->socket()->Disconnect();
+  // won't call us back and we don't try to reuse it later on. However,
+  // don't close the socket if we should keep the connection alive.
+  if (connection_.get() && connection_->is_initialized()) {
+    // The STATE_NONE check guarantees there are no pending socket IOs that
+    // could try to call this object back after it is deleted.
+    bool keep_alive = next_state_ == STATE_NONE &&
+                      http_stream_.get() &&
+                      http_stream_->IsResponseBodyComplete() &&
+                      http_stream_->CanFindEndOfResponse() &&
+                      GetResponseHeaders()->IsKeepAlive();
+    if (!keep_alive)
+      connection_->socket()->Disconnect();
+  }
 
   if (pac_request_)
     session_->proxy_service()->CancelPacRequest(pac_request_);