summaryrefslogtreecommitdiffstats
path: root/net/http/http_network_transaction.cc
diff options
context:
space:
mode:
authorBen Murdoch <benm@google.com>2010-07-29 17:14:53 +0100
committerBen Murdoch <benm@google.com>2010-08-04 14:29:45 +0100
commitc407dc5cd9bdc5668497f21b26b09d988ab439de (patch)
tree7eaf8707c0309516bdb042ad976feedaf72b0bb1 /net/http/http_network_transaction.cc
parent0998b1cdac5733f299c12d88bc31ef9c8035b8fa (diff)
downloadexternal_chromium-c407dc5cd9bdc5668497f21b26b09d988ab439de.zip
external_chromium-c407dc5cd9bdc5668497f21b26b09d988ab439de.tar.gz
external_chromium-c407dc5cd9bdc5668497f21b26b09d988ab439de.tar.bz2
Merge Chromium src@r53293
Change-Id: Ia79acf8670f385cee48c45b0a75371d8e950af34
Diffstat (limited to 'net/http/http_network_transaction.cc')
-rw-r--r--net/http/http_network_transaction.cc1772
1 files changed, 840 insertions, 932 deletions
diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc
index 4be555f..a85a1ca 100644
--- a/net/http/http_network_transaction.cc
+++ b/net/http/http_network_transaction.cc
@@ -1,41 +1,51 @@
-// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_network_transaction.h"
-#include "base/format_macros.h"
-#include "base/scoped_ptr.h"
#include "base/compiler_specific.h"
#include "base/field_trial.h"
+#include "base/format_macros.h"
#include "base/histogram.h"
+#include "base/scoped_ptr.h"
#include "base/stats_counters.h"
+#include "base/stl_util-inl.h"
#include "base/string_util.h"
-#include "base/trace_event.h"
#include "build/build_config.h"
+#include "googleurl/src/gurl.h"
#include "net/base/connection_type_histograms.h"
+#include "net/base/host_mapping_rules.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/ssl_cert_request_info.h"
+#include "net/base/ssl_connection_status_flags.h"
#include "net/base/upload_data_stream.h"
-#include "net/flip/flip_session.h"
-#include "net/flip/flip_session_pool.h"
-#include "net/flip/flip_stream.h"
#include "net/http/http_auth.h"
#include "net/http/http_auth_handler.h"
+#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_basic_stream.h"
#include "net/http/http_chunked_decoder.h"
+#include "net/http/http_net_log_params.h"
#include "net/http/http_network_session.h"
+#include "net/http/http_proxy_client_socket.h"
+#include "net/http/http_proxy_client_socket_pool.h"
+#include "net/http/http_request_headers.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
+#include "net/http/url_security_manager.h"
#include "net/socket/client_socket_factory.h"
-#include "net/socket/socks5_client_socket.h"
-#include "net/socket/socks_client_socket.h"
+#include "net/socket/socks_client_socket_pool.h"
#include "net/socket/ssl_client_socket.h"
+#include "net/socket/ssl_client_socket_pool.h"
+#include "net/socket/tcp_client_socket_pool.h"
+#include "net/spdy/spdy_http_stream.h"
+#include "net/spdy/spdy_session.h"
+#include "net/spdy/spdy_session_pool.h"
using base::Time;
@@ -43,95 +53,143 @@ namespace net {
namespace {
+const HostMappingRules* g_host_mapping_rules = NULL;
+const std::string* g_next_protos = NULL;
+bool g_use_alternate_protocols = false;
+
+// A set of host:port strings. These are servers which we have needed to back
+// off to SSLv3 for.
+std::set<std::string>* g_tls_intolerant_servers = NULL;
+
void BuildRequestHeaders(const HttpRequestInfo* request_info,
- const std::string& authorization_headers,
+ const HttpRequestHeaders& authorization_headers,
const UploadDataStream* upload_data_stream,
bool using_proxy,
- std::string* request_headers) {
+ std::string* request_line,
+ HttpRequestHeaders* request_headers) {
const std::string path = using_proxy ?
- HttpUtil::SpecForRequest(request_info->url) :
- HttpUtil::PathForRequest(request_info->url);
- *request_headers =
- StringPrintf("%s %s HTTP/1.1\r\nHost: %s\r\n",
- request_info->method.c_str(), path.c_str(),
- GetHostAndOptionalPort(request_info->url).c_str());
+ HttpUtil::SpecForRequest(request_info->url) :
+ HttpUtil::PathForRequest(request_info->url);
+ *request_line = StringPrintf(
+ "%s %s HTTP/1.1\r\n", request_info->method.c_str(), path.c_str());
+ request_headers->SetHeader(HttpRequestHeaders::kHost,
+ GetHostAndOptionalPort(request_info->url));
// For compat with HTTP/1.0 servers and proxies:
- if (using_proxy)
- *request_headers += "Proxy-";
- *request_headers += "Connection: keep-alive\r\n";
-
- if (!request_info->user_agent.empty()) {
- StringAppendF(request_headers, "User-Agent: %s\r\n",
- request_info->user_agent.c_str());
+ if (using_proxy) {
+ request_headers->SetHeader(HttpRequestHeaders::kProxyConnection,
+ "keep-alive");
+ } else {
+ request_headers->SetHeader(HttpRequestHeaders::kConnection, "keep-alive");
}
// Our consumer should have made sure that this is a safe referrer. See for
// instance WebCore::FrameLoader::HideReferrer.
- if (request_info->referrer.is_valid())
- StringAppendF(request_headers, "Referer: %s\r\n",
- request_info->referrer.spec().c_str());
+ if (request_info->referrer.is_valid()) {
+ request_headers->SetHeader(HttpRequestHeaders::kReferer,
+ request_info->referrer.spec());
+ }
// Add a content length header?
if (upload_data_stream) {
- StringAppendF(request_headers, "Content-Length: %" PRIu64 "\r\n",
- upload_data_stream->size());
+ request_headers->SetHeader(
+ HttpRequestHeaders::kContentLength,
+ Uint64ToString(upload_data_stream->size()));
} else if (request_info->method == "POST" || request_info->method == "PUT" ||
request_info->method == "HEAD") {
// An empty POST/PUT request still needs a content length. As for HEAD,
// IE and Safari also add a content length header. Presumably it is to
// support sending a HEAD request to an URL that only expects to be sent a
// POST or some other method that normally would have a message body.
- *request_headers += "Content-Length: 0\r\n";
+ request_headers->SetHeader(HttpRequestHeaders::kContentLength, "0");
}
// Honor load flags that impact proxy caches.
if (request_info->load_flags & LOAD_BYPASS_CACHE) {
- *request_headers += "Pragma: no-cache\r\nCache-Control: no-cache\r\n";
+ request_headers->SetHeader(HttpRequestHeaders::kPragma, "no-cache");
+ request_headers->SetHeader(HttpRequestHeaders::kCacheControl, "no-cache");
} else if (request_info->load_flags & LOAD_VALIDATE_CACHE) {
- *request_headers += "Cache-Control: max-age=0\r\n";
+ request_headers->SetHeader(HttpRequestHeaders::kCacheControl, "max-age=0");
}
- if (!authorization_headers.empty()) {
- *request_headers += authorization_headers;
- }
+ request_headers->MergeFrom(authorization_headers);
- // TODO(darin): Need to prune out duplicate headers.
+ // Headers that will be stripped from request_info->extra_headers to prevent,
+ // e.g., plugins from overriding headers that are controlled using other
+ // means. Otherwise a plugin could set a referrer although sending the
+ // referrer is inhibited.
+ // TODO(jochen): check whether also other headers should be stripped.
+ static const char* const kExtraHeadersToBeStripped[] = {
+ "Referer"
+ };
- *request_headers += request_info->extra_headers;
- *request_headers += "\r\n";
+ HttpRequestHeaders stripped_extra_headers;
+ stripped_extra_headers.CopyFrom(request_info->extra_headers);
+ for (size_t i = 0; i < arraysize(kExtraHeadersToBeStripped); ++i)
+ stripped_extra_headers.RemoveHeader(kExtraHeadersToBeStripped[i]);
+ request_headers->MergeFrom(stripped_extra_headers);
}
-// The HTTP CONNECT method for establishing a tunnel connection is documented
-// in draft-luotonen-web-proxy-tunneling-01.txt and RFC 2817, Sections 5.2 and
-// 5.3.
-void BuildTunnelRequest(const HttpRequestInfo* request_info,
- const std::string& authorization_headers,
- std::string* request_headers) {
- // RFC 2616 Section 9 says the Host request-header field MUST accompany all
- // HTTP/1.1 requests. Add "Proxy-Connection: keep-alive" for compat with
- // HTTP/1.0 proxies such as Squid (required for NTLM authentication).
- *request_headers = StringPrintf(
- "CONNECT %s HTTP/1.1\r\nHost: %s\r\nProxy-Connection: keep-alive\r\n",
- GetHostAndPort(request_info->url).c_str(),
- GetHostAndOptionalPort(request_info->url).c_str());
+void ProcessAlternateProtocol(const HttpResponseHeaders& headers,
+ const HostPortPair& http_host_port_pair,
+ HttpAlternateProtocols* alternate_protocols) {
+
+ std::string alternate_protocol_str;
+ if (!headers.EnumerateHeader(NULL, HttpAlternateProtocols::kHeader,
+ &alternate_protocol_str)) {
+ // Header is not present.
+ return;
+ }
- if (!request_info->user_agent.empty())
- StringAppendF(request_headers, "User-Agent: %s\r\n",
- request_info->user_agent.c_str());
+ std::vector<std::string> port_protocol_vector;
+ SplitString(alternate_protocol_str, ':', &port_protocol_vector);
+ if (port_protocol_vector.size() != 2) {
+ DLOG(WARNING) << HttpAlternateProtocols::kHeader
+ << " header has too many tokens: "
+ << alternate_protocol_str;
+ return;
+ }
- if (!authorization_headers.empty()) {
- *request_headers += authorization_headers;
+ int port;
+ if (!StringToInt(port_protocol_vector[0], &port) ||
+ port <= 0 || port >= 1 << 16) {
+ DLOG(WARNING) << HttpAlternateProtocols::kHeader
+ << " header has unrecognizable port: "
+ << port_protocol_vector[0];
+ return;
}
- *request_headers += "\r\n";
+ if (port_protocol_vector[1] !=
+ HttpAlternateProtocols::kProtocolStrings[
+ HttpAlternateProtocols::NPN_SPDY_1]) {
+ // Currently, we only recognize the npn-spdy protocol.
+ DLOG(WARNING) << HttpAlternateProtocols::kHeader
+ << " header has unrecognized protocol: "
+ << port_protocol_vector[1];
+ return;
+ }
+
+ HostPortPair host_port(http_host_port_pair);
+ if (g_host_mapping_rules)
+ g_host_mapping_rules->RewriteHost(&host_port);
+
+ if (alternate_protocols->HasAlternateProtocolFor(host_port)) {
+ const HttpAlternateProtocols::PortProtocolPair existing_alternate =
+ alternate_protocols->GetAlternateProtocolFor(host_port);
+ // If we think the alternate protocol is broken, don't change it.
+ if (existing_alternate.protocol == HttpAlternateProtocols::BROKEN)
+ return;
+ }
+
+ alternate_protocols->SetAlternateProtocolFor(
+ host_port, port, HttpAlternateProtocols::NPN_SPDY_1);
}
} // namespace
//-----------------------------------------------------------------------------
-std::string* HttpNetworkTransaction::g_next_protos = NULL;
+bool HttpNetworkTransaction::g_ignore_certificate_errors = false;
HttpNetworkTransaction::HttpNetworkTransaction(HttpNetworkSession* session)
: pending_auth_target_(HttpAuth::AUTH_NONE),
@@ -144,16 +202,34 @@ HttpNetworkTransaction::HttpNetworkTransaction(HttpNetworkSession* session)
connection_(new ClientSocketHandle),
reused_socket_(false),
headers_valid_(false),
- logged_response_time(false),
+ logged_response_time_(false),
using_ssl_(false),
- proxy_mode_(kDirectConnection),
- establishing_tunnel_(false),
- embedded_identity_used_(false),
+ using_spdy_(false),
+ spdy_certificate_error_(OK),
+ alternate_protocol_mode_(
+ g_use_alternate_protocols ? kUnspecified :
+ kDoNotUseAlternateProtocol),
read_buf_len_(0),
- next_state_(STATE_NONE) {
+ next_state_(STATE_NONE),
+ establishing_tunnel_(false) {
session->ssl_config_service()->GetSSLConfig(&ssl_config_);
if (g_next_protos)
ssl_config_.next_protos = *g_next_protos;
+ if (!g_tls_intolerant_servers)
+ g_tls_intolerant_servers = new std::set<std::string>;
+}
+
+// static
+void HttpNetworkTransaction::SetHostMappingRules(const std::string& rules) {
+ HostMappingRules* host_mapping_rules = new HostMappingRules();
+ host_mapping_rules->SetRulesFromString(rules);
+ delete g_host_mapping_rules;
+ g_host_mapping_rules = host_mapping_rules;
+}
+
+// static
+void HttpNetworkTransaction::SetUseAlternateProtocols(bool value) {
+ g_use_alternate_protocols = value;
}
// static
@@ -162,12 +238,17 @@ void HttpNetworkTransaction::SetNextProtos(const std::string& next_protos) {
g_next_protos = new std::string(next_protos);
}
+// static
+void HttpNetworkTransaction::IgnoreCertificateErrors(bool enabled) {
+ g_ignore_certificate_errors = enabled;
+}
+
int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
CompletionCallback* callback,
- LoadLog* load_log) {
+ const BoundNetLog& net_log) {
SIMPLE_STATS_COUNTER("HttpNetworkTransaction.Count");
- load_log_ = load_log;
+ net_log_ = net_log;
request_ = request_info;
start_time_ = base::Time::Now();
@@ -180,10 +261,18 @@ int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
int HttpNetworkTransaction::RestartIgnoringLastError(
CompletionCallback* callback) {
- if (connection_->socket()->IsConnectedAndIdle()) {
- next_state_ = STATE_SEND_REQUEST;
+ if (connection_->socket() && connection_->socket()->IsConnectedAndIdle()) {
+ // TODO(wtc): Should we update any of the connection histograms that we
+ // update in DoSSLConnectComplete if |result| is OK?
+ if (using_spdy_) {
+ // TODO(cbentzel): Add auth support to spdy. See http://crbug.com/46620
+ next_state_ = STATE_SPDY_GET_STREAM;
+ } else {
+ next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
+ }
} else {
- connection_->socket()->Disconnect();
+ if (connection_->socket())
+ connection_->socket()->Disconnect();
connection_->Reset();
next_state_ = STATE_INIT_CONNECTION;
}
@@ -221,22 +310,18 @@ int HttpNetworkTransaction::RestartWithAuth(
NOTREACHED();
return ERR_UNEXPECTED;
}
-
pending_auth_target_ = HttpAuth::AUTH_NONE;
- DCHECK(auth_identity_[target].invalid ||
- (username.empty() && password.empty()));
+ auth_controllers_[target]->ResetAuth(username, password);
- if (auth_identity_[target].invalid) {
- // Update the username/password.
- auth_identity_[target].source = HttpAuth::IDENT_SRC_EXTERNAL;
- auth_identity_[target].invalid = false;
- auth_identity_[target].username = username;
- auth_identity_[target].password = password;
+ if (target == HttpAuth::AUTH_PROXY && using_ssl_ && proxy_info_.is_http()) {
+ DCHECK(establishing_tunnel_);
+ next_state_ = STATE_INIT_CONNECTION;
+ ResetStateForRestart();
+ } else {
+ PrepareForAuthRestart(target);
}
- PrepareForAuthRestart(target);
-
DCHECK(user_callback_ == NULL);
int rv = DoLoop(OK);
if (rv == ERR_IO_PENDING)
@@ -247,29 +332,7 @@ int HttpNetworkTransaction::RestartWithAuth(
void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
DCHECK(HaveAuth(target));
- DCHECK(auth_identity_[target].source != HttpAuth::IDENT_SRC_PATH_LOOKUP);
-
- // Add the auth entry to the cache before restarting. We don't know whether
- // the identity is valid yet, but if it is valid we want other transactions
- // to know about it. If an entry for (origin, handler->realm()) already
- // exists, we update it.
- //
- // If auth_identity_[target].source is HttpAuth::IDENT_SRC_NONE,
- // auth_identity_[target] contains no identity because identity is not
- // required yet.
- //
- // TODO(wtc): For NTLM_SSPI, we add the same auth entry to the cache in
- // round 1 and round 2, which is redundant but correct. It would be nice
- // to add an auth entry to the cache only once, preferrably in round 1.
- // See http://crbug.com/21015.
- bool has_auth_identity =
- auth_identity_[target].source != HttpAuth::IDENT_SRC_NONE;
- if (has_auth_identity) {
- session_->auth_cache()->Add(AuthOrigin(target), auth_handler_[target],
- auth_identity_[target].username, auth_identity_[target].password,
- AuthPath(target));
- }
-
+ DCHECK(!establishing_tunnel_);
bool keep_alive = false;
// Even if the server says the connection is keep-alive, we have to be
// able to find the end of each response in order to reuse the connection.
@@ -292,10 +355,11 @@ void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
}
void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive) {
+ DCHECK(!establishing_tunnel_);
if (keep_alive && connection_->socket()->IsConnectedAndIdle()) {
// We should call connection_->set_idle_time(), but this doesn't occur
// often enough to be worth the trouble.
- next_state_ = STATE_SEND_REQUEST;
+ next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
connection_->set_is_reused(true);
reused_socket_ = true;
} else {
@@ -315,31 +379,34 @@ int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
State next_state = STATE_NONE;
+ scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
+ if (headers_valid_ && headers.get() && establishing_tunnel_) {
+ // We're trying to read the body of the response but we're still trying
+ // to establish an SSL tunnel through the proxy. We can't read these
+ // bytes when establishing a tunnel because they might be controlled by
+ // an active network attacker. We don't worry about this for HTTP
+ // because an active network attacker can already control HTTP sessions.
+ // We reach this case when the user cancels a 407 proxy auth prompt.
+ // See http://crbug.com/8473.
+ DCHECK(proxy_info_.is_http());
+ DCHECK_EQ(headers->response_code(), 407);
+ LOG(WARNING) << "Blocked proxy response with status "
+ << headers->response_code() << " to CONNECT request for "
+ << GetHostAndPort(request_->url) << ".";
+ return ERR_TUNNEL_CONNECTION_FAILED;
+ }
+
// Are we using SPDY or HTTP?
- if (spdy_stream_.get()) {
+ if (using_spdy_) {
DCHECK(!http_stream_.get());
- DCHECK(spdy_stream_->GetResponseInfo()->headers);
+ DCHECK(spdy_http_stream_->GetResponseInfo()->headers);
next_state = STATE_SPDY_READ_BODY;
} else {
- scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
- DCHECK(headers.get());
+ DCHECK(!spdy_http_stream_.get());
next_state = STATE_READ_BODY;
if (!connection_->is_initialized())
- return 0; // connection_->has been reset. Treat like EOF.
-
- if (establishing_tunnel_) {
- // We're trying to read the body of the response but we're still trying
- // to establish an SSL tunnel through the proxy. We can't read these
- // bytes when establishing a tunnel because they might be controlled by
- // an active network attacker. We don't worry about this for HTTP
- // because an active network attacker can already control HTTP sessions.
- // We reach this case when the user cancels a 407 proxy auth prompt.
- // See http://crbug.com/8473.
- DCHECK_EQ(407, headers->response_code());
- LogBlockedTunnelResponse(headers->response_code());
- return ERR_TUNNEL_CONNECTION_FAILED;
- }
+ return 0; // |*connection_| has been reset. Treat like EOF.
}
read_buf_ = buf;
@@ -365,11 +432,17 @@ LoadState HttpNetworkTransaction::GetLoadState() const {
return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
case STATE_INIT_CONNECTION_COMPLETE:
return connection_->GetLoadState();
+ case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
+ case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
case STATE_SEND_REQUEST_COMPLETE:
+ case STATE_SPDY_GET_STREAM:
+ case STATE_SPDY_SEND_REQUEST_COMPLETE:
return LOAD_STATE_SENDING_REQUEST;
case STATE_READ_HEADERS_COMPLETE:
+ case STATE_SPDY_READ_HEADERS_COMPLETE:
return LOAD_STATE_WAITING_FOR_RESPONSE;
case STATE_READ_BODY_COMPLETE:
+ case STATE_SPDY_READ_BODY_COMPLETE:
return LOAD_STATE_READING_RESPONSE;
default:
return LOAD_STATE_IDLE;
@@ -385,15 +458,25 @@ uint64 HttpNetworkTransaction::GetUploadProgress() const {
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_);
- if (spdy_stream_.get())
- spdy_stream_->Cancel();
+ if (spdy_http_stream_.get())
+ spdy_http_stream_->Cancel();
}
void HttpNetworkTransaction::DoCallback(int rv) {
@@ -422,134 +505,103 @@ int HttpNetworkTransaction::DoLoop(int result) {
switch (state) {
case STATE_RESOLVE_PROXY:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.resolve_proxy", request_, request_->url.spec());
rv = DoResolveProxy();
break;
case STATE_RESOLVE_PROXY_COMPLETE:
rv = DoResolveProxyComplete(rv);
- TRACE_EVENT_END("http.resolve_proxy", request_, request_->url.spec());
break;
case STATE_INIT_CONNECTION:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.init_conn", request_, request_->url.spec());
rv = DoInitConnection();
break;
case STATE_INIT_CONNECTION_COMPLETE:
rv = DoInitConnectionComplete(rv);
- TRACE_EVENT_END("http.init_conn", request_, request_->url.spec());
break;
- case STATE_SOCKS_CONNECT:
+ case STATE_GENERATE_PROXY_AUTH_TOKEN:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.socks_connect", request_, request_->url.spec());
- rv = DoSOCKSConnect();
+ rv = DoGenerateProxyAuthToken();
break;
- case STATE_SOCKS_CONNECT_COMPLETE:
- rv = DoSOCKSConnectComplete(rv);
- TRACE_EVENT_END("http.socks_connect", request_, request_->url.spec());
+ case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
+ rv = DoGenerateProxyAuthTokenComplete(rv);
break;
- case STATE_SSL_CONNECT:
+ case STATE_GENERATE_SERVER_AUTH_TOKEN:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.ssl_connect", request_, request_->url.spec());
- rv = DoSSLConnect();
+ rv = DoGenerateServerAuthToken();
break;
- case STATE_SSL_CONNECT_COMPLETE:
- rv = DoSSLConnectComplete(rv);
- TRACE_EVENT_END("http.ssl_connect", request_, request_->url.spec());
+ case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
+ rv = DoGenerateServerAuthTokenComplete(rv);
break;
case STATE_SEND_REQUEST:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.send_request", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
+ net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, NULL);
rv = DoSendRequest();
break;
case STATE_SEND_REQUEST_COMPLETE:
rv = DoSendRequestComplete(rv);
- TRACE_EVENT_END("http.send_request", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
+ net_log_.EndEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, NULL);
break;
case STATE_READ_HEADERS:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.read_headers", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
+ net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, NULL);
rv = DoReadHeaders();
break;
case STATE_READ_HEADERS_COMPLETE:
rv = DoReadHeadersComplete(rv);
- TRACE_EVENT_END("http.read_headers", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
+ net_log_.EndEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, NULL);
break;
case STATE_READ_BODY:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.read_body", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_READ_BODY);
+ net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, NULL);
rv = DoReadBody();
break;
case STATE_READ_BODY_COMPLETE:
rv = DoReadBodyComplete(rv);
- TRACE_EVENT_END("http.read_body", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_READ_BODY);
+ net_log_.EndEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, NULL);
break;
case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.drain_body_for_auth_restart",
- request_, request_->url.spec());
- LoadLog::BeginEvent(
- load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
+ net_log_.BeginEvent(
+ NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, NULL);
rv = DoDrainBodyForAuthRestart();
break;
case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
rv = DoDrainBodyForAuthRestartComplete(rv);
- TRACE_EVENT_END("http.drain_body_for_auth_restart",
- request_, request_->url.spec());
- LoadLog::EndEvent(
- load_log_,
- LoadLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
+ net_log_.EndEvent(
+ NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, NULL);
+ break;
+ case STATE_SPDY_GET_STREAM:
+ DCHECK_EQ(OK, rv);
+ rv = DoSpdyGetStream();
+ break;
+ case STATE_SPDY_GET_STREAM_COMPLETE:
+ rv = DoSpdyGetStreamComplete(rv);
break;
case STATE_SPDY_SEND_REQUEST:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.send_request", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_SEND_REQUEST);
+ net_log_.BeginEvent(NetLog::TYPE_SPDY_TRANSACTION_SEND_REQUEST, NULL);
rv = DoSpdySendRequest();
break;
case STATE_SPDY_SEND_REQUEST_COMPLETE:
rv = DoSpdySendRequestComplete(rv);
- TRACE_EVENT_END("http.send_request", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_SEND_REQUEST);
+ net_log_.EndEvent(NetLog::TYPE_SPDY_TRANSACTION_SEND_REQUEST, NULL);
break;
case STATE_SPDY_READ_HEADERS:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.read_headers", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_READ_HEADERS);
+ net_log_.BeginEvent(NetLog::TYPE_SPDY_TRANSACTION_READ_HEADERS, NULL);
rv = DoSpdyReadHeaders();
break;
case STATE_SPDY_READ_HEADERS_COMPLETE:
rv = DoSpdyReadHeadersComplete(rv);
- TRACE_EVENT_END("http.read_headers", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_READ_HEADERS);
+ net_log_.EndEvent(NetLog::TYPE_SPDY_TRANSACTION_READ_HEADERS, NULL);
break;
case STATE_SPDY_READ_BODY:
DCHECK_EQ(OK, rv);
- TRACE_EVENT_BEGIN("http.read_body", request_, request_->url.spec());
- LoadLog::BeginEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_READ_BODY);
+ net_log_.BeginEvent(NetLog::TYPE_SPDY_TRANSACTION_READ_BODY, NULL);
rv = DoSpdyReadBody();
break;
case STATE_SPDY_READ_BODY_COMPLETE:
rv = DoSpdyReadBodyComplete(rv);
- TRACE_EVENT_END("http.read_body", request_, request_->url.spec());
- LoadLog::EndEvent(load_log_,
- LoadLog::TYPE_FLIP_TRANSACTION_READ_BODY);
+ net_log_.EndEvent(NetLog::TYPE_SPDY_TRANSACTION_READ_BODY, NULL);
break;
default:
NOTREACHED() << "bad state";
@@ -566,57 +618,73 @@ int HttpNetworkTransaction::DoResolveProxy() {
next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
+ // |endpoint_| indicates the final destination endpoint.
+ endpoint_ = HostPortPair(request_->url.HostNoBrackets(),
+ request_->url.EffectiveIntPort());
+
+ // Extra URL we might be attempting to resolve to.
+ GURL alternate_endpoint_url;
+
+ // Tracks whether we are using |request_->url| or |alternate_endpoint_url|.
+ const GURL *curr_endpoint_url = &request_->url;
+
+ if (g_host_mapping_rules && g_host_mapping_rules->RewriteHost(&endpoint_)) {
+ url_canon::Replacements<char> replacements;
+ const std::string port_str = IntToString(endpoint_.port);
+ replacements.SetPort(port_str.c_str(),
+ url_parse::Component(0, port_str.size()));
+ replacements.SetHost(endpoint_.host.c_str(),
+ url_parse::Component(0, endpoint_.host.size()));
+ alternate_endpoint_url = curr_endpoint_url->ReplaceComponents(replacements);
+ curr_endpoint_url = &alternate_endpoint_url;
+ }
+
+ const HttpAlternateProtocols& alternate_protocols =
+ session_->alternate_protocols();
+ if (alternate_protocols.HasAlternateProtocolFor(endpoint_)) {
+ response_.was_alternate_protocol_available = true;
+ if (alternate_protocol_mode_ == kUnspecified) {
+ HttpAlternateProtocols::PortProtocolPair alternate =
+ alternate_protocols.GetAlternateProtocolFor(endpoint_);
+ if (alternate.protocol != HttpAlternateProtocols::BROKEN) {
+ DCHECK_EQ(HttpAlternateProtocols::NPN_SPDY_1, alternate.protocol);
+ endpoint_.port = alternate.port;
+ alternate_protocol_ = HttpAlternateProtocols::NPN_SPDY_1;
+ alternate_protocol_mode_ = kUsingAlternateProtocol;
+
+ url_canon::Replacements<char> replacements;
+ replacements.SetScheme("https",
+ url_parse::Component(0, strlen("https")));
+ const std::string port_str = IntToString(endpoint_.port);
+ replacements.SetPort(port_str.c_str(),
+ url_parse::Component(0, port_str.size()));
+ alternate_endpoint_url =
+ curr_endpoint_url->ReplaceComponents(replacements);
+ curr_endpoint_url = &alternate_endpoint_url;
+ }
+ }
+ }
+
if (request_->load_flags & LOAD_BYPASS_PROXY) {
proxy_info_.UseDirect();
return OK;
}
return session_->proxy_service()->ResolveProxy(
- request_->url, &proxy_info_, &io_callback_, &pac_request_, load_log_);
+ *curr_endpoint_url, &proxy_info_, &io_callback_, &pac_request_, net_log_);
}
int HttpNetworkTransaction::DoResolveProxyComplete(int result) {
-
pac_request_ = NULL;
- if (result != OK) {
- DLOG(ERROR) << "Failed to resolve proxy: " << result;
- // Fall-back to direct when there were runtime errors in the PAC script,
- // or some other failure with the settings.
- proxy_info_.UseDirect();
- }
+ if (result != OK)
+ return result;
// Remove unsupported proxies from the list.
proxy_info_.RemoveProxiesWithoutScheme(
ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
- // There are four possible outcomes of having run the ProxyService:
- // (1) The ProxyService decided we should connect through a proxy.
- // (2) The ProxyService decided we should direct-connect.
- // (3) The ProxyService decided we should give up, as there are no more
- // proxies to try (this is more likely to happen during
- // ReconsiderProxyAfterError()).
- // (4) The ProxyService failed (which can happen if the PAC script
- // we were configured with threw a runtime exception).
- //
- // It is important that we fail the connection in case (3) rather than
- // falling-back to a direct connection, since sending traffic through
- // a proxy may be integral to the user's privacy/security model.
- //
- // For example if a user had configured traffic to go through the TOR
- // anonymizing proxy to protect their privacy, it would be bad if we
- // silently fell-back to direct connect if the proxy server were to
- // become unreachable.
- //
- // In case (4) it is less obvious what the right thing to do is. On the
- // one hand, for consistency it would be natural to hard-fail as well.
- // However, both Firefox 3.5 and Internet Explorer 8 will silently fall-back
- // to DIRECT in this case, so we will do the same for compatibility.
- //
- // For more information, see:
- // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
-
if (proxy_info_.is_empty()) {
// No proxies/direct to choose from. This happens when we don't support any
// of the proxies in the returned list.
@@ -630,269 +698,333 @@ int HttpNetworkTransaction::DoResolveProxyComplete(int result) {
int HttpNetworkTransaction::DoInitConnection() {
DCHECK(!connection_->is_initialized());
DCHECK(proxy_info_.proxy_server().is_valid());
-
next_state_ = STATE_INIT_CONNECTION_COMPLETE;
- using_ssl_ = request_->url.SchemeIs("https");
-
- if (proxy_info_.is_direct())
- proxy_mode_ = kDirectConnection;
- else if (proxy_info_.proxy_server().is_socks())
- proxy_mode_ = kSOCKSProxy;
- else if (using_ssl_)
- proxy_mode_ = kHTTPProxyUsingTunnel;
- else
- proxy_mode_ = kHTTPProxy;
-
- // Build the string used to uniquely identify connections of this type.
- // Determine the host and port to connect to.
- std::string connection_group;
- std::string host;
- int port;
- if (proxy_mode_ != kDirectConnection) {
- ProxyServer proxy_server = proxy_info_.proxy_server();
- connection_group = "proxy/" + proxy_server.ToURI() + "/";
- host = proxy_server.HostNoBrackets();
- port = proxy_server.port();
- } else {
- host = request_->url.HostNoBrackets();
- port = request_->url.EffectiveIntPort();
+ // Now that the proxy server has been resolved, create the auth_controllers_.
+ for (int i = 0; i < HttpAuth::AUTH_NUM_TARGETS; i++) {
+ HttpAuth::Target target = static_cast<HttpAuth::Target>(i);
+ if (!auth_controllers_[target].get())
+ auth_controllers_[target] = new HttpAuthController(target,
+ AuthURL(target),
+ session_);
}
+ bool want_spdy = alternate_protocol_mode_ == kUsingAlternateProtocol
+ && alternate_protocol_ == HttpAlternateProtocols::NPN_SPDY_1;
+ using_ssl_ = request_->url.SchemeIs("https") || want_spdy;
+ using_spdy_ = false;
+ response_.was_fetched_via_proxy = !proxy_info_.is_direct();
+
// Use the fixed testing ports if they've been provided.
if (using_ssl_) {
if (session_->fixed_https_port() != 0)
- port = session_->fixed_https_port();
+ endpoint_.port = session_->fixed_https_port();
} else if (session_->fixed_http_port() != 0) {
- port = session_->fixed_http_port();
- }
-
- // For a connection via HTTP proxy not using CONNECT, the connection
- // is to the proxy server only. For all other cases
- // (direct, HTTP proxy CONNECT, SOCKS), the connection is upto the
- // url endpoint. Hence we append the url data into the connection_group.
- if (proxy_mode_ != kHTTPProxy)
- connection_group.append(request_->url.GetOrigin().spec());
-
- DCHECK(!connection_group.empty());
-
- HostResolver::RequestInfo resolve_info(host, port);
- resolve_info.set_priority(request_->priority);
-
- // The referrer is used by the DNS prefetch system to correlate resolutions
- // with the page that triggered them. It doesn't impact the actual addresses
- // that we resolve to.
- resolve_info.set_referrer(request_->referrer);
-
- // If the user is refreshing the page, bypass the host cache.
- if (request_->load_flags & LOAD_BYPASS_CACHE ||
- request_->load_flags & LOAD_DISABLE_CACHE) {
- resolve_info.set_allow_cached_response(false);
+ endpoint_.port = session_->fixed_http_port();
}
- // Check first if we have a flip session for this group. If so, then go
+ // Check first if we have a spdy session for this group. If so, then go
// straight to using that.
- if (session_->flip_session_pool()->HasSession(resolve_info))
+ if (session_->spdy_session_pool()->HasSession(endpoint_)) {
+ using_spdy_ = true;
+ reused_socket_ = true;
+ next_state_ = STATE_SPDY_GET_STREAM;
return OK;
-
- int rv = connection_->Init(connection_group, resolve_info, request_->priority,
- &io_callback_, session_->tcp_socket_pool(),
- load_log_);
- return rv;
-}
-
-int HttpNetworkTransaction::DoInitConnectionComplete(int result) {
- if (result < 0) {
- UpdateConnectionTypeHistograms(CONNECTION_HTTP, false);
- return ReconsiderProxyAfterError(result);
}
- DCHECK_EQ(OK, result);
-
- // If we don't have an initialized connection, that means we have a flip
- // connection waiting for us.
- if (!connection_->is_initialized()) {
- next_state_ = STATE_SPDY_SEND_REQUEST;
- return OK;
- }
+ // Build the string used to uniquely identify connections of this type.
+ // Determine the host and port to connect to.
+ std::string connection_group = endpoint_.ToString();
+ DCHECK(!connection_group.empty());
- LogTCPConnectedMetrics(*connection_);
+ if (using_ssl_)
+ connection_group = StringPrintf("ssl/%s", connection_group.c_str());
- // Set the reused_socket_ flag to indicate that we are using a keep-alive
- // connection. This flag is used to handle errors that occur while we are
- // trying to reuse a keep-alive connection.
- reused_socket_ = connection_->is_reused();
- if (reused_socket_) {
- next_state_ = STATE_SEND_REQUEST;
+ // If the user is refreshing the page, bypass the host cache.
+ bool disable_resolver_cache = request_->load_flags & LOAD_BYPASS_CACHE ||
+ request_->load_flags & LOAD_VALIDATE_CACHE ||
+ request_->load_flags & LOAD_DISABLE_CACHE;
+
+ // Build up the connection parameters.
+ scoped_refptr<TCPSocketParams> tcp_params;
+ scoped_refptr<HttpProxySocketParams> http_proxy_params;
+ scoped_refptr<SOCKSSocketParams> socks_params;
+ scoped_ptr<HostPortPair> proxy_host_port;
+
+ if (proxy_info_.is_direct()) {
+ tcp_params = new TCPSocketParams(endpoint_, request_->priority,
+ request_->referrer,
+ disable_resolver_cache);
} else {
- // Now we have a TCP connected socket. Perform other connection setup as
- // needed.
- UpdateConnectionTypeHistograms(CONNECTION_HTTP, true);
- if (proxy_mode_ == kSOCKSProxy)
- next_state_ = STATE_SOCKS_CONNECT;
- else if (using_ssl_ && proxy_mode_ == kDirectConnection) {
- next_state_ = STATE_SSL_CONNECT;
- } else {
- next_state_ = STATE_SEND_REQUEST;
- if (proxy_mode_ == kHTTPProxyUsingTunnel)
+ ProxyServer proxy_server = proxy_info_.proxy_server();
+ proxy_host_port.reset(new HostPortPair(proxy_server.HostNoBrackets(),
+ proxy_server.port()));
+ scoped_refptr<TCPSocketParams> proxy_tcp_params =
+ new TCPSocketParams(*proxy_host_port, request_->priority,
+ request_->referrer, disable_resolver_cache);
+
+ if (proxy_info_.is_http()) {
+ scoped_refptr<HttpAuthController> http_proxy_auth;
+ if (using_ssl_) {
+ http_proxy_auth = auth_controllers_[HttpAuth::AUTH_PROXY];
establishing_tunnel_ = true;
+ }
+ http_proxy_params = new HttpProxySocketParams(proxy_tcp_params,
+ request_->url, endpoint_,
+ http_proxy_auth,
+ using_ssl_);
+ } else {
+ DCHECK(proxy_info_.is_socks());
+ char socks_version;
+ if (proxy_server.scheme() == ProxyServer::SCHEME_SOCKS5)
+ socks_version = '5';
+ else
+ socks_version = '4';
+ connection_group =
+ StringPrintf("socks%c/%s", socks_version, connection_group.c_str());
+
+ socks_params = new SOCKSSocketParams(proxy_tcp_params,
+ socks_version == '5',
+ endpoint_,
+ request_->priority,
+ request_->referrer);
}
}
- return OK;
-}
+ // Deal with SSL - which layers on top of any given proxy.
+ if (using_ssl_) {
+ if (ContainsKey(*g_tls_intolerant_servers, GetHostAndPort(request_->url))) {
+ LOG(WARNING) << "Falling back to SSLv3 because host is TLS intolerant: "
+ << GetHostAndPort(request_->url);
+ ssl_config_.ssl3_fallback = true;
+ ssl_config_.tls1_enabled = false;
+ }
-int HttpNetworkTransaction::DoSOCKSConnect() {
- DCHECK_EQ(kSOCKSProxy, proxy_mode_);
+ UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLv3Fallback",
+ (int) ssl_config_.ssl3_fallback, 2);
- next_state_ = STATE_SOCKS_CONNECT_COMPLETE;
+ int load_flags = request_->load_flags;
+ if (g_ignore_certificate_errors)
+ load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
+ if (request_->load_flags & LOAD_VERIFY_EV_CERT)
+ ssl_config_.verify_ev_cert = true;
- // Add a SOCKS connection on top of our existing transport socket.
- ClientSocket* s = connection_->release_socket();
- HostResolver::RequestInfo req_info(request_->url.HostNoBrackets(),
- request_->url.EffectiveIntPort());
- req_info.set_referrer(request_->referrer);
- req_info.set_priority(request_->priority);
+ scoped_refptr<SSLSocketParams> ssl_params =
+ new SSLSocketParams(tcp_params, http_proxy_params, socks_params,
+ proxy_info_.proxy_server().scheme(),
+ request_->url.HostNoBrackets(), ssl_config_,
+ load_flags, want_spdy);
- if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5)
- s = new SOCKS5ClientSocket(s, req_info);
- else
- s = new SOCKSClientSocket(s, req_info, session_->host_resolver());
- connection_->set_socket(s);
- return connection_->socket()->Connect(&io_callback_, load_log_);
-}
+ scoped_refptr<SSLClientSocketPool> ssl_pool;
+ if (proxy_info_.is_direct())
+ ssl_pool = session_->ssl_socket_pool();
+ else
+ ssl_pool = session_->GetSocketPoolForSSLWithProxy(*proxy_host_port);
-int HttpNetworkTransaction::DoSOCKSConnectComplete(int result) {
- DCHECK_EQ(kSOCKSProxy, proxy_mode_);
+ return connection_->Init(connection_group, ssl_params, request_->priority,
+ &io_callback_, ssl_pool, net_log_);
+ }
- if (result == OK) {
- if (using_ssl_) {
- next_state_ = STATE_SSL_CONNECT;
- } else {
- next_state_ = STATE_SEND_REQUEST;
- }
- } else {
- result = ReconsiderProxyAfterError(result);
+ // Finally, get the connection started.
+ if (proxy_info_.is_http()) {
+ return connection_->Init(
+ connection_group, http_proxy_params, request_->priority, &io_callback_,
+ session_->GetSocketPoolForHTTPProxy(*proxy_host_port), net_log_);
}
- return result;
+
+ if (proxy_info_.is_socks()) {
+ return connection_->Init(
+ connection_group, socks_params, request_->priority, &io_callback_,
+ session_->GetSocketPoolForSOCKSProxy(*proxy_host_port), net_log_);
+ }
+
+ DCHECK(proxy_info_.is_direct());
+ return connection_->Init(connection_group, tcp_params, request_->priority,
+ &io_callback_, session_->tcp_socket_pool(),
+ net_log_);
}
-int HttpNetworkTransaction::DoSSLConnect() {
- next_state_ = STATE_SSL_CONNECT_COMPLETE;
+int HttpNetworkTransaction::DoInitConnectionComplete(int result) {
+ // |result| may be the result of any of the stacked pools. The following
+ // logic is used when determining how to interpret an error.
+ // If |result| < 0:
+ // and connection_->socket() != NULL, then the SSL handshake ran and it
+ // is a potentially recoverable error.
+ // and connection_->socket == NULL and connection_->is_ssl_error() is true,
+ // then the SSL handshake ran with an unrecoverable error.
+ // otherwise, the error came from one of the other pools.
+ bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
+ connection_->is_ssl_error());
+
+ if (ssl_started && (result == OK || IsCertificateError(result))) {
+ SSLClientSocket* ssl_socket =
+ static_cast<SSLClientSocket*>(connection_->socket());
+ if (ssl_socket->wasNpnNegotiated()) {
+ response_.was_npn_negotiated = true;
+ std::string proto;
+ ssl_socket->GetNextProto(&proto);
+ if (SSLClientSocket::NextProtoFromString(proto) ==
+ SSLClientSocket::kProtoSPDY1)
+ using_spdy_ = true;
+ }
+ }
- if (request_->load_flags & LOAD_VERIFY_EV_CERT)
- ssl_config_.verify_ev_cert = true;
+ if (result == ERR_PROXY_AUTH_REQUESTED) {
+ DCHECK(!ssl_started);
+ const HttpResponseInfo& tunnel_auth_response =
+ connection_->ssl_error_response_info();
- ssl_connect_start_time_ = base::TimeTicks::Now();
+ response_.headers = tunnel_auth_response.headers;
+ response_.auth_challenge = tunnel_auth_response.auth_challenge;
+ headers_valid_ = true;
+ pending_auth_target_ = HttpAuth::AUTH_PROXY;
+ return OK;
+ }
- // Add a SSL socket on top of our existing transport socket.
- ClientSocket* s = connection_->release_socket();
- s = session_->socket_factory()->CreateSSLClientSocket(
- s, request_->url.HostNoBrackets(), ssl_config_);
- connection_->set_socket(s);
- return connection_->socket()->Connect(&io_callback_, load_log_);
-}
+ if ((!ssl_started && result < 0 &&
+ alternate_protocol_mode_ == kUsingAlternateProtocol) ||
+ result == ERR_NPN_NEGOTIATION_FAILED) {
+ // Mark the alternate protocol as broken and fallback.
+ MarkBrokenAlternateProtocolAndFallback();
+ return OK;
+ }
-int HttpNetworkTransaction::DoSSLConnectComplete(int result) {
- SSLClientSocket* ssl_socket =
- reinterpret_cast<SSLClientSocket*>(connection_->socket());
-
- SSLClientSocket::NextProtoStatus status =
- SSLClientSocket::kNextProtoUnsupported;
- std::string proto;
- // GetNextProto will fail and and trigger a NOTREACHED if we pass in a socket
- // that hasn't had SSL_ImportFD called on it. If we get a certificate error
- // here, then we know that we called SSL_ImportFD.
- if (result == OK || IsCertificateError(result))
- status = ssl_socket->GetNextProto(&proto);
- static const char kSpdyProto[] = "spdy";
- const bool use_spdy = (status == SSLClientSocket::kNextProtoNegotiated &&
- proto == kSpdyProto);
+ if (result < 0 && !ssl_started)
+ return ReconsiderProxyAfterError(result);
+ establishing_tunnel_ = false;
+
+ if (connection_->socket()) {
+ LogHttpConnectedMetrics(*connection_);
+
+ // Set the reused_socket_ flag to indicate that we are using a keep-alive
+ // connection. This flag is used to handle errors that occur while we are
+ // trying to reuse a keep-alive connection.
+ reused_socket_ = connection_->is_reused();
+ // TODO(vandebo) should we exclude SPDY in the following if?
+ if (!reused_socket_)
+ UpdateConnectionTypeHistograms(CONNECTION_HTTP);
+
+ if (!using_ssl_) {
+ DCHECK_EQ(OK, result);
+ next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
+ return result;
+ }
+ }
+ // Handle SSL errors below.
+ DCHECK(using_ssl_);
+ DCHECK(ssl_started);
if (IsCertificateError(result)) {
- if (use_spdy) {
- // TODO(agl/willchan/wtc): We currently ignore certificate errors for
- // spdy but we shouldn't. http://crbug.com/32020
+ if (using_spdy_ && request_->url.SchemeIs("http")) {
+ // We ignore certificate errors for http over spdy.
+ spdy_certificate_error_ = result;
result = OK;
} else {
result = HandleCertificateError(result);
+ if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
+ connection_->socket()->Disconnect();
+ connection_->Reset();
+ next_state_ = STATE_INIT_CONNECTION;
+ return result;
+ }
}
}
- if (result == OK) {
- DCHECK(ssl_connect_start_time_ != base::TimeTicks());
- base::TimeDelta connect_duration =
- base::TimeTicks::Now() - ssl_connect_start_time_;
-
- if (use_spdy) {
- UMA_HISTOGRAM_CUSTOM_TIMES("Net.SpdyConnectionLatency",
- connect_duration,
- base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(10),
- 100);
-
- UpdateConnectionTypeHistograms(CONNECTION_SPDY, true);
- next_state_ = STATE_SPDY_SEND_REQUEST;
- } else {
- UMA_HISTOGRAM_CUSTOM_TIMES("Net.SSL_Connection_Latency",
- connect_duration,
- base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(10),
- 100);
+ if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
+ response_.cert_request_info =
+ connection_->ssl_error_response_info().cert_request_info;
+ return HandleCertificateRequest(result);
+ }
+ if (result < 0)
+ return HandleSSLHandshakeError(result);
- next_state_ = STATE_SEND_REQUEST;
- }
- } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
- result = HandleCertificateRequest(result);
+ if (using_spdy_) {
+ UpdateConnectionTypeHistograms(CONNECTION_SPDY);
+ // TODO(cbentzel): Add auth support to spdy. See http://crbug.com/46620
+ next_state_ = STATE_SPDY_GET_STREAM;
} else {
- result = HandleSSLHandshakeError(result);
+ next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
}
- return result;
+ return OK;
+}
+
+int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
+ next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
+ if (!ShouldApplyProxyAuth())
+ return OK;
+ return auth_controllers_[HttpAuth::AUTH_PROXY]->MaybeGenerateAuthToken(
+ request_, &io_callback_, net_log_);
+}
+
+int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
+ DCHECK_NE(ERR_IO_PENDING, rv);
+ if (rv == OK)
+ next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
+ return rv;
+}
+
+int HttpNetworkTransaction::DoGenerateServerAuthToken() {
+ next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE;
+ if (!ShouldApplyServerAuth())
+ return OK;
+ return auth_controllers_[HttpAuth::AUTH_SERVER]->MaybeGenerateAuthToken(
+ request_, &io_callback_, net_log_);
+}
+
+int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
+ DCHECK_NE(ERR_IO_PENDING, rv);
+ if (rv == OK)
+ next_state_ = STATE_SEND_REQUEST;
+ return rv;
}
int HttpNetworkTransaction::DoSendRequest() {
next_state_ = STATE_SEND_REQUEST_COMPLETE;
UploadDataStream* request_body = NULL;
- if (!establishing_tunnel_ && request_->upload_data)
- request_body = new UploadDataStream(request_->upload_data);
+ if (request_->upload_data) {
+ int error_code;
+ request_body = UploadDataStream::Create(request_->upload_data, &error_code);
+ if (!request_body)
+ return error_code;
+ }
// This is constructed lazily (instead of within our Start method), so that
// we have proxy info available.
if (request_headers_.empty()) {
// Figure out if we can/should add Proxy-Authentication & Authentication
// headers.
- bool have_proxy_auth =
- ShouldApplyProxyAuth() &&
- (HaveAuth(HttpAuth::AUTH_PROXY) ||
- SelectPreemptiveAuth(HttpAuth::AUTH_PROXY));
- bool have_server_auth =
- ShouldApplyServerAuth() &&
- (HaveAuth(HttpAuth::AUTH_SERVER) ||
- SelectPreemptiveAuth(HttpAuth::AUTH_SERVER));
-
- std::string authorization_headers;
-
- // TODO(wtc): If BuildAuthorizationHeader fails (returns an authorization
- // header with no credentials), we should return an error to prevent
- // entering an infinite auth restart loop. See http://crbug.com/21050.
+ HttpRequestHeaders authorization_headers;
+ bool have_proxy_auth = (ShouldApplyProxyAuth() &&
+ HaveAuth(HttpAuth::AUTH_PROXY));
+ bool have_server_auth = (ShouldApplyServerAuth() &&
+ HaveAuth(HttpAuth::AUTH_SERVER));
if (have_proxy_auth)
- authorization_headers.append(
- BuildAuthorizationHeader(HttpAuth::AUTH_PROXY));
+ auth_controllers_[HttpAuth::AUTH_PROXY]->AddAuthorizationHeader(
+ &authorization_headers);
if (have_server_auth)
- authorization_headers.append(
- BuildAuthorizationHeader(HttpAuth::AUTH_SERVER));
-
- if (establishing_tunnel_) {
- BuildTunnelRequest(request_, authorization_headers, &request_headers_);
- } else {
- BuildRequestHeaders(request_, authorization_headers, request_body,
- proxy_mode_ == kHTTPProxy, &request_headers_);
+ auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
+ &authorization_headers);
+ std::string request_line;
+ HttpRequestHeaders request_headers;
+ BuildRequestHeaders(request_, authorization_headers, request_body,
+ !using_ssl_ && proxy_info_.is_http(), &request_line,
+ &request_headers);
+
+ if (session_->network_delegate())
+ session_->network_delegate()->OnSendHttpRequest(&request_headers);
+
+ if (net_log_.HasListener()) {
+ net_log_.AddEvent(
+ NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
+ new NetLogHttpRequestParameter(request_line, request_headers));
}
+
+ request_headers_ = request_line + request_headers.ToString();
}
headers_valid_ = false;
- http_stream_.reset(new HttpBasicStream(connection_.get(), load_log_));
+ http_stream_.reset(new HttpBasicStream(connection_.get(), net_log_));
return http_stream_->SendRequest(request_, request_headers_,
request_body, &response_, &io_callback_);
@@ -901,24 +1033,16 @@ int HttpNetworkTransaction::DoSendRequest() {
int HttpNetworkTransaction::DoSendRequestComplete(int result) {
if (result < 0)
return HandleIOError(result);
-
next_state_ = STATE_READ_HEADERS;
-
return OK;
}
int HttpNetworkTransaction::DoReadHeaders() {
next_state_ = STATE_READ_HEADERS_COMPLETE;
-
return http_stream_->ReadResponseHeaders(&io_callback_);
}
int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
- if (establishing_tunnel_) {
- // The connection was closed before the tunnel could be established.
- return ERR_TUNNEL_CONNECTION_FAILED;
- }
-
if (!response_.headers) {
// The connection was closed before any data was sent. Likely an error
// rather than empty HTTP/0.9 response.
@@ -940,9 +1064,30 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
<< " during SSL renegotiation";
result = ERR_CERT_ERROR_IN_SSL_RENEGOTIATION;
} else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
+ response_.cert_request_info = new SSLCertRequestInfo;
+ SSLClientSocket* ssl_socket =
+ static_cast<SSLClientSocket*>(connection_->socket());
+ ssl_socket->GetSSLCertRequestInfo(response_.cert_request_info);
result = HandleCertificateRequest(result);
if (result == OK)
return result;
+ } else if ((result == ERR_SSL_DECOMPRESSION_FAILURE_ALERT ||
+ result == ERR_SSL_BAD_RECORD_MAC_ALERT) &&
+ ssl_config_.tls1_enabled &&
+ !SSLConfigService::IsKnownStrictTLSServer(request_->url.host())){
+ // Some buggy servers select DEFLATE compression when offered and then
+ // fail to ever decompress anything. They will send a fatal alert telling
+ // us this. Normally we would pick this up during the handshake because
+ // our Finished message is compressed and we'll never get the server's
+ // Finished if it fails to process ours.
+ //
+ // However, with False Start, we'll believe that the handshake is
+ // complete as soon as we've /sent/ our Finished message. In this case,
+ // we only find out that the server is buggy here, when we try to read
+ // the initial reply.
+ g_tls_intolerant_servers->insert(GetHostAndPort(request_->url));
+ ResetConnectionAndRequestForResend();
+ return OK;
}
}
@@ -957,26 +1102,23 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
// After we call RestartWithAuth a new response_time will be recorded, and
// we need to be cautious about incorrectly logging the duration across the
// authentication activity.
- if (!logged_response_time) {
- LogTransactionConnectedMetrics();
- logged_response_time = true;
- }
+ LogTransactionConnectedMetrics();
if (result == ERR_CONNECTION_CLOSED) {
+ // For now, if we get at least some data, we do the best we can to make
+ // sense of it and send it back up the stack.
int rv = HandleConnectionClosedBeforeEndOfHeaders();
if (rv != OK)
return rv;
- // TODO(wtc): Traditionally this code has returned 0 when reading a closed
- // socket. That is partially corrected in classes that we call, but
- // callers need to be updated.
- result = 0;
}
- if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
- // Require the "HTTP/1.x" status line for SSL CONNECT.
- if (establishing_tunnel_)
- return ERR_TUNNEL_CONNECTION_FAILED;
+ if (net_log_.HasListener()) {
+ net_log_.AddEvent(
+ NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
+ new NetLogHttpResponseParameter(response_.headers));
+ }
+ if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
// HTTP/0.9 doesn't support the PUT method, so lack of response headers
// indicates a buggy server. See:
// https://bugzilla.mozilla.org/show_bug.cgi?id=193921
@@ -984,44 +1126,6 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
return ERR_METHOD_NOT_SUPPORTED;
}
- if (establishing_tunnel_) {
- switch (response_.headers->response_code()) {
- case 200: // OK
- if (http_stream_->IsMoreDataBuffered()) {
- // The proxy sent extraneous data after the headers.
- return ERR_TUNNEL_CONNECTION_FAILED;
- }
- next_state_ = STATE_SSL_CONNECT;
- // Reset for the real request and response headers.
- request_headers_.clear();
- http_stream_.reset(new HttpBasicStream(connection_.get(), load_log_));
- headers_valid_ = false;
- establishing_tunnel_ = false;
- return OK;
-
- // We aren't able to CONNECT to the remote host through the proxy. We
- // need to be very suspicious about the response because an active network
- // attacker can force us into this state by masquerading as the proxy.
- // The only safe thing to do here is to fail the connection because our
- // client is expecting an SSL protected response.
- // See http://crbug.com/7338.
- case 407: // Proxy Authentication Required
- // We need this status code to allow proxy authentication. Our
- // authentication code is smart enough to avoid being tricked by an
- // active network attacker.
- break;
- default:
- // For all other status codes, we conservatively fail the CONNECT
- // request.
- // We lose something by doing this. We have seen proxy 403, 404, and
- // 501 response bodies that contain a useful error message. For
- // example, Squid uses a 404 response to report the DNS error: "The
- // domain name does not exist."
- LogBlockedTunnelResponse(response_.headers->response_code());
- return ERR_TUNNEL_CONNECTION_FAILED;
- }
- }
-
// Check for an intermediate 100 Continue response. An origin server is
// allowed to send this response even if we didn't ask for it, so we just
// need to skip over it.
@@ -1033,13 +1137,17 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
return OK;
}
+ ProcessAlternateProtocol(*response_.headers,
+ endpoint_,
+ session_->mutable_alternate_protocols());
+
int rv = HandleAuthChallenge();
if (rv != OK)
return rv;
- if (using_ssl_ && !establishing_tunnel_) {
+ if (using_ssl_) {
SSLClientSocket* ssl_socket =
- reinterpret_cast<SSLClientSocket*>(connection_->socket());
+ static_cast<SSLClientSocket*>(connection_->socket());
ssl_socket->GetSSLInfo(&response_.ssl_info);
}
@@ -1059,21 +1167,14 @@ int HttpNetworkTransaction::DoReadBody() {
int HttpNetworkTransaction::DoReadBodyComplete(int result) {
// We are done with the Read call.
- DCHECK(!establishing_tunnel_) <<
- "We should never read a response body of a tunnel.";
-
bool done = false, keep_alive = false;
- if (result < 0) {
- // Error or closed connection while reading the socket.
+ if (result <= 0)
done = true;
- // TODO(wtc): Traditionally this code has returned 0 when reading a closed
- // socket. That is partially corrected in classes that we call, but
- // callers need to be updated.
- if (result == ERR_CONNECTION_CLOSED)
- result = 0;
- } else if (http_stream_->IsResponseBodyComplete()) {
+
+ if (http_stream_->IsResponseBodyComplete()) {
done = true;
- keep_alive = GetResponseHeaders()->IsKeepAlive();
+ if (http_stream_->CanFindEndOfResponse())
+ keep_alive = GetResponseHeaders()->IsKeepAlive();
}
// Clean up connection_->if we are done.
@@ -1126,36 +1227,65 @@ int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
return OK;
}
-int HttpNetworkTransaction::DoSpdySendRequest() {
- next_state_ = STATE_SPDY_SEND_REQUEST_COMPLETE;
- CHECK(!spdy_stream_.get());
+int HttpNetworkTransaction::DoSpdyGetStream() {
+ next_state_ = STATE_SPDY_GET_STREAM_COMPLETE;
+ CHECK(!spdy_http_stream_.get());
// First we get a SPDY session. Theoretically, we've just negotiated one, but
// if one already exists, then screw it, use the existing one! Otherwise,
// use the existing TCP socket.
- HostResolver::RequestInfo req_info(request_->url.HostNoBrackets(),
- request_->url.EffectiveIntPort());
- req_info.set_priority(request_->priority);
- const scoped_refptr<FlipSessionPool> spdy_pool =
- session_->flip_session_pool();
- scoped_refptr<FlipSession> spdy_session;
+ const scoped_refptr<SpdySessionPool> spdy_pool =
+ session_->spdy_session_pool();
+ scoped_refptr<SpdySession> spdy_session;
- if (spdy_pool->HasSession(req_info)) {
- spdy_session = spdy_pool->Get(req_info, session_);
+ if (spdy_pool->HasSession(endpoint_)) {
+ spdy_session = spdy_pool->Get(endpoint_, session_, net_log_);
} else {
- spdy_session = spdy_pool->GetFlipSessionFromSocket(
- req_info, session_, connection_.release());
+ // SPDY is negotiated using the TLS next protocol negotiation (NPN)
+ // extension, so |connection_| must contain an SSLClientSocket.
+ DCHECK(using_ssl_);
+ CHECK(connection_->socket());
+ int error = spdy_pool->GetSpdySessionFromSSLSocket(
+ endpoint_, session_, connection_.release(), net_log_,
+ spdy_certificate_error_, &spdy_session);
+ if (error != OK)
+ return error;
}
CHECK(spdy_session.get());
+ if(spdy_session->IsClosed())
+ return ERR_CONNECTION_CLOSED;
- UploadDataStream* upload_data = request_->upload_data ?
- new UploadDataStream(request_->upload_data) : NULL;
headers_valid_ = false;
- spdy_stream_ = spdy_session->GetOrCreateStream(
- *request_, upload_data, load_log_);
- return spdy_stream_->SendRequest(upload_data, &response_, &io_callback_);
+
+ spdy_http_stream_.reset(new SpdyHttpStream());
+ return spdy_http_stream_->InitializeStream(spdy_session, *request_,
+ net_log_, &io_callback_);
+}
+
+int HttpNetworkTransaction::DoSpdyGetStreamComplete(int result) {
+ if (result < 0)
+ return result;
+
+ next_state_ = STATE_SPDY_SEND_REQUEST;
+ return OK;
+}
+
+int HttpNetworkTransaction::DoSpdySendRequest() {
+ next_state_ = STATE_SPDY_SEND_REQUEST_COMPLETE;
+
+ UploadDataStream* upload_data_stream = NULL;
+ if (request_->upload_data) {
+ int error_code = OK;
+ upload_data_stream = UploadDataStream::Create(request_->upload_data,
+ &error_code);
+ if (!upload_data_stream)
+ return error_code;
+ }
+ spdy_http_stream_->InitializeRequest(base::Time::Now(), upload_data_stream);
+
+ return spdy_http_stream_->SendRequest(&response_, &io_callback_);
}
int HttpNetworkTransaction::DoSpdySendRequestComplete(int result) {
@@ -1168,20 +1298,23 @@ int HttpNetworkTransaction::DoSpdySendRequestComplete(int result) {
int HttpNetworkTransaction::DoSpdyReadHeaders() {
next_state_ = STATE_SPDY_READ_HEADERS_COMPLETE;
- return spdy_stream_->ReadResponseHeaders(&io_callback_);
+ return spdy_http_stream_->ReadResponseHeaders(&io_callback_);
}
int HttpNetworkTransaction::DoSpdyReadHeadersComplete(int result) {
// TODO(willchan): Flesh out the support for HTTP authentication here.
if (result == OK)
headers_valid_ = true;
+
+ LogTransactionConnectedMetrics();
+
return result;
}
int HttpNetworkTransaction::DoSpdyReadBody() {
next_state_ = STATE_SPDY_READ_BODY_COMPLETE;
- return spdy_stream_->ReadResponseBody(
+ return spdy_http_stream_->ReadResponseBody(
read_buf_, read_buf_len_, &io_callback_);
}
@@ -1190,79 +1323,37 @@ int HttpNetworkTransaction::DoSpdyReadBodyComplete(int result) {
read_buf_len_ = 0;
if (result <= 0)
- spdy_stream_ = NULL;
+ spdy_http_stream_.reset();
return result;
}
-void HttpNetworkTransaction::LogTCPConnectedMetrics(
+void HttpNetworkTransaction::LogHttpConnectedMetrics(
const ClientSocketHandle& handle) {
- const base::TimeDelta time_to_obtain_connected_socket =
- base::TimeTicks::Now() - handle.init_time();
-
- static const bool use_late_binding_histogram =
- !FieldTrial::MakeName("", "SocketLateBinding").empty();
-
- if (handle.reuse_type() == ClientSocketHandle::UNUSED) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- "Net.HttpConnectionLatency",
- time_to_obtain_connected_socket,
- base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
- 100);
- }
-
- UMA_HISTOGRAM_ENUMERATION("Net.TCPSocketType", handle.reuse_type(),
- ClientSocketHandle::NUM_TYPES);
-
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_ENUMERATION(
- FieldTrial::MakeName("Net.TCPSocketType", "SocketLateBinding"),
- handle.reuse_type(), ClientSocketHandle::NUM_TYPES);
- }
-
- UMA_HISTOGRAM_CLIPPED_TIMES(
- "Net.TransportSocketRequestTime",
- time_to_obtain_connected_socket,
- base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
- 100);
-
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.TransportSocketRequestTime",
- "SocketLateBinding").data(),
- time_to_obtain_connected_socket,
- base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
- 100);
- }
+ UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
+ ClientSocketHandle::NUM_TYPES);
switch (handle.reuse_type()) {
case ClientSocketHandle::UNUSED:
+ UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
+ handle.setup_time(),
+ base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(10),
+ 100);
break;
case ClientSocketHandle::UNUSED_IDLE:
- UMA_HISTOGRAM_CUSTOM_TIMES(
- "Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
- "SocketLateBinding").data(),
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- }
+ UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
+ handle.idle_time(),
+ base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(6),
+ 100);
break;
case ClientSocketHandle::REUSED_IDLE:
- UMA_HISTOGRAM_CUSTOM_TIMES(
- "Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
- "SocketLateBinding").data(),
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- }
+ UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
+ handle.idle_time(),
+ base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(6),
+ 100);
break;
default:
NOTREACHED();
@@ -1272,18 +1363,8 @@ void HttpNetworkTransaction::LogTCPConnectedMetrics(
void HttpNetworkTransaction::LogIOErrorMetrics(
const ClientSocketHandle& handle) {
- static const bool use_late_binding_histogram =
- !FieldTrial::MakeName("", "SocketLateBinding").empty();
-
UMA_HISTOGRAM_ENUMERATION("Net.IOError_SocketReuseType",
- handle.reuse_type(), ClientSocketHandle::NUM_TYPES);
-
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_ENUMERATION(
- FieldTrial::MakeName("Net.IOError_SocketReuseType",
- "SocketLateBinding"),
- handle.reuse_type(), ClientSocketHandle::NUM_TYPES);
- }
+ handle.reuse_type(), ClientSocketHandle::NUM_TYPES);
switch (handle.reuse_type()) {
case ClientSocketHandle::UNUSED:
@@ -1293,26 +1374,12 @@ void HttpNetworkTransaction::LogIOErrorMetrics(
"Net.SocketIdleTimeOnIOError2_UnusedSocket",
handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMinutes(6), 100);
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.SocketIdleTimeOnIOError2_UnusedSocket",
- "SocketLateBinding").data(),
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- }
break;
case ClientSocketHandle::REUSED_IDLE:
UMA_HISTOGRAM_CUSTOM_TIMES(
"Net.SocketIdleTimeOnIOError2_ReusedSocket",
handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMinutes(6), 100);
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.SocketIdleTimeOnIOError2_ReusedSocket",
- "SocketLateBinding").data(),
- handle.idle_time(), base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(6), 100);
- }
break;
default:
NOTREACHED();
@@ -1320,7 +1387,12 @@ void HttpNetworkTransaction::LogIOErrorMetrics(
}
}
-void HttpNetworkTransaction::LogTransactionConnectedMetrics() const {
+void HttpNetworkTransaction::LogTransactionConnectedMetrics() {
+ if (logged_response_time_)
+ return;
+
+ logged_response_time_ = true;
+
base::TimeDelta total_duration = response_.response_time - start_time_;
UMA_HISTOGRAM_CLIPPED_TIMES(
@@ -1329,24 +1401,40 @@ void HttpNetworkTransaction::LogTransactionConnectedMetrics() const {
base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
100);
- static const bool use_late_binding_histogram =
- !FieldTrial::MakeName("", "SocketLateBinding").empty();
-
- if (use_late_binding_histogram) {
- UMA_HISTOGRAM_CUSTOM_TIMES(
- FieldTrial::MakeName("Net.Transaction_Connected_Under_10",
- "SocketLateBinding").data(),
+ if (!reused_socket_) {
+ UMA_HISTOGRAM_CLIPPED_TIMES(
+ "Net.Transaction_Connected_New",
total_duration,
base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
100);
- }
- if (!reused_socket_) {
+ static bool use_conn_impact_histogram(
+ FieldTrialList::Find("ConnCountImpact") &&
+ !FieldTrialList::Find("ConnCountImpact")->group_name().empty());
+ if (use_conn_impact_histogram) {
UMA_HISTOGRAM_CLIPPED_TIMES(
- "Net.Transaction_Connected_New",
+ FieldTrial::MakeName("Net.Transaction_Connected_New",
+ "ConnCountImpact"),
total_duration,
base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
100);
+ }
+ }
+
+ static bool use_spdy_histogram(FieldTrialList::Find("SpdyImpact") &&
+ !FieldTrialList::Find("SpdyImpact")->group_name().empty());
+ if (use_spdy_histogram && response_.was_npn_negotiated) {
+ UMA_HISTOGRAM_CLIPPED_TIMES(
+ FieldTrial::MakeName("Net.Transaction_Connected_Under_10", "SpdyImpact"),
+ total_duration, base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(10), 100);
+
+ if (!reused_socket_) {
+ UMA_HISTOGRAM_CLIPPED_TIMES(
+ FieldTrial::MakeName("Net.Transaction_Connected_New", "SpdyImpact"),
+ total_duration, base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(10), 100);
+ }
}
// Currently, non-zero priority requests are frame or sub-frame resource
@@ -1369,7 +1457,7 @@ void HttpNetworkTransaction::LogTransactionConnectedMetrics() const {
void HttpNetworkTransaction::LogTransactionMetrics() const {
base::TimeDelta duration = base::Time::Now() -
- response_.request_time;
+ response_.request_time;
if (60 < duration.InMinutes())
return;
@@ -1377,11 +1465,13 @@ void HttpNetworkTransaction::LogTransactionMetrics() const {
UMA_HISTOGRAM_LONG_TIMES("Net.Transaction_Latency", duration);
UMA_HISTOGRAM_CLIPPED_TIMES("Net.Transaction_Latency_Under_10", duration,
- base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
- 100);
+ base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(10),
+ 100);
UMA_HISTOGRAM_CLIPPED_TIMES("Net.Transaction_Latency_Total_Under_10",
- total_duration, base::TimeDelta::FromMilliseconds(1),
- base::TimeDelta::FromMinutes(10), 100);
+ total_duration,
+ base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMinutes(10), 100);
if (!reused_socket_) {
UMA_HISTOGRAM_CLIPPED_TIMES(
"Net.Transaction_Latency_Total_New_Connection_Under_10",
@@ -1390,79 +1480,42 @@ void HttpNetworkTransaction::LogTransactionMetrics() const {
}
}
-void HttpNetworkTransaction::LogBlockedTunnelResponse(
- int response_code) const {
- LOG(WARNING) << "Blocked proxy response with status " << response_code
- << " to CONNECT request for "
- << GetHostAndPort(request_->url) << ".";
-}
-
int HttpNetworkTransaction::HandleCertificateError(int error) {
DCHECK(using_ssl_);
+ DCHECK(IsCertificateError(error));
- const int kCertFlags = LOAD_IGNORE_CERT_COMMON_NAME_INVALID |
- LOAD_IGNORE_CERT_DATE_INVALID |
- LOAD_IGNORE_CERT_AUTHORITY_INVALID |
- LOAD_IGNORE_CERT_WRONG_USAGE;
- if (request_->load_flags & kCertFlags) {
- switch (error) {
- case ERR_CERT_COMMON_NAME_INVALID:
- if (request_->load_flags & LOAD_IGNORE_CERT_COMMON_NAME_INVALID)
- error = OK;
- break;
- case ERR_CERT_DATE_INVALID:
- if (request_->load_flags & LOAD_IGNORE_CERT_DATE_INVALID)
- error = OK;
- break;
- case ERR_CERT_AUTHORITY_INVALID:
- if (request_->load_flags & LOAD_IGNORE_CERT_AUTHORITY_INVALID)
- error = OK;
- break;
- }
- }
-
- if (error != OK) {
- SSLClientSocket* ssl_socket =
- reinterpret_cast<SSLClientSocket*>(connection_->socket());
- ssl_socket->GetSSLInfo(&response_.ssl_info);
-
- // Add the bad certificate to the set of allowed certificates in the
- // SSL info object. This data structure will be consulted after calling
- // RestartIgnoringLastError(). And the user will be asked interactively
- // before RestartIgnoringLastError() is ever called.
- SSLConfig::CertAndStatus bad_cert;
- bad_cert.cert = response_.ssl_info.cert;
- bad_cert.cert_status = response_.ssl_info.cert_status;
- ssl_config_.allowed_bad_certs.push_back(bad_cert);
- }
+ SSLClientSocket* ssl_socket =
+ static_cast<SSLClientSocket*>(connection_->socket());
+ ssl_socket->GetSSLInfo(&response_.ssl_info);
+
+ // Add the bad certificate to the set of allowed certificates in the
+ // SSL info object. This data structure will be consulted after calling
+ // RestartIgnoringLastError(). And the user will be asked interactively
+ // before RestartIgnoringLastError() is ever called.
+ SSLConfig::CertAndStatus bad_cert;
+ bad_cert.cert = response_.ssl_info.cert;
+ bad_cert.cert_status = response_.ssl_info.cert_status;
+ ssl_config_.allowed_bad_certs.push_back(bad_cert);
+
+ int load_flags = request_->load_flags;
+ if (g_ignore_certificate_errors)
+ load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
+ if (ssl_socket->IgnoreCertError(error, load_flags))
+ return OK;
return error;
}
int HttpNetworkTransaction::HandleCertificateRequest(int error) {
- // Assert that the socket did not send a client certificate.
- // Note: If we got a reused socket, it was created with some other
- // transaction's ssl_config_, so we need to disable this assertion. We can
- // get a certificate request on a reused socket when the server requested
- // renegotiation (rehandshake).
- // TODO(wtc): add a GetSSLParams method to SSLClientSocket so we can query
- // the SSL parameters it was created with and get rid of the reused_socket_
- // test.
- DCHECK(reused_socket_ || !ssl_config_.send_client_cert);
-
- response_.cert_request_info = new SSLCertRequestInfo;
- SSLClientSocket* ssl_socket =
- reinterpret_cast<SSLClientSocket*>(connection_->socket());
- ssl_socket->GetSSLCertRequestInfo(response_.cert_request_info);
-
// Close the connection while the user is selecting a certificate to send
// to the server.
- connection_->socket()->Disconnect();
+ if (connection_->socket())
+ connection_->socket()->Disconnect();
connection_->Reset();
// If the user selected one of the certificate in client_certs for this
// server before, use it automatically.
X509Certificate* client_cert = session_->ssl_client_auth_cache()->
- Lookup(GetHostAndPort(request_->url));
+ Lookup(GetHostAndPort(request_->url));
if (client_cert) {
const std::vector<scoped_refptr<X509Certificate> >& client_certs =
response_.cert_request_info->client_certs;
@@ -1483,21 +1536,23 @@ int HttpNetworkTransaction::HandleCertificateRequest(int error) {
int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
if (ssl_config_.send_client_cert &&
- (error == ERR_SSL_PROTOCOL_ERROR ||
- error == ERR_BAD_SSL_CLIENT_AUTH_CERT)) {
+ (error == ERR_SSL_PROTOCOL_ERROR ||
+ error == ERR_BAD_SSL_CLIENT_AUTH_CERT)) {
session_->ssl_client_auth_cache()->Remove(GetHostAndPort(request_->url));
}
switch (error) {
case ERR_SSL_PROTOCOL_ERROR:
case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
- if (ssl_config_.tls1_enabled) {
- // This could be a TLS-intolerant server or an SSL 3.0 server that
- // chose a TLS-only cipher suite. Turn off TLS 1.0 and retry.
- ssl_config_.tls1_enabled = false;
- connection_->socket()->Disconnect();
- connection_->Reset();
- next_state_ = STATE_INIT_CONNECTION;
+ case ERR_SSL_DECOMPRESSION_FAILURE_ALERT:
+ case ERR_SSL_BAD_RECORD_MAC_ALERT:
+ if (ssl_config_.tls1_enabled &&
+ !SSLConfigService::IsKnownStrictTLSServer(request_->url.host())) {
+ // This could be a TLS-intolerant server, an SSL 3.0 server that
+ // chose a TLS-only cipher suite or a server with buggy DEFLATE
+ // support. Turn off TLS 1.0, DEFLATE support and retry.
+ g_tls_intolerant_servers->insert(GetHostAndPort(request_->url));
+ ResetConnectionAndRequestForResend();
error = OK;
}
break;
@@ -1546,8 +1601,7 @@ bool HttpNetworkTransaction::ShouldResendRequest(int error) const {
// NOTE: we resend a request only if we reused a keep-alive connection.
// This automatically prevents an infinite resend loop because we'll run
// out of the cached keep-alive connections eventually.
- if (establishing_tunnel_ ||
- !connection_->ShouldResendFailedRequest(error) ||
+ if (!connection_->ShouldResendFailedRequest(error) ||
GetResponseHeaders()) { // We have received some response headers.
return false;
}
@@ -1555,11 +1609,13 @@ bool HttpNetworkTransaction::ShouldResendRequest(int error) const {
}
void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
- connection_->socket()->Disconnect();
+ if (connection_->socket())
+ connection_->socket()->Disconnect();
connection_->Reset();
// We need to clear request_headers_ because it contains the real request
// headers, but we may need to resend the CONNECT request first to recreate
// the SSL tunnel.
+
request_headers_.clear();
next_state_ = STATE_INIT_CONNECTION; // Resend the request.
}
@@ -1585,7 +1641,18 @@ int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
case ERR_CONNECTION_ABORTED:
case ERR_TIMED_OUT:
case ERR_TUNNEL_CONNECTION_FAILED:
+ case ERR_SOCKS_CONNECTION_FAILED:
break;
+ case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
+ // Remap the SOCKS-specific "host unreachable" error to a more
+ // generic error code (this way consumers like the link doctor
+ // know to substitute their error page).
+ //
+ // Note that if the host resolving was done by the SOCSK5 proxy, we can't
+ // differentiate between a proxy-side "host not found" versus a proxy-side
+ // "address unreachable" error, and will report both of these failures as
+ // ERR_ADDRESS_UNREACHABLE.
+ return ERR_ADDRESS_UNREACHABLE;
default:
return error;
}
@@ -1595,7 +1662,7 @@ int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
}
int rv = session_->proxy_service()->ReconsiderProxyAfterError(
- request_->url, &proxy_info_, &io_callback_, &pac_request_, load_log_);
+ request_->url, &proxy_info_, &io_callback_, &pac_request_, net_log_);
if (rv == OK || rv == ERR_IO_PENDING) {
// If the error was during connection setup, there is no socket to
// disconnect.
@@ -1615,178 +1682,11 @@ int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
}
bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
- return (proxy_mode_ == kHTTPProxy) || establishing_tunnel_;
+ return !using_ssl_ && proxy_info_.is_http();
}
bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
- return !establishing_tunnel_ &&
- !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA);
-}
-
-std::string HttpNetworkTransaction::BuildAuthorizationHeader(
- HttpAuth::Target target) const {
- DCHECK(HaveAuth(target));
-
- // Add a Authorization/Proxy-Authorization header line.
- std::string credentials = auth_handler_[target]->GenerateCredentials(
- auth_identity_[target].username,
- auth_identity_[target].password,
- request_,
- &proxy_info_);
-
- return HttpAuth::GetAuthorizationHeaderName(target) +
- ": " + credentials + "\r\n";
-}
-
-GURL HttpNetworkTransaction::AuthOrigin(HttpAuth::Target target) const {
- return target == HttpAuth::AUTH_PROXY ?
- GURL("http://" + proxy_info_.proxy_server().host_and_port()) :
- request_->url.GetOrigin();
-}
-
-std::string HttpNetworkTransaction::AuthPath(HttpAuth::Target target)
- const {
- // Proxy authentication realms apply to all paths. So we will use
- // empty string in place of an absolute path.
- return target == HttpAuth::AUTH_PROXY ?
- std::string() : request_->url.path();
-}
-
-// static
-std::string HttpNetworkTransaction::AuthTargetString(
- HttpAuth::Target target) {
- return target == HttpAuth::AUTH_PROXY ? "proxy" : "server";
-}
-
-void HttpNetworkTransaction::InvalidateRejectedAuthFromCache(
- HttpAuth::Target target,
- const GURL& auth_origin) {
- DCHECK(HaveAuth(target));
-
- // TODO(eroman): this short-circuit can be relaxed. If the realm of
- // the preemptively used auth entry matches the realm of the subsequent
- // challenge, then we can invalidate the preemptively used entry.
- // Otherwise as-is we may send the failed credentials one extra time.
- if (auth_identity_[target].source == HttpAuth::IDENT_SRC_PATH_LOOKUP)
- return;
-
- // Clear the cache entry for the identity we just failed on.
- // Note: we require the username/password to match before invalidating
- // since the entry in the cache may be newer than what we used last time.
- session_->auth_cache()->Remove(auth_origin,
- auth_handler_[target]->realm(),
- auth_identity_[target].username,
- auth_identity_[target].password);
-}
-
-bool HttpNetworkTransaction::SelectPreemptiveAuth(HttpAuth::Target target) {
- DCHECK(!HaveAuth(target));
-
- // Don't do preemptive authorization if the URL contains a username/password,
- // since we must first be challenged in order to use the URL's identity.
- if (request_->url.has_username())
- return false;
-
- // SelectPreemptiveAuth() is on the critical path for each request, so it
- // is expected to be fast. LookupByPath() is fast in the common case, since
- // the number of http auth cache entries is expected to be very small.
- // (For most users in fact, it will be 0.)
-
- HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByPath(
- AuthOrigin(target), AuthPath(target));
-
- // We don't support preemptive authentication for connection-based
- // authentication schemes because they can't reuse entry->handler().
- // Hopefully we can remove this limitation in the future.
- if (entry && !entry->handler()->is_connection_based()) {
- auth_identity_[target].source = HttpAuth::IDENT_SRC_PATH_LOOKUP;
- auth_identity_[target].invalid = false;
- auth_identity_[target].username = entry->username();
- auth_identity_[target].password = entry->password();
- auth_handler_[target] = entry->handler();
- return true;
- }
- return false;
-}
-
-bool HttpNetworkTransaction::SelectNextAuthIdentityToTry(
- HttpAuth::Target target,
- const GURL& auth_origin) {
- DCHECK(auth_handler_[target]);
- DCHECK(auth_identity_[target].invalid);
-
- // Try to use the username/password encoded into the URL first.
- if (target == HttpAuth::AUTH_SERVER && request_->url.has_username() &&
- !embedded_identity_used_) {
- auth_identity_[target].source = HttpAuth::IDENT_SRC_URL;
- auth_identity_[target].invalid = false;
- // Extract the username:password from the URL.
- GetIdentityFromURL(request_->url,
- &auth_identity_[target].username,
- &auth_identity_[target].password);
- embedded_identity_used_ = true;
- // TODO(eroman): If the password is blank, should we also try combining
- // with a password from the cache?
- return true;
- }
-
- // Check the auth cache for a realm entry.
- HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByRealm(
- auth_origin, auth_handler_[target]->realm());
-
- if (entry) {
- // Disallow re-using of identity if the scheme of the originating challenge
- // does not match. This protects against the following situation:
- // 1. Browser prompts user to sign into DIGEST realm="Foo".
- // 2. Since the auth-scheme is not BASIC, the user is reasured that it
- // will not be sent over the wire in clear text. So they use their
- // most trusted password.
- // 3. Next, the browser receives a challenge for BASIC realm="Foo". This
- // is the same realm that we have a cached identity for. However if
- // we use that identity, it would get sent over the wire in
- // clear text (which isn't what the user agreed to when entering it).
- if (entry->handler()->scheme() != auth_handler_[target]->scheme()) {
- LOG(WARNING) << "The scheme of realm " << auth_handler_[target]->realm()
- << " has changed from " << entry->handler()->scheme()
- << " to " << auth_handler_[target]->scheme();
- return false;
- }
-
- auth_identity_[target].source = HttpAuth::IDENT_SRC_REALM_LOOKUP;
- auth_identity_[target].invalid = false;
- auth_identity_[target].username = entry->username();
- auth_identity_[target].password = entry->password();
- return true;
- }
- return false;
-}
-
-std::string HttpNetworkTransaction::AuthChallengeLogMessage() const {
- std::string msg;
- std::string header_val;
- void* iter = NULL;
- scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
- while (headers->EnumerateHeader(&iter, "proxy-authenticate", &header_val)) {
- msg.append("\n Has header Proxy-Authenticate: ");
- msg.append(header_val);
- }
-
- iter = NULL;
- while (headers->EnumerateHeader(&iter, "www-authenticate", &header_val)) {
- msg.append("\n Has header WWW-Authenticate: ");
- msg.append(header_val);
- }
-
- // RFC 4559 requires that a proxy indicate its support of NTLM/Negotiate
- // authentication with a "Proxy-Support: Session-Based-Authentication"
- // response header.
- iter = NULL;
- while (headers->EnumerateHeader(&iter, "proxy-support", &header_val)) {
- msg.append("\n Has header Proxy-Support: ");
- msg.append(header_val);
- }
-
- return msg;
+ return !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA);
}
int HttpNetworkTransaction::HandleAuthChallenge() {
@@ -1797,91 +1697,99 @@ int HttpNetworkTransaction::HandleAuthChallenge() {
if (status != 401 && status != 407)
return OK;
HttpAuth::Target target = status == 407 ?
- HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
- GURL auth_origin = AuthOrigin(target);
-
- LOG(INFO) << "The " << AuthTargetString(target) << " "
- << auth_origin << " requested auth"
- << AuthChallengeLogMessage();
-
+ HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
return ERR_UNEXPECTED_PROXY_AUTH;
- // The auth we tried just failed, hence it can't be valid. Remove it from
- // the cache so it won't be used again.
- // TODO(wtc): IsFinalRound is not the right condition. In a multi-round
- // auth sequence, the server may fail the auth in round 1 if our first
- // authorization header is broken. We should inspect response_.headers to
- // determine if the server already failed the auth or wants us to continue.
- // See http://crbug.com/21015.
- if (HaveAuth(target) && auth_handler_[target]->IsFinalRound()) {
- InvalidateRejectedAuthFromCache(target, auth_origin);
- auth_handler_[target] = NULL;
- auth_identity_[target] = HttpAuth::Identity();
- }
-
- auth_identity_[target].invalid = true;
-
- if (target != HttpAuth::AUTH_SERVER ||
- !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA)) {
- // Find the best authentication challenge that we support.
- HttpAuth::ChooseBestChallenge(headers, target, auth_origin,
- &auth_handler_[target]);
- }
-
- if (!auth_handler_[target]) {
- if (establishing_tunnel_) {
- LOG(ERROR) << "Can't perform auth to the " << AuthTargetString(target)
- << " " << auth_origin << " when establishing a tunnel"
- << AuthChallengeLogMessage();
-
- // We are establishing a tunnel, we can't show the error page because an
- // active network attacker could control its contents. Instead, we just
- // fail to establish the tunnel.
- DCHECK(target == HttpAuth::AUTH_PROXY);
- return ERR_PROXY_AUTH_REQUESTED;
- }
- // We found no supported challenge -- let the transaction continue
- // so we end up displaying the error page.
- return OK;
- }
+ int rv = auth_controllers_[target]->HandleAuthChallenge(
+ headers, (request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA) != 0, false,
+ net_log_);
+ if (auth_controllers_[target]->HaveAuthHandler())
+ pending_auth_target_ = target;
- if (auth_handler_[target]->NeedsIdentity()) {
- // Pick a new auth identity to try, by looking to the URL and auth cache.
- // If an identity to try is found, it is saved to auth_identity_[target].
- SelectNextAuthIdentityToTry(target, auth_origin);
- } else {
- // Proceed with the existing identity or a null identity.
- //
- // TODO(wtc): Add a safeguard against infinite transaction restarts, if
- // the server keeps returning "NTLM".
- auth_identity_[target].invalid = false;
- }
+ scoped_refptr<AuthChallengeInfo> auth_info =
+ auth_controllers_[target]->auth_info();
+ if (auth_info.get())
+ response_.auth_challenge = auth_info;
- // Make a note that we are waiting for auth. This variable is inspected
- // when the client calls RestartWithAuth() to pick up where we left off.
- pending_auth_target_ = target;
+ return rv;
+}
- if (auth_identity_[target].invalid) {
- // We have exhausted all identity possibilities, all we can do now is
- // pass the challenge information back to the client.
- PopulateAuthChallenge(target, auth_origin);
+GURL HttpNetworkTransaction::AuthURL(HttpAuth::Target target) const {
+ switch (target) {
+ case HttpAuth::AUTH_PROXY:
+ if (!proxy_info_.proxy_server().is_valid() ||
+ proxy_info_.proxy_server().is_direct()) {
+ return GURL(); // There is no proxy server.
+ }
+ return GURL("http://" + proxy_info_.proxy_server().host_and_port());
+ case HttpAuth::AUTH_SERVER:
+ return request_->url;
+ default:
+ return GURL();
}
- return OK;
}
-void HttpNetworkTransaction::PopulateAuthChallenge(HttpAuth::Target target,
- const GURL& auth_origin) {
- // Populates response_.auth_challenge with the authentication challenge info.
- // This info is consumed by URLRequestHttpJob::GetAuthChallengeInfo().
+void HttpNetworkTransaction::MarkBrokenAlternateProtocolAndFallback() {
+ // We have to:
+ // * Reset the endpoint to be the unmodified URL specified destination.
+ // * Mark the endpoint as broken so we don't try again.
+ // * Set the alternate protocol mode to kDoNotUseAlternateProtocol so we
+ // ignore future Alternate-Protocol headers from the HostPortPair.
+ // * Reset the connection and go back to STATE_INIT_CONNECTION.
+
+ endpoint_ = HostPortPair(request_->url.HostNoBrackets(),
+ request_->url.EffectiveIntPort());
- AuthChallengeInfo* auth_info = new AuthChallengeInfo;
- auth_info->is_proxy = target == HttpAuth::AUTH_PROXY;
- auth_info->host_and_port = ASCIIToWide(GetHostAndPort(auth_origin));
- auth_info->scheme = ASCIIToWide(auth_handler_[target]->scheme());
- // TODO(eroman): decode realm according to RFC 2047.
- auth_info->realm = ASCIIToWide(auth_handler_[target]->realm());
- response_.auth_challenge = auth_info;
+ session_->mutable_alternate_protocols()->MarkBrokenAlternateProtocolFor(
+ endpoint_);
+
+ alternate_protocol_mode_ = kDoNotUseAlternateProtocol;
+ if (connection_->socket())
+ connection_->socket()->Disconnect();
+ connection_->Reset();
+ next_state_ = STATE_INIT_CONNECTION;
+}
+
+#define STATE_CASE(s) case s: \
+ description = StringPrintf("%s (0x%08X)", #s, s); \
+ break
+
+std::string HttpNetworkTransaction::DescribeState(State state) {
+ std::string description;
+ switch (state) {
+ STATE_CASE(STATE_RESOLVE_PROXY);
+ STATE_CASE(STATE_RESOLVE_PROXY_COMPLETE);
+ STATE_CASE(STATE_INIT_CONNECTION);
+ STATE_CASE(STATE_INIT_CONNECTION_COMPLETE);
+ STATE_CASE(STATE_GENERATE_PROXY_AUTH_TOKEN);
+ STATE_CASE(STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE);
+ STATE_CASE(STATE_GENERATE_SERVER_AUTH_TOKEN);
+ STATE_CASE(STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE);
+ STATE_CASE(STATE_SEND_REQUEST);
+ STATE_CASE(STATE_SEND_REQUEST_COMPLETE);
+ STATE_CASE(STATE_READ_HEADERS);
+ STATE_CASE(STATE_READ_HEADERS_COMPLETE);
+ STATE_CASE(STATE_READ_BODY);
+ STATE_CASE(STATE_READ_BODY_COMPLETE);
+ STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART);
+ STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE);
+ STATE_CASE(STATE_SPDY_GET_STREAM);
+ STATE_CASE(STATE_SPDY_GET_STREAM_COMPLETE);
+ STATE_CASE(STATE_SPDY_SEND_REQUEST);
+ STATE_CASE(STATE_SPDY_SEND_REQUEST_COMPLETE);
+ STATE_CASE(STATE_SPDY_READ_HEADERS);
+ STATE_CASE(STATE_SPDY_READ_HEADERS_COMPLETE);
+ STATE_CASE(STATE_SPDY_READ_BODY);
+ STATE_CASE(STATE_SPDY_READ_BODY_COMPLETE);
+ STATE_CASE(STATE_NONE);
+ default:
+ description = StringPrintf("Unknown state 0x%08X (%u)", state, state);
+ break;
+ }
+ return description;
}
+#undef STATE_CASE
+
} // namespace net