blob: bcd52058b992bc87d313fad50c739d90cd8c8c3a [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit586acc5fe2008-07-26 22:42:524
5#include "net/http/http_network_transaction.h"
6
[email protected]c3b35c22008-09-27 03:19:427#include "base/scoped_ptr.h"
[email protected]68bf9152008-09-25 19:47:308#include "base/compiler_specific.h"
initial.commit586acc5fe2008-07-26 22:42:529#include "base/string_util.h"
[email protected]113ab132008-09-18 20:42:5510#include "base/trace_event.h"
[email protected]68bf9152008-09-25 19:47:3011#include "build/build_config.h"
initial.commit586acc5fe2008-07-26 22:42:5212#include "net/base/client_socket_factory.h"
[email protected]5d0153c512009-01-12 19:08:3613#include "net/base/connection_type_histograms.h"
[email protected]8947da62008-10-24 19:11:1014#include "net/base/dns_resolution_observer.h"
initial.commit586acc5fe2008-07-26 22:42:5215#include "net/base/host_resolver.h"
[email protected]74a85ce2009-02-12 00:03:1916#include "net/base/io_buffer.h"
initial.commit586acc5fe2008-07-26 22:42:5217#include "net/base/load_flags.h"
[email protected]c3b35c22008-09-27 03:19:4218#include "net/base/net_util.h"
[email protected]4628a2a2008-08-14 20:33:2519#include "net/base/ssl_client_socket.h"
initial.commit586acc5fe2008-07-26 22:42:5220#include "net/base/upload_data_stream.h"
[email protected]c3b35c22008-09-27 03:19:4221#include "net/http/http_auth.h"
22#include "net/http/http_auth_handler.h"
initial.commit586acc5fe2008-07-26 22:42:5223#include "net/http/http_chunked_decoder.h"
24#include "net/http/http_network_session.h"
25#include "net/http/http_request_info.h"
[email protected]319d9e6f2009-02-18 19:47:2126#include "net/http/http_response_headers.h"
initial.commit586acc5fe2008-07-26 22:42:5227#include "net/http/http_util.h"
28
[email protected]e1acf6f2008-10-27 20:43:3329using base::Time;
30
initial.commit586acc5fe2008-07-26 22:42:5231namespace net {
32
33//-----------------------------------------------------------------------------
34
initial.commit586acc5fe2008-07-26 22:42:5235HttpNetworkTransaction::HttpNetworkTransaction(HttpNetworkSession* session,
36 ClientSocketFactory* csf)
[email protected]68bf9152008-09-25 19:47:3037 : ALLOW_THIS_IN_INITIALIZER_LIST(
38 io_callback_(this, &HttpNetworkTransaction::OnIOComplete)),
initial.commit586acc5fe2008-07-26 22:42:5239 user_callback_(NULL),
40 session_(session),
41 request_(NULL),
42 pac_request_(NULL),
43 socket_factory_(csf),
[email protected]e1e06262008-08-06 23:57:0744 connection_(session->connection_pool()),
initial.commit586acc5fe2008-07-26 22:42:5245 reused_socket_(false),
46 using_ssl_(false),
47 using_proxy_(false),
48 using_tunnel_(false),
[email protected]6b9833e2008-09-10 20:32:2549 establishing_tunnel_(false),
[email protected]96d570e42008-08-05 22:43:0450 request_headers_bytes_sent_(0),
initial.commit586acc5fe2008-07-26 22:42:5251 header_buf_capacity_(0),
52 header_buf_len_(0),
53 header_buf_body_offset_(-1),
[email protected]231d5a32008-09-13 00:45:2754 header_buf_http_offset_(-1),
[email protected]ef0faf2e72009-03-05 23:27:2355 response_body_length_(-1), // -1 means unspecified.
56 response_body_read_(0),
initial.commit586acc5fe2008-07-26 22:42:5257 read_buf_len_(0),
58 next_state_(STATE_NONE) {
[email protected]2cd713f2008-10-21 17:54:2859#if defined(OS_WIN)
60 // TODO(port): Port the SSLConfigService class to Linux and Mac OS X.
61 session->ssl_config_service()->GetSSLConfig(&ssl_config_);
62#endif
initial.commit586acc5fe2008-07-26 22:42:5263}
64
[email protected]96d570e42008-08-05 22:43:0465int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
66 CompletionCallback* callback) {
[email protected]5d0153c512009-01-12 19:08:3667 UpdateConnectionTypeHistograms(CONNECTION_ANY);
68
[email protected]96d570e42008-08-05 22:43:0469 request_ = request_info;
70
71 next_state_ = STATE_RESOLVE_PROXY;
72 int rv = DoLoop(OK);
73 if (rv == ERR_IO_PENDING)
74 user_callback_ = callback;
75 return rv;
76}
77
78int HttpNetworkTransaction::RestartIgnoringLastError(
79 CompletionCallback* callback) {
[email protected]ccb40e52008-09-17 20:54:4080 // TODO(wtc): If the connection is no longer alive, call
81 // connection_.socket()->ReconnectIgnoringLastError().
82 next_state_ = STATE_WRITE_HEADERS;
83 int rv = DoLoop(OK);
84 if (rv == ERR_IO_PENDING)
85 user_callback_ = callback;
[email protected]aaead502008-10-15 00:20:1186 return rv;
[email protected]96d570e42008-08-05 22:43:0487}
88
89int HttpNetworkTransaction::RestartWithAuth(
90 const std::wstring& username,
91 const std::wstring& password,
92 CompletionCallback* callback) {
[email protected]c3b35c22008-09-27 03:19:4293
94 DCHECK(NeedAuth(HttpAuth::AUTH_PROXY) ||
95 NeedAuth(HttpAuth::AUTH_SERVER));
96
97 // Figure out whether this username password is for proxy or server.
98 // Proxy gets set first, then server.
99 HttpAuth::Target target = NeedAuth(HttpAuth::AUTH_PROXY) ?
100 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
101
102 // Update the username/password.
[email protected]f9ee6b52008-11-08 06:46:23103 auth_identity_[target].source = HttpAuth::IDENT_SRC_EXTERNAL;
104 auth_identity_[target].invalid = false;
105 auth_identity_[target].username = username;
106 auth_identity_[target].password = password;
[email protected]c3b35c22008-09-27 03:19:42107
[email protected]f9ee6b52008-11-08 06:46:23108 PrepareForAuthRestart(target);
[email protected]c3b35c22008-09-27 03:19:42109
110 DCHECK(user_callback_ == NULL);
111 int rv = DoLoop(OK);
112 if (rv == ERR_IO_PENDING)
113 user_callback_ = callback;
114
115 return rv;
[email protected]96d570e42008-08-05 22:43:04116}
117
[email protected]f9ee6b52008-11-08 06:46:23118void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
119 DCHECK(HaveAuth(target));
120 DCHECK(auth_identity_[target].source != HttpAuth::IDENT_SRC_PATH_LOOKUP);
121
122 // Add the auth entry to the cache before restarting. We don't know whether
123 // the identity is valid yet, but if it is valid we want other transactions
124 // to know about it. If an entry for (origin, handler->realm()) already
125 // exists, we update it.
[email protected]3f918782009-02-28 01:29:24126 //
127 // If auth_identity_[target].source is HttpAuth::IDENT_SRC_NONE,
128 // auth_identity_[target] contains no identity because identity is not
129 // required yet.
130 if (auth_identity_[target].source != HttpAuth::IDENT_SRC_NONE) {
131 session_->auth_cache()->Add(AuthOrigin(target), auth_handler_[target],
132 auth_identity_[target].username, auth_identity_[target].password,
133 AuthPath(target));
134 }
[email protected]f9ee6b52008-11-08 06:46:23135
[email protected]2d2697f92009-02-18 21:00:32136 bool keep_alive = false;
137 if (response_.headers->IsKeepAlive()) {
138 // If there is a response body of known length, we need to drain it first.
[email protected]ef0faf2e72009-03-05 23:27:23139 if (response_body_length_ > 0 || chunked_decoder_.get()) {
[email protected]2d2697f92009-02-18 21:00:32140 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
141 read_buf_ = new IOBuffer(kDrainBodyBufferSize); // A bit bucket
142 read_buf_len_ = kDrainBodyBufferSize;
143 return;
144 }
[email protected]ef0faf2e72009-03-05 23:27:23145 if (response_body_length_ == 0) // No response body to drain.
[email protected]2d2697f92009-02-18 21:00:32146 keep_alive = true;
[email protected]ef0faf2e72009-03-05 23:27:23147 // response_body_length_ is -1 and we're not using chunked encoding. We
148 // don't know the length of the response body, so we can't reuse this
149 // connection even though the server says it's keep-alive.
[email protected]2d2697f92009-02-18 21:00:32150 }
151
[email protected]04f40b32009-03-04 22:18:11152 // If the auth scheme is connection-based but the proxy/server mistakenly
153 // marks the connection as not keep-alive, the auth is going to fail, so log
154 // an error message.
155 if (!keep_alive && auth_handler_[target]->is_connection_based() &&
156 auth_identity_[target].source != HttpAuth::IDENT_SRC_NONE) {
157 std::string auth_target(target == HttpAuth::AUTH_PROXY ?
158 "proxy" : "server");
159 LOG(ERROR) << "Can't perform " << auth_handler_[target]->scheme()
160 << " auth to the " << auth_target << " "
161 << AuthOrigin(target).spec()
162 << " over a non-keep-alive connection";
163
164 HttpVersion http_version = response_.headers->GetHttpVersion();
165 LOG(ERROR) << " HTTP version is " << http_version.major_value() << "."
166 << http_version.minor_value();
167
168 std::string connection_val;
169 void* iter = NULL;
170 while (response_.headers->EnumerateHeader(&iter, "connection",
171 &connection_val)) {
172 LOG(ERROR) << " Has header Connection: " << connection_val;
173 }
174
175 iter = NULL;
176 while (response_.headers->EnumerateHeader(&iter, "proxy-connection",
177 &connection_val)) {
178 LOG(ERROR) << " Has header Proxy-Connection: " << connection_val;
179 }
180 }
181
[email protected]2d2697f92009-02-18 21:00:32182 // We don't need to drain the response body, so we act as if we had drained
183 // the response body.
184 DidDrainBodyForAuthRestart(keep_alive);
185}
186
187void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive) {
188 if (keep_alive) {
189 next_state_ = STATE_WRITE_HEADERS;
190 reused_socket_ = true;
191 } else {
192 next_state_ = STATE_INIT_CONNECTION;
193 connection_.set_socket(NULL);
194 connection_.Reset();
195 }
[email protected]f9ee6b52008-11-08 06:46:23196
197 // Reset the other member variables.
198 ResetStateForRestart();
199}
200
[email protected]9dea9e1f2009-01-29 00:30:47201int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
[email protected]96d570e42008-08-05 22:43:04202 CompletionCallback* callback) {
203 DCHECK(response_.headers);
204 DCHECK(buf);
205 DCHECK(buf_len > 0);
206
207 if (!connection_.is_initialized())
208 return 0; // connection_ has been reset. Treat like EOF.
209
[email protected]a8e9b162009-03-12 00:06:44210 if (establishing_tunnel_) {
211 // We're trying to read the body of the response but we're still trying to
212 // establish an SSL tunnel through the proxy. We can't read these bytes
213 // when establishing a tunnel because they might be controlled by an active
214 // network attacker. We don't worry about this for HTTP because an active
215 // network attacker can already control HTTP sessions.
216 // We reach this case when the user cancels a 407 proxy auth prompt.
217 // See http://crbug.com/8473
[email protected]9f9f86c2009-03-12 22:32:42218 DCHECK(response_.headers->response_code() == 407);
219 LogBlockedTunnelResponse(*response_.headers);
[email protected]a8e9b162009-03-12 00:06:44220 return ERR_TUNNEL_CONNECTION_FAILED;
221 }
222
[email protected]96d570e42008-08-05 22:43:04223 read_buf_ = buf;
224 read_buf_len_ = buf_len;
225
226 next_state_ = STATE_READ_BODY;
227 int rv = DoLoop(OK);
228 if (rv == ERR_IO_PENDING)
229 user_callback_ = callback;
230 return rv;
231}
232
233const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
[email protected]4628a2a2008-08-14 20:33:25234 return (response_.headers || response_.ssl_info.cert) ? &response_ : NULL;
[email protected]96d570e42008-08-05 22:43:04235}
236
237LoadState HttpNetworkTransaction::GetLoadState() const {
238 // TODO(wtc): Define a new LoadState value for the
239 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
240 switch (next_state_) {
241 case STATE_RESOLVE_PROXY_COMPLETE:
242 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
243 case STATE_RESOLVE_HOST_COMPLETE:
244 return LOAD_STATE_RESOLVING_HOST;
245 case STATE_CONNECT_COMPLETE:
246 return LOAD_STATE_CONNECTING;
247 case STATE_WRITE_HEADERS_COMPLETE:
248 case STATE_WRITE_BODY_COMPLETE:
249 return LOAD_STATE_SENDING_REQUEST;
250 case STATE_READ_HEADERS_COMPLETE:
251 return LOAD_STATE_WAITING_FOR_RESPONSE;
252 case STATE_READ_BODY_COMPLETE:
253 return LOAD_STATE_READING_RESPONSE;
254 default:
255 return LOAD_STATE_IDLE;
256 }
257}
258
259uint64 HttpNetworkTransaction::GetUploadProgress() const {
260 if (!request_body_stream_.get())
261 return 0;
262
263 return request_body_stream_->position();
264}
265
initial.commit586acc5fe2008-07-26 22:42:52266HttpNetworkTransaction::~HttpNetworkTransaction() {
267 // If we still have an open socket, then make sure to close it so we don't
268 // try to reuse it later on.
269 if (connection_.is_initialized())
270 connection_.set_socket(NULL);
271
272 if (pac_request_)
273 session_->proxy_service()->CancelPacRequest(pac_request_);
274}
275
276void HttpNetworkTransaction::BuildRequestHeaders() {
[email protected]3130a8532008-09-15 18:37:11277 // For proxy use the full url. Otherwise just the absolute path.
278 // This strips out any reference/username/password.
279 std::string path = using_proxy_ ?
280 HttpUtil::SpecForRequest(request_->url) :
281 HttpUtil::PathForRequest(request_->url);
initial.commit586acc5fe2008-07-26 22:42:52282
[email protected]c7af8b22008-08-25 20:41:46283 request_headers_ = request_->method + " " + path +
284 " HTTP/1.1\r\nHost: " + request_->url.host();
initial.commit586acc5fe2008-07-26 22:42:52285 if (request_->url.IntPort() != -1)
286 request_headers_ += ":" + request_->url.port();
287 request_headers_ += "\r\n";
288
289 // For compat with HTTP/1.0 servers and proxies:
290 if (using_proxy_)
291 request_headers_ += "Proxy-";
292 request_headers_ += "Connection: keep-alive\r\n";
293
294 if (!request_->user_agent.empty())
295 request_headers_ += "User-Agent: " + request_->user_agent + "\r\n";
296
297 // Our consumer should have made sure that this is a safe referrer. See for
298 // instance WebCore::FrameLoader::HideReferrer.
299 if (request_->referrer.is_valid())
300 request_headers_ += "Referer: " + request_->referrer.spec() + "\r\n";
301
302 // Add a content length header?
303 if (request_->upload_data) {
304 request_body_stream_.reset(new UploadDataStream(request_->upload_data));
305 request_headers_ +=
306 "Content-Length: " + Uint64ToString(request_body_stream_->size()) +
307 "\r\n";
308 } else if (request_->method == "POST" || request_->method == "PUT" ||
309 request_->method == "HEAD") {
310 // An empty POST/PUT request still needs a content length. As for HEAD,
311 // IE and Safari also add a content length header. Presumably it is to
312 // support sending a HEAD request to an URL that only expects to be sent a
313 // POST or some other method that normally would have a message body.
314 request_headers_ += "Content-Length: 0\r\n";
315 }
316
317 // Honor load flags that impact proxy caches.
318 if (request_->load_flags & LOAD_BYPASS_CACHE) {
319 request_headers_ += "Pragma: no-cache\r\nCache-Control: no-cache\r\n";
320 } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
321 request_headers_ += "Cache-Control: max-age=0\r\n";
322 }
323
[email protected]c3b35c22008-09-27 03:19:42324 ApplyAuth();
325
initial.commit586acc5fe2008-07-26 22:42:52326 // TODO(darin): Need to prune out duplicate headers.
327
328 request_headers_ += request_->extra_headers;
329 request_headers_ += "\r\n";
330}
331
[email protected]c7af8b22008-08-25 20:41:46332// The HTTP CONNECT method for establishing a tunnel connection is documented
[email protected]6b9833e2008-09-10 20:32:25333// in draft-luotonen-web-proxy-tunneling-01.txt and RFC 2817, Sections 5.2 and
[email protected]c7af8b22008-08-25 20:41:46334// 5.3.
335void HttpNetworkTransaction::BuildTunnelRequest() {
[email protected]c7af8b22008-08-25 20:41:46336 // RFC 2616 Section 9 says the Host request-header field MUST accompany all
337 // HTTP/1.1 requests.
[email protected]6d748ec2008-10-08 22:11:39338 request_headers_ = StringPrintf("CONNECT %s:%d HTTP/1.1\r\n",
339 request_->url.host().c_str(), request_->url.EffectiveIntPort());
340 request_headers_ += "Host: " + request_->url.host();
341 if (request_->url.has_port())
[email protected]c7af8b22008-08-25 20:41:46342 request_headers_ += ":" + request_->url.port();
343 request_headers_ += "\r\n";
344
345 if (!request_->user_agent.empty())
346 request_headers_ += "User-Agent: " + request_->user_agent + "\r\n";
347
[email protected]c3b35c22008-09-27 03:19:42348 ApplyAuth();
[email protected]c7af8b22008-08-25 20:41:46349
350 request_headers_ += "\r\n";
351}
352
initial.commit586acc5fe2008-07-26 22:42:52353void HttpNetworkTransaction::DoCallback(int rv) {
354 DCHECK(rv != ERR_IO_PENDING);
355 DCHECK(user_callback_);
356
[email protected]96d570e42008-08-05 22:43:04357 // Since Run may result in Read being called, clear user_callback_ up front.
initial.commit586acc5fe2008-07-26 22:42:52358 CompletionCallback* c = user_callback_;
359 user_callback_ = NULL;
360 c->Run(rv);
361}
362
363void HttpNetworkTransaction::OnIOComplete(int result) {
364 int rv = DoLoop(result);
365 if (rv != ERR_IO_PENDING)
366 DoCallback(rv);
367}
368
369int HttpNetworkTransaction::DoLoop(int result) {
370 DCHECK(next_state_ != STATE_NONE);
371
372 int rv = result;
373 do {
374 State state = next_state_;
375 next_state_ = STATE_NONE;
376 switch (state) {
377 case STATE_RESOLVE_PROXY:
[email protected]96d570e42008-08-05 22:43:04378 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55379 TRACE_EVENT_BEGIN("http.resolve_proxy", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52380 rv = DoResolveProxy();
381 break;
382 case STATE_RESOLVE_PROXY_COMPLETE:
383 rv = DoResolveProxyComplete(rv);
[email protected]113ab132008-09-18 20:42:55384 TRACE_EVENT_END("http.resolve_proxy", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52385 break;
386 case STATE_INIT_CONNECTION:
[email protected]96d570e42008-08-05 22:43:04387 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55388 TRACE_EVENT_BEGIN("http.init_conn", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52389 rv = DoInitConnection();
390 break;
391 case STATE_INIT_CONNECTION_COMPLETE:
392 rv = DoInitConnectionComplete(rv);
[email protected]113ab132008-09-18 20:42:55393 TRACE_EVENT_END("http.init_conn", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52394 break;
395 case STATE_RESOLVE_HOST:
[email protected]96d570e42008-08-05 22:43:04396 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55397 TRACE_EVENT_BEGIN("http.resolve_host", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52398 rv = DoResolveHost();
399 break;
400 case STATE_RESOLVE_HOST_COMPLETE:
401 rv = DoResolveHostComplete(rv);
[email protected]113ab132008-09-18 20:42:55402 TRACE_EVENT_END("http.resolve_host", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52403 break;
404 case STATE_CONNECT:
[email protected]96d570e42008-08-05 22:43:04405 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55406 TRACE_EVENT_BEGIN("http.connect", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52407 rv = DoConnect();
408 break;
409 case STATE_CONNECT_COMPLETE:
410 rv = DoConnectComplete(rv);
[email protected]113ab132008-09-18 20:42:55411 TRACE_EVENT_END("http.connect", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52412 break;
[email protected]c7af8b22008-08-25 20:41:46413 case STATE_SSL_CONNECT_OVER_TUNNEL:
414 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55415 TRACE_EVENT_BEGIN("http.ssl_tunnel", request_, request_->url.spec());
[email protected]c7af8b22008-08-25 20:41:46416 rv = DoSSLConnectOverTunnel();
417 break;
418 case STATE_SSL_CONNECT_OVER_TUNNEL_COMPLETE:
419 rv = DoSSLConnectOverTunnelComplete(rv);
[email protected]113ab132008-09-18 20:42:55420 TRACE_EVENT_END("http.ssl_tunnel", request_, request_->url.spec());
[email protected]c7af8b22008-08-25 20:41:46421 break;
initial.commit586acc5fe2008-07-26 22:42:52422 case STATE_WRITE_HEADERS:
[email protected]96d570e42008-08-05 22:43:04423 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55424 TRACE_EVENT_BEGIN("http.write_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52425 rv = DoWriteHeaders();
426 break;
427 case STATE_WRITE_HEADERS_COMPLETE:
428 rv = DoWriteHeadersComplete(rv);
[email protected]113ab132008-09-18 20:42:55429 TRACE_EVENT_END("http.write_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52430 break;
431 case STATE_WRITE_BODY:
[email protected]96d570e42008-08-05 22:43:04432 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55433 TRACE_EVENT_BEGIN("http.write_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52434 rv = DoWriteBody();
435 break;
436 case STATE_WRITE_BODY_COMPLETE:
437 rv = DoWriteBodyComplete(rv);
[email protected]113ab132008-09-18 20:42:55438 TRACE_EVENT_END("http.write_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52439 break;
440 case STATE_READ_HEADERS:
[email protected]96d570e42008-08-05 22:43:04441 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55442 TRACE_EVENT_BEGIN("http.read_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52443 rv = DoReadHeaders();
444 break;
445 case STATE_READ_HEADERS_COMPLETE:
446 rv = DoReadHeadersComplete(rv);
[email protected]113ab132008-09-18 20:42:55447 TRACE_EVENT_END("http.read_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52448 break;
449 case STATE_READ_BODY:
[email protected]96d570e42008-08-05 22:43:04450 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55451 TRACE_EVENT_BEGIN("http.read_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52452 rv = DoReadBody();
453 break;
454 case STATE_READ_BODY_COMPLETE:
455 rv = DoReadBodyComplete(rv);
[email protected]113ab132008-09-18 20:42:55456 TRACE_EVENT_END("http.read_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52457 break;
[email protected]2d2697f92009-02-18 21:00:32458 case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
459 DCHECK(rv == OK);
460 TRACE_EVENT_BEGIN("http.drain_body_for_auth_restart",
461 request_, request_->url.spec());
462 rv = DoDrainBodyForAuthRestart();
463 break;
464 case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
465 rv = DoDrainBodyForAuthRestartComplete(rv);
466 TRACE_EVENT_END("http.drain_body_for_auth_restart",
467 request_, request_->url.spec());
468 break;
initial.commit586acc5fe2008-07-26 22:42:52469 default:
470 NOTREACHED() << "bad state";
471 rv = ERR_FAILED;
[email protected]96d570e42008-08-05 22:43:04472 break;
initial.commit586acc5fe2008-07-26 22:42:52473 }
474 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
475
476 return rv;
477}
478
479int HttpNetworkTransaction::DoResolveProxy() {
480 DCHECK(!pac_request_);
481
482 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
483
[email protected]677c90572008-12-10 09:03:15484 if (request_->load_flags & LOAD_BYPASS_PROXY) {
485 proxy_info_.UseDirect();
486 return OK;
487 }
488
initial.commit586acc5fe2008-07-26 22:42:52489 return session_->proxy_service()->ResolveProxy(
490 request_->url, &proxy_info_, &io_callback_, &pac_request_);
491}
492
493int HttpNetworkTransaction::DoResolveProxyComplete(int result) {
494 next_state_ = STATE_INIT_CONNECTION;
495
[email protected]f6fb2de2009-02-19 08:11:42496 // Since we only support HTTP proxies or DIRECT connections, remove
497 // any other type of proxy from the list (i.e. SOCKS).
498 // Supporting SOCKS is issue http://crbug.com/469.
499 proxy_info_.RemoveProxiesWithoutScheme(
500 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP);
501
initial.commit586acc5fe2008-07-26 22:42:52502 pac_request_ = NULL;
503
504 if (result != OK) {
505 DLOG(ERROR) << "Failed to resolve proxy: " << result;
506 proxy_info_.UseDirect();
507 }
508 return OK;
509}
510
511int HttpNetworkTransaction::DoInitConnection() {
512 DCHECK(!connection_.is_initialized());
513
514 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
515
516 using_ssl_ = request_->url.SchemeIs("https");
517 using_proxy_ = !proxy_info_.is_direct() && !using_ssl_;
518 using_tunnel_ = !proxy_info_.is_direct() && using_ssl_;
519
520 // Build the string used to uniquely identify connections of this type.
521 std::string connection_group;
522 if (using_proxy_ || using_tunnel_)
[email protected]f6fb2de2009-02-19 08:11:42523 connection_group = "proxy/" + proxy_info_.proxy_server().ToURI() + "/";
initial.commit586acc5fe2008-07-26 22:42:52524 if (!using_proxy_)
525 connection_group.append(request_->url.GetOrigin().spec());
526
[email protected]96d570e42008-08-05 22:43:04527 DCHECK(!connection_group.empty());
initial.commit586acc5fe2008-07-26 22:42:52528 return connection_.Init(connection_group, &io_callback_);
529}
530
531int HttpNetworkTransaction::DoInitConnectionComplete(int result) {
532 if (result < 0)
533 return result;
534
535 DCHECK(connection_.is_initialized());
536
537 // Set the reused_socket_ flag to indicate that we are using a keep-alive
538 // connection. This flag is used to handle errors that occur while we are
539 // trying to reuse a keep-alive connection.
[email protected]049d4ee2008-10-23 21:42:07540 reused_socket_ = (connection_.socket() != NULL);
541 if (reused_socket_) {
initial.commit586acc5fe2008-07-26 22:42:52542 next_state_ = STATE_WRITE_HEADERS;
543 } else {
544 next_state_ = STATE_RESOLVE_HOST;
545 }
546 return OK;
547}
548
549int HttpNetworkTransaction::DoResolveHost() {
550 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
551
initial.commit586acc5fe2008-07-26 22:42:52552 std::string host;
553 int port;
554
555 // Determine the host and port to connect to.
556 if (using_proxy_ || using_tunnel_) {
[email protected]f6fb2de2009-02-19 08:11:42557 ProxyServer proxy_server = proxy_info_.proxy_server();
558 host = proxy_server.host();
559 port = proxy_server.port();
initial.commit586acc5fe2008-07-26 22:42:52560 } else {
[email protected]96d570e42008-08-05 22:43:04561 // Direct connection
initial.commit586acc5fe2008-07-26 22:42:52562 host = request_->url.host();
[email protected]6d748ec2008-10-08 22:11:39563 port = request_->url.EffectiveIntPort();
initial.commit586acc5fe2008-07-26 22:42:52564 }
565
[email protected]8947da62008-10-24 19:11:10566 DidStartDnsResolution(host, this);
[email protected]96d570e42008-08-05 22:43:04567 return resolver_.Resolve(host, port, &addresses_, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52568}
569
570int HttpNetworkTransaction::DoResolveHostComplete(int result) {
[email protected]8947da62008-10-24 19:11:10571 bool ok = (result == OK);
[email protected]77848d12008-11-14 00:00:22572 DidFinishDnsResolutionWithStatus(ok, request_->referrer, this);
[email protected]8947da62008-10-24 19:11:10573 if (ok) {
initial.commit586acc5fe2008-07-26 22:42:52574 next_state_ = STATE_CONNECT;
[email protected]86ec30d2008-09-29 21:53:54575 } else {
576 result = ReconsiderProxyAfterError(result);
577 }
initial.commit586acc5fe2008-07-26 22:42:52578 return result;
579}
580
581int HttpNetworkTransaction::DoConnect() {
582 next_state_ = STATE_CONNECT_COMPLETE;
583
584 DCHECK(!connection_.socket());
585
586 ClientSocket* s = socket_factory_->CreateTCPClientSocket(addresses_);
587
588 // If we are using a direct SSL connection, then go ahead and create the SSL
589 // wrapper socket now. Otherwise, we need to first issue a CONNECT request.
590 if (using_ssl_ && !using_tunnel_)
[email protected]c5949a32008-10-08 17:28:23591 s = socket_factory_->CreateSSLClientSocket(s, request_->url.host(),
[email protected]aaead502008-10-15 00:20:11592 ssl_config_);
initial.commit586acc5fe2008-07-26 22:42:52593
594 connection_.set_socket(s);
595 return connection_.socket()->Connect(&io_callback_);
596}
597
598int HttpNetworkTransaction::DoConnectComplete(int result) {
[email protected]771d0c2b2008-09-30 00:26:17599 if (IsCertificateError(result))
600 result = HandleCertificateError(result);
601
[email protected]c7af8b22008-08-25 20:41:46602 if (result == OK) {
[email protected]6b9833e2008-09-10 20:32:25603 next_state_ = STATE_WRITE_HEADERS;
[email protected]27161fb2008-11-03 23:39:05604 if (using_tunnel_)
[email protected]6b9833e2008-09-10 20:32:25605 establishing_tunnel_ = true;
[email protected]86ec30d2008-09-29 21:53:54606 } else {
[email protected]5a179bcc2008-10-13 18:10:59607 result = HandleSSLHandshakeError(result);
608 if (result != OK)
609 result = ReconsiderProxyAfterError(result);
[email protected]c7af8b22008-08-25 20:41:46610 }
611 return result;
612}
613
[email protected]c7af8b22008-08-25 20:41:46614int HttpNetworkTransaction::DoSSLConnectOverTunnel() {
615 next_state_ = STATE_SSL_CONNECT_OVER_TUNNEL_COMPLETE;
616
[email protected]86ec30d2008-09-29 21:53:54617 // Add a SSL socket on top of our existing transport socket.
[email protected]c7af8b22008-08-25 20:41:46618 ClientSocket* s = connection_.release_socket();
[email protected]c5949a32008-10-08 17:28:23619 s = socket_factory_->CreateSSLClientSocket(s, request_->url.host(),
[email protected]aaead502008-10-15 00:20:11620 ssl_config_);
[email protected]c7af8b22008-08-25 20:41:46621 connection_.set_socket(s);
622 return connection_.socket()->Connect(&io_callback_);
623}
624
625int HttpNetworkTransaction::DoSSLConnectOverTunnelComplete(int result) {
[email protected]771d0c2b2008-09-30 00:26:17626 if (IsCertificateError(result))
[email protected]ccb40e52008-09-17 20:54:40627 result = HandleCertificateError(result);
[email protected]771d0c2b2008-09-30 00:26:17628
[email protected]c5949a32008-10-08 17:28:23629 if (result == OK) {
[email protected]771d0c2b2008-09-30 00:26:17630 next_state_ = STATE_WRITE_HEADERS;
[email protected]5a179bcc2008-10-13 18:10:59631 } else {
[email protected]c5949a32008-10-08 17:28:23632 result = HandleSSLHandshakeError(result);
633 }
initial.commit586acc5fe2008-07-26 22:42:52634 return result;
635}
636
637int HttpNetworkTransaction::DoWriteHeaders() {
638 next_state_ = STATE_WRITE_HEADERS_COMPLETE;
639
640 // This is constructed lazily (instead of within our Start method), so that
641 // we have proxy info available.
[email protected]6b9833e2008-09-10 20:32:25642 if (request_headers_.empty()) {
643 if (establishing_tunnel_) {
644 BuildTunnelRequest();
645 } else {
646 BuildRequestHeaders();
647 }
648 }
initial.commit586acc5fe2008-07-26 22:42:52649
650 // Record our best estimate of the 'request time' as the time when we send
651 // out the first bytes of the request headers.
[email protected]87a1a952009-01-13 18:06:03652 if (request_headers_bytes_sent_ == 0) {
initial.commit586acc5fe2008-07-26 22:42:52653 response_.request_time = Time::Now();
[email protected]87a1a952009-01-13 18:06:03654 response_.was_cached = false;
655 }
initial.commit586acc5fe2008-07-26 22:42:52656
[email protected]6b9833e2008-09-10 20:32:25657 const char* buf = request_headers_.data() + request_headers_bytes_sent_;
658 int buf_len = static_cast<int>(request_headers_.size() -
659 request_headers_bytes_sent_);
660 DCHECK(buf_len > 0);
661
662 return connection_.socket()->Write(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52663}
664
665int HttpNetworkTransaction::DoWriteHeadersComplete(int result) {
666 if (result < 0)
667 return HandleIOError(result);
668
[email protected]96d570e42008-08-05 22:43:04669 request_headers_bytes_sent_ += result;
670 if (request_headers_bytes_sent_ < request_headers_.size()) {
initial.commit586acc5fe2008-07-26 22:42:52671 next_state_ = STATE_WRITE_HEADERS;
[email protected]6b9833e2008-09-10 20:32:25672 } else if (!establishing_tunnel_ && request_->upload_data) {
initial.commit586acc5fe2008-07-26 22:42:52673 next_state_ = STATE_WRITE_BODY;
674 } else {
675 next_state_ = STATE_READ_HEADERS;
676 }
677 return OK;
678}
679
680int HttpNetworkTransaction::DoWriteBody() {
681 next_state_ = STATE_WRITE_BODY_COMPLETE;
682
683 DCHECK(request_->upload_data);
684 DCHECK(request_body_stream_.get());
685
686 const char* buf = request_body_stream_->buf();
687 int buf_len = static_cast<int>(request_body_stream_->buf_len());
688
689 return connection_.socket()->Write(buf, buf_len, &io_callback_);
690}
691
692int HttpNetworkTransaction::DoWriteBodyComplete(int result) {
693 if (result < 0)
694 return HandleIOError(result);
695
696 request_body_stream_->DidConsume(result);
697
698 if (request_body_stream_->position() < request_body_stream_->size()) {
699 next_state_ = STATE_WRITE_BODY;
700 } else {
701 next_state_ = STATE_READ_HEADERS;
702 }
703 return OK;
704}
705
706int HttpNetworkTransaction::DoReadHeaders() {
707 next_state_ = STATE_READ_HEADERS_COMPLETE;
708
[email protected]6b9833e2008-09-10 20:32:25709 // Grow the read buffer if necessary.
710 if (header_buf_len_ == header_buf_capacity_) {
711 header_buf_capacity_ += kHeaderBufInitialSize;
712 header_buf_.reset(static_cast<char*>(
713 realloc(header_buf_.release(), header_buf_capacity_)));
714 }
715
716 char* buf = header_buf_.get() + header_buf_len_;
717 int buf_len = header_buf_capacity_ - header_buf_len_;
718
719 return connection_.socket()->Read(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52720}
721
[email protected]0e75a732008-10-16 20:36:09722int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
[email protected]aecfbf22008-10-16 02:02:47723 if (establishing_tunnel_) {
[email protected]0e75a732008-10-16 20:36:09724 // The connection was closed before the tunnel could be established.
[email protected]aecfbf22008-10-16 02:02:47725 return ERR_TUNNEL_CONNECTION_FAILED;
726 }
727
728 if (has_found_status_line_start()) {
729 // Assume EOF is end-of-headers.
730 header_buf_body_offset_ = header_buf_len_;
731 return OK;
732 }
733
734 // No status line was matched yet. Could have been a HTTP/0.9 response, or
735 // a partial HTTP/1.x response.
736
737 if (header_buf_len_ == 0) {
[email protected]0e75a732008-10-16 20:36:09738 // The connection was closed before any data was sent. Likely an error
739 // rather than empty HTTP/0.9 response.
[email protected]aecfbf22008-10-16 02:02:47740 return ERR_EMPTY_RESPONSE;
741 }
742
743 // Assume everything else is a HTTP/0.9 response (including responses
744 // of 'h', 'ht', 'htt').
745 header_buf_body_offset_ = 0;
746 return OK;
747}
748
initial.commit586acc5fe2008-07-26 22:42:52749int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
750 if (result < 0)
751 return HandleIOError(result);
752
[email protected]2a5c76b2008-09-25 22:15:16753 if (result == 0 && ShouldResendRequest())
754 return result;
755
initial.commit586acc5fe2008-07-26 22:42:52756 // Record our best estimate of the 'response time' as the time when we read
757 // the first bytes of the response headers.
758 if (header_buf_len_ == 0)
759 response_.response_time = Time::Now();
760
[email protected]231d5a32008-09-13 00:45:27761 // The socket was closed before we found end-of-headers.
initial.commit586acc5fe2008-07-26 22:42:52762 if (result == 0) {
[email protected]0e75a732008-10-16 20:36:09763 int rv = HandleConnectionClosedBeforeEndOfHeaders();
[email protected]aecfbf22008-10-16 02:02:47764 if (rv != OK)
765 return rv;
initial.commit586acc5fe2008-07-26 22:42:52766 } else {
767 header_buf_len_ += result;
768 DCHECK(header_buf_len_ <= header_buf_capacity_);
769
[email protected]231d5a32008-09-13 00:45:27770 // Look for the start of the status line, if it hasn't been found yet.
771 if (!has_found_status_line_start()) {
772 header_buf_http_offset_ = HttpUtil::LocateStartOfStatusLine(
773 header_buf_.get(), header_buf_len_);
initial.commit586acc5fe2008-07-26 22:42:52774 }
[email protected]231d5a32008-09-13 00:45:27775
776 if (has_found_status_line_start()) {
777 int eoh = HttpUtil::LocateEndOfHeaders(
778 header_buf_.get(), header_buf_len_, header_buf_http_offset_);
779 if (eoh == -1) {
[email protected]4ddaf2502008-10-23 18:26:19780 // Prevent growing the headers buffer indefinitely.
781 if (header_buf_len_ >= kMaxHeaderBufSize)
782 return ERR_RESPONSE_HEADERS_TOO_BIG;
783
[email protected]231d5a32008-09-13 00:45:27784 // Haven't found the end of headers yet, keep reading.
785 next_state_ = STATE_READ_HEADERS;
786 return OK;
787 }
788 header_buf_body_offset_ = eoh;
789 } else if (header_buf_len_ < 8) {
790 // Not enough data to decide whether this is HTTP/0.9 yet.
791 // 8 bytes = (4 bytes of junk) + "http".length()
792 next_state_ = STATE_READ_HEADERS;
793 return OK;
794 } else {
795 // Enough data was read -- there is no status line.
796 header_buf_body_offset_ = 0;
797 }
initial.commit586acc5fe2008-07-26 22:42:52798 }
[email protected]65f11402008-10-31 17:39:44799
[email protected]6b9833e2008-09-10 20:32:25800 // And, we are done with the Start or the SSL tunnel CONNECT sequence.
[email protected]27161fb2008-11-03 23:39:05801 return DidReadResponseHeaders();
initial.commit586acc5fe2008-07-26 22:42:52802}
803
804int HttpNetworkTransaction::DoReadBody() {
805 DCHECK(read_buf_);
806 DCHECK(read_buf_len_ > 0);
807 DCHECK(connection_.is_initialized());
808
809 next_state_ = STATE_READ_BODY_COMPLETE;
810
[email protected]f9d44aa2008-09-23 23:57:17811 // We may have already consumed the indicated content length.
[email protected]ef0faf2e72009-03-05 23:27:23812 if (response_body_length_ != -1 &&
813 response_body_read_ >= response_body_length_)
[email protected]f9d44aa2008-09-23 23:57:17814 return 0;
815
[email protected]96d570e42008-08-05 22:43:04816 // We may have some data remaining in the header buffer.
initial.commit586acc5fe2008-07-26 22:42:52817 if (header_buf_.get() && header_buf_body_offset_ < header_buf_len_) {
818 int n = std::min(read_buf_len_, header_buf_len_ - header_buf_body_offset_);
[email protected]9dea9e1f2009-01-29 00:30:47819 memcpy(read_buf_->data(), header_buf_.get() + header_buf_body_offset_, n);
initial.commit586acc5fe2008-07-26 22:42:52820 header_buf_body_offset_ += n;
[email protected]96d570e42008-08-05 22:43:04821 if (header_buf_body_offset_ == header_buf_len_) {
initial.commit586acc5fe2008-07-26 22:42:52822 header_buf_.reset();
[email protected]96d570e42008-08-05 22:43:04823 header_buf_capacity_ = 0;
824 header_buf_len_ = 0;
825 header_buf_body_offset_ = -1;
826 }
initial.commit586acc5fe2008-07-26 22:42:52827 return n;
828 }
829
[email protected]9dea9e1f2009-01-29 00:30:47830 return connection_.socket()->Read(read_buf_->data(), read_buf_len_,
831 &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52832}
833
834int HttpNetworkTransaction::DoReadBodyComplete(int result) {
835 // We are done with the Read call.
[email protected]c744cf22009-02-27 07:28:08836 DCHECK(!establishing_tunnel_) <<
837 "We should never read a response body of a tunnel.";
initial.commit586acc5fe2008-07-26 22:42:52838
[email protected]96d570e42008-08-05 22:43:04839 bool unfiltered_eof = (result == 0);
840
initial.commit586acc5fe2008-07-26 22:42:52841 // Filter incoming data if appropriate. FilterBuf may return an error.
842 if (result > 0 && chunked_decoder_.get()) {
[email protected]9dea9e1f2009-01-29 00:30:47843 result = chunked_decoder_->FilterBuf(read_buf_->data(), result);
[email protected]96d570e42008-08-05 22:43:04844 if (result == 0 && !chunked_decoder_->reached_eof()) {
initial.commit586acc5fe2008-07-26 22:42:52845 // Don't signal completion of the Read call yet or else it'll look like
846 // we received end-of-file. Wait for more data.
847 next_state_ = STATE_READ_BODY;
848 return OK;
849 }
850 }
851
852 bool done = false, keep_alive = false;
853 if (result < 0) {
854 // Error while reading the socket.
855 done = true;
856 } else {
[email protected]ef0faf2e72009-03-05 23:27:23857 response_body_read_ += result;
[email protected]96d570e42008-08-05 22:43:04858 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23859 (response_body_length_ != -1 &&
860 response_body_read_ >= response_body_length_) ||
initial.commit586acc5fe2008-07-26 22:42:52861 (chunked_decoder_.get() && chunked_decoder_->reached_eof())) {
862 done = true;
863 keep_alive = response_.headers->IsKeepAlive();
[email protected]96d570e42008-08-05 22:43:04864 // We can't reuse the connection if we read more than the advertised
[email protected]c744cf22009-02-27 07:28:08865 // content length.
[email protected]f4e426b2008-11-05 00:24:49866 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23867 (response_body_length_ != -1 &&
868 response_body_read_ > response_body_length_))
[email protected]96d570e42008-08-05 22:43:04869 keep_alive = false;
initial.commit586acc5fe2008-07-26 22:42:52870 }
871 }
872
[email protected]2d2697f92009-02-18 21:00:32873 // Clean up connection_ if we are done.
initial.commit586acc5fe2008-07-26 22:42:52874 if (done) {
[email protected]56300172008-11-06 18:42:55875 LogTransactionMetrics();
initial.commit586acc5fe2008-07-26 22:42:52876 if (!keep_alive)
877 connection_.set_socket(NULL);
878 connection_.Reset();
[email protected]96d570e42008-08-05 22:43:04879 // The next Read call will return 0 (EOF).
initial.commit586acc5fe2008-07-26 22:42:52880 }
881
882 // Clear these to avoid leaving around old state.
883 read_buf_ = NULL;
884 read_buf_len_ = 0;
885
886 return result;
887}
888
[email protected]2d2697f92009-02-18 21:00:32889int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
890 // This method differs from DoReadBody only in the next_state_. So we just
891 // call DoReadBody and override the next_state_. Perhaps there is a more
892 // elegant way for these two methods to share code.
893 int rv = DoReadBody();
894 DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
895 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
896 return rv;
897}
898
899// TODO(wtc): The first two thirds of this method and the DoReadBodyComplete
900// method are almost the same. Figure out a good way for these two methods
901// to share code.
902int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
903 bool unfiltered_eof = (result == 0);
904
905 // Filter incoming data if appropriate. FilterBuf may return an error.
906 if (result > 0 && chunked_decoder_.get()) {
907 result = chunked_decoder_->FilterBuf(read_buf_->data(), result);
908 if (result == 0 && !chunked_decoder_->reached_eof()) {
909 // Don't signal completion of the Read call yet or else it'll look like
910 // we received end-of-file. Wait for more data.
911 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
912 return OK;
913 }
914 }
915
916 bool done = false, keep_alive = false;
917 if (result < 0) {
918 // Error while reading the socket.
919 done = true;
920 } else {
[email protected]ef0faf2e72009-03-05 23:27:23921 response_body_read_ += result;
[email protected]2d2697f92009-02-18 21:00:32922 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23923 (response_body_length_ != -1 &&
924 response_body_read_ >= response_body_length_) ||
[email protected]2d2697f92009-02-18 21:00:32925 (chunked_decoder_.get() && chunked_decoder_->reached_eof())) {
926 done = true;
927 keep_alive = response_.headers->IsKeepAlive();
928 // We can't reuse the connection if we read more than the advertised
929 // content length.
930 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23931 (response_body_length_ != -1 &&
932 response_body_read_ > response_body_length_))
[email protected]2d2697f92009-02-18 21:00:32933 keep_alive = false;
934 }
935 }
936
937 if (done) {
938 DidDrainBodyForAuthRestart(keep_alive);
939 } else {
940 // Keep draining.
941 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
942 }
943
944 return OK;
945}
946
[email protected]56300172008-11-06 18:42:55947void HttpNetworkTransaction::LogTransactionMetrics() const {
948 base::TimeDelta duration = base::Time::Now() - response_.request_time;
949 if (60 < duration.InMinutes())
950 return;
[email protected]553dba62009-02-24 19:08:23951 UMA_HISTOGRAM_LONG_TIMES("Net.Transaction_Latency", duration);
[email protected]56300172008-11-06 18:42:55952 if (!duration.InMilliseconds())
953 return;
[email protected]553dba62009-02-24 19:08:23954 UMA_HISTOGRAM_COUNTS("Net.Transaction_Bandwidth",
[email protected]ef0faf2e72009-03-05 23:27:23955 static_cast<int> (response_body_read_ / duration.InMilliseconds()));
[email protected]56300172008-11-06 18:42:55956}
957
[email protected]9f9f86c2009-03-12 22:32:42958void HttpNetworkTransaction::LogBlockedTunnelResponse(
959 const HttpResponseHeaders& headers) const {
960 LOG(WARNING) << "Blocked proxy response with status "
961 << headers.response_code() << " to CONNECT request for "
962 << request_->url.host() << ":"
963 << request_->url.EffectiveIntPort() << ".";
964}
965
[email protected]27161fb2008-11-03 23:39:05966int HttpNetworkTransaction::DidReadResponseHeaders() {
[email protected]231d5a32008-09-13 00:45:27967 scoped_refptr<HttpResponseHeaders> headers;
968 if (has_found_status_line_start()) {
969 headers = new HttpResponseHeaders(
970 HttpUtil::AssembleRawHeaders(
971 header_buf_.get(), header_buf_body_offset_));
972 } else {
973 // Fabricate a status line to to preserve the HTTP/0.9 version.
974 // (otherwise HttpResponseHeaders will default it to HTTP/1.0).
975 headers = new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
976 }
977
[email protected]f9d44aa2008-09-23 23:57:17978 if (headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
979 // Require the "HTTP/1.x" status line for SSL CONNECT.
980 if (establishing_tunnel_)
981 return ERR_TUNNEL_CONNECTION_FAILED;
[email protected]231d5a32008-09-13 00:45:27982
[email protected]f9d44aa2008-09-23 23:57:17983 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
984 // indicates a buggy server. See:
985 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
986 if (request_->method == "PUT")
987 return ERR_METHOD_NOT_SUPPORTED;
988 }
initial.commit586acc5fe2008-07-26 22:42:52989
[email protected]d1ec59082009-02-11 02:48:15990 if (establishing_tunnel_) {
[email protected]c744cf22009-02-27 07:28:08991 switch (headers->response_code()) {
992 case 200: // OK
993 if (header_buf_body_offset_ != header_buf_len_) {
994 // The proxy sent extraneous data after the headers.
995 return ERR_TUNNEL_CONNECTION_FAILED;
996 }
997 next_state_ = STATE_SSL_CONNECT_OVER_TUNNEL;
998 // Reset for the real request and response headers.
999 request_headers_.clear();
1000 request_headers_bytes_sent_ = 0;
1001 header_buf_len_ = 0;
1002 header_buf_body_offset_ = 0;
1003 establishing_tunnel_ = false;
1004 return OK;
1005
1006 // We aren't able to CONNECT to the remote host through the proxy. We
1007 // need to be very suspicious about the response because an active network
1008 // attacker can force us into this state by masquerading as the proxy.
1009 // The only safe thing to do here is to fail the connection because our
1010 // client is expecting an SSL protected response.
1011 // See http://crbug.com/7338.
1012 case 407: // Proxy Authentication Required
1013 // We need this status code to allow proxy authentication. Our
1014 // authentication code is smart enough to avoid being tricked by an
1015 // active network attacker.
1016 break;
1017 default:
1018 // For all other status codes, we conservatively fail the CONNECT
1019 // request.
1020 // We lose something by doing this. We have seen proxy 403, 404, and
1021 // 501 response bodies that contain a useful error message. For
1022 // example, Squid uses a 404 response to report the DNS error: "The
1023 // domain name does not exist."
[email protected]9f9f86c2009-03-12 22:32:421024 LogBlockedTunnelResponse(*headers);
[email protected]d1ec59082009-02-11 02:48:151025 return ERR_TUNNEL_CONNECTION_FAILED;
[email protected]d1ec59082009-02-11 02:48:151026 }
[email protected]d1ec59082009-02-11 02:48:151027 }
1028
initial.commit586acc5fe2008-07-26 22:42:521029 // Check for an intermediate 100 Continue response. An origin server is
1030 // allowed to send this response even if we didn't ask for it, so we just
1031 // need to skip over it.
1032 if (headers->response_code() == 100) {
[email protected]96d570e42008-08-05 22:43:041033 header_buf_len_ -= header_buf_body_offset_;
1034 // If we've already received some bytes after the 100 Continue response,
1035 // move them to the beginning of header_buf_.
1036 if (header_buf_len_) {
1037 memmove(header_buf_.get(), header_buf_.get() + header_buf_body_offset_,
1038 header_buf_len_);
1039 }
initial.commit586acc5fe2008-07-26 22:42:521040 header_buf_body_offset_ = -1;
1041 next_state_ = STATE_READ_HEADERS;
1042 return OK;
1043 }
1044
1045 response_.headers = headers;
1046 response_.vary_data.Init(*request_, *response_.headers);
1047
1048 // Figure how to determine EOF:
1049
[email protected]ef0faf2e72009-03-05 23:27:231050 // For certain responses, we know the content length is always 0. From
1051 // RFC 2616 Section 4.3 Message Body:
1052 //
1053 // For response messages, whether or not a message-body is included with
1054 // a message is dependent on both the request method and the response
1055 // status code (section 6.1.1). All responses to the HEAD request method
1056 // MUST NOT include a message-body, even though the presence of entity-
1057 // header fields might lead one to believe they do. All 1xx
1058 // (informational), 204 (no content), and 304 (not modified) responses
1059 // MUST NOT include a message-body. All other responses do include a
1060 // message-body, although it MAY be of zero length.
initial.commit586acc5fe2008-07-26 22:42:521061 switch (response_.headers->response_code()) {
[email protected]96d570e42008-08-05 22:43:041062 case 204: // No Content
1063 case 205: // Reset Content
1064 case 304: // Not Modified
[email protected]ef0faf2e72009-03-05 23:27:231065 response_body_length_ = 0;
initial.commit586acc5fe2008-07-26 22:42:521066 break;
1067 }
[email protected]ef0faf2e72009-03-05 23:27:231068 if (request_->method == "HEAD")
1069 response_body_length_ = 0;
initial.commit586acc5fe2008-07-26 22:42:521070
[email protected]ef0faf2e72009-03-05 23:27:231071 if (response_body_length_ == -1) {
initial.commit586acc5fe2008-07-26 22:42:521072 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1073 // Otherwise "Transfer-Encoding: chunked" trumps "Content-Length: N"
[email protected]f9d44aa2008-09-23 23:57:171074 if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1) &&
initial.commit586acc5fe2008-07-26 22:42:521075 response_.headers->HasHeaderValue("Transfer-Encoding", "chunked")) {
1076 chunked_decoder_.reset(new HttpChunkedDecoder());
1077 } else {
[email protected]ef0faf2e72009-03-05 23:27:231078 response_body_length_ = response_.headers->GetContentLength();
1079 // If response_body_length_ is still -1, then we have to wait for the
1080 // server to close the connection.
initial.commit586acc5fe2008-07-26 22:42:521081 }
1082 }
1083
[email protected]2d2697f92009-02-18 21:00:321084 int rv = HandleAuthChallenge();
1085 if (rv == WILL_RESTART_TRANSACTION)
1086 return OK;
1087 if (rv != OK)
1088 return rv;
1089
[email protected]6b9833e2008-09-10 20:32:251090 if (using_ssl_ && !establishing_tunnel_) {
[email protected]4628a2a2008-08-14 20:33:251091 SSLClientSocket* ssl_socket =
1092 reinterpret_cast<SSLClientSocket*>(connection_.socket());
1093 ssl_socket->GetSSLInfo(&response_.ssl_info);
1094 }
1095
initial.commit586acc5fe2008-07-26 22:42:521096 return OK;
1097}
1098
[email protected]ccb40e52008-09-17 20:54:401099int HttpNetworkTransaction::HandleCertificateError(int error) {
1100 DCHECK(using_ssl_);
1101
1102 const int kCertFlags = LOAD_IGNORE_CERT_COMMON_NAME_INVALID |
1103 LOAD_IGNORE_CERT_DATE_INVALID |
1104 LOAD_IGNORE_CERT_AUTHORITY_INVALID |
1105 LOAD_IGNORE_CERT_WRONG_USAGE;
1106 if (request_->load_flags & kCertFlags) {
1107 switch (error) {
1108 case ERR_CERT_COMMON_NAME_INVALID:
1109 if (request_->load_flags & LOAD_IGNORE_CERT_COMMON_NAME_INVALID)
1110 error = OK;
1111 break;
1112 case ERR_CERT_DATE_INVALID:
1113 if (request_->load_flags & LOAD_IGNORE_CERT_DATE_INVALID)
1114 error = OK;
1115 break;
1116 case ERR_CERT_AUTHORITY_INVALID:
1117 if (request_->load_flags & LOAD_IGNORE_CERT_AUTHORITY_INVALID)
1118 error = OK;
1119 break;
1120 }
1121 }
1122
1123 if (error != OK) {
1124 SSLClientSocket* ssl_socket =
1125 reinterpret_cast<SSLClientSocket*>(connection_.socket());
1126 ssl_socket->GetSSLInfo(&response_.ssl_info);
1127 }
1128 return error;
1129}
1130
[email protected]c5949a32008-10-08 17:28:231131int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
[email protected]5a179bcc2008-10-13 18:10:591132 switch (error) {
1133 case ERR_SSL_PROTOCOL_ERROR:
1134 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
[email protected]aaead502008-10-15 00:20:111135 if (ssl_config_.tls1_enabled) {
[email protected]5a179bcc2008-10-13 18:10:591136 // This could be a TLS-intolerant server or an SSL 3.0 server that
1137 // chose a TLS-only cipher suite. Turn off TLS 1.0 and retry.
[email protected]aaead502008-10-15 00:20:111138 ssl_config_.tls1_enabled = false;
[email protected]5a179bcc2008-10-13 18:10:591139 connection_.set_socket(NULL);
1140 connection_.Reset();
1141 next_state_ = STATE_INIT_CONNECTION;
1142 error = OK;
1143 }
1144 break;
[email protected]c5949a32008-10-08 17:28:231145 }
[email protected]c5949a32008-10-08 17:28:231146 return error;
1147}
1148
[email protected]96d570e42008-08-05 22:43:041149// This method determines whether it is safe to resend the request after an
1150// IO error. It can only be called in response to request header or body
1151// write errors or response header read errors. It should not be used in
1152// other cases, such as a Connect error.
initial.commit586acc5fe2008-07-26 22:42:521153int HttpNetworkTransaction::HandleIOError(int error) {
1154 switch (error) {
1155 // If we try to reuse a connection that the server is in the process of
1156 // closing, we may end up successfully writing out our request (or a
1157 // portion of our request) only to find a connection error when we try to
1158 // read from (or finish writing to) the socket.
1159 case ERR_CONNECTION_RESET:
1160 case ERR_CONNECTION_CLOSED:
1161 case ERR_CONNECTION_ABORTED:
[email protected]2a5c76b2008-09-25 22:15:161162 if (ShouldResendRequest())
initial.commit586acc5fe2008-07-26 22:42:521163 error = OK;
initial.commit586acc5fe2008-07-26 22:42:521164 break;
1165 }
1166 return error;
1167}
1168
[email protected]c3b35c22008-09-27 03:19:421169void HttpNetworkTransaction::ResetStateForRestart() {
1170 header_buf_.reset();
1171 header_buf_capacity_ = 0;
1172 header_buf_len_ = 0;
1173 header_buf_body_offset_ = -1;
1174 header_buf_http_offset_ = -1;
[email protected]ef0faf2e72009-03-05 23:27:231175 response_body_length_ = -1;
1176 response_body_read_ = 0;
[email protected]c3b35c22008-09-27 03:19:421177 read_buf_ = NULL;
1178 read_buf_len_ = 0;
1179 request_headers_.clear();
1180 request_headers_bytes_sent_ = 0;
1181 chunked_decoder_.reset();
[email protected]038e9a32008-10-08 22:40:161182 // Reset the scoped_refptr
1183 response_.headers = NULL;
1184 response_.auth_challenge = NULL;
[email protected]c3b35c22008-09-27 03:19:421185}
1186
[email protected]2a5c76b2008-09-25 22:15:161187bool HttpNetworkTransaction::ShouldResendRequest() {
1188 // NOTE: we resend a request only if we reused a keep-alive connection.
1189 // This automatically prevents an infinite resend loop because we'll run
1190 // out of the cached keep-alive connections eventually.
1191 if (establishing_tunnel_ ||
1192 !reused_socket_ || // We didn't reuse a keep-alive connection.
1193 header_buf_len_) { // We have received some response headers.
1194 return false;
1195 }
1196 connection_.set_socket(NULL);
1197 connection_.Reset();
[email protected]372d34a2008-11-05 21:30:511198 // There are two reasons we need to clear request_headers_. 1) It contains
1199 // the real request headers, but we may need to resend the CONNECT request
1200 // first to recreate the SSL tunnel. 2) An empty request_headers_ causes
1201 // BuildRequestHeaders to be called, which rewinds request_body_stream_ to
1202 // the beginning of request_->upload_data.
1203 request_headers_.clear();
[email protected]2a5c76b2008-09-25 22:15:161204 request_headers_bytes_sent_ = 0;
[email protected]2a5c76b2008-09-25 22:15:161205 next_state_ = STATE_INIT_CONNECTION; // Resend the request.
1206 return true;
1207}
1208
[email protected]86ec30d2008-09-29 21:53:541209int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
1210 DCHECK(!pac_request_);
1211
1212 // A failure to resolve the hostname or any error related to establishing a
1213 // TCP connection could be grounds for trying a new proxy configuration.
[email protected]7be51312008-09-29 23:21:301214 //
1215 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1216 // to proxy servers. The hostname in those URLs might fail to resolve if we
1217 // are still using a non-proxy config. We need to check if a proxy config
1218 // now exists that corresponds to a proxy server that could load the URL.
1219 //
[email protected]86ec30d2008-09-29 21:53:541220 switch (error) {
1221 case ERR_NAME_NOT_RESOLVED:
1222 case ERR_INTERNET_DISCONNECTED:
1223 case ERR_ADDRESS_UNREACHABLE:
1224 case ERR_CONNECTION_CLOSED:
1225 case ERR_CONNECTION_RESET:
1226 case ERR_CONNECTION_REFUSED:
1227 case ERR_CONNECTION_ABORTED:
1228 case ERR_TIMED_OUT:
1229 case ERR_TUNNEL_CONNECTION_FAILED:
1230 break;
1231 default:
1232 return error;
1233 }
1234
[email protected]677c90572008-12-10 09:03:151235 if (request_->load_flags & LOAD_BYPASS_PROXY) {
1236 return error;
1237 }
1238
[email protected]86ec30d2008-09-29 21:53:541239 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1240 request_->url, &proxy_info_, &io_callback_, &pac_request_);
1241 if (rv == OK || rv == ERR_IO_PENDING) {
1242 connection_.set_socket(NULL);
1243 connection_.Reset();
1244 DCHECK(!request_headers_bytes_sent_);
1245 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1246 } else {
1247 rv = error;
1248 }
1249
1250 return rv;
1251}
1252
[email protected]c3b35c22008-09-27 03:19:421253void HttpNetworkTransaction::AddAuthorizationHeader(HttpAuth::Target target) {
[email protected]f9ee6b52008-11-08 06:46:231254 // If we have no authentication information, check if we can select
1255 // a cache entry preemptively (based on the path).
[email protected]5d0153c512009-01-12 19:08:361256 if (!HaveAuth(target) && !SelectPreemptiveAuth(target))
[email protected]f9ee6b52008-11-08 06:46:231257 return;
license.botbf09a502008-08-24 00:55:551258
[email protected]f9ee6b52008-11-08 06:46:231259 DCHECK(HaveAuth(target));
[email protected]aaead502008-10-15 00:20:111260
[email protected]c3b35c22008-09-27 03:19:421261 // Add a Authorization/Proxy-Authorization header line.
1262 std::string credentials = auth_handler_[target]->GenerateCredentials(
[email protected]f9ee6b52008-11-08 06:46:231263 auth_identity_[target].username,
1264 auth_identity_[target].password,
[email protected]c3b35c22008-09-27 03:19:421265 request_,
1266 &proxy_info_);
1267 request_headers_ += HttpAuth::GetAuthorizationHeaderName(target) +
1268 ": " + credentials + "\r\n";
1269}
1270
1271void HttpNetworkTransaction::ApplyAuth() {
1272 // We expect using_proxy_ and using_tunnel_ to be mutually exclusive.
1273 DCHECK(!using_proxy_ || !using_tunnel_);
1274
1275 // Don't send proxy auth after tunnel has been established.
1276 bool should_apply_proxy_auth = using_proxy_ || establishing_tunnel_;
1277
1278 // Don't send origin server auth while establishing tunnel.
1279 bool should_apply_server_auth = !establishing_tunnel_;
1280
[email protected]f9ee6b52008-11-08 06:46:231281 if (should_apply_proxy_auth)
[email protected]c3b35c22008-09-27 03:19:421282 AddAuthorizationHeader(HttpAuth::AUTH_PROXY);
[email protected]f9ee6b52008-11-08 06:46:231283 if (should_apply_server_auth)
[email protected]c3b35c22008-09-27 03:19:421284 AddAuthorizationHeader(HttpAuth::AUTH_SERVER);
1285}
1286
[email protected]f9ee6b52008-11-08 06:46:231287GURL HttpNetworkTransaction::AuthOrigin(HttpAuth::Target target) const {
1288 return target == HttpAuth::AUTH_PROXY ?
[email protected]f6fb2de2009-02-19 08:11:421289 GURL("http://" + proxy_info_.proxy_server().host_and_port()) :
[email protected]f9ee6b52008-11-08 06:46:231290 request_->url.GetOrigin();
1291}
1292
1293std::string HttpNetworkTransaction::AuthPath(HttpAuth::Target target)
1294 const {
1295 // Proxy authentication realms apply to all paths. So we will use
1296 // empty string in place of an absolute path.
1297 return target == HttpAuth::AUTH_PROXY ?
1298 std::string() : request_->url.path();
1299}
1300
1301void HttpNetworkTransaction::InvalidateRejectedAuthFromCache(
1302 HttpAuth::Target target) {
1303 DCHECK(HaveAuth(target));
1304
1305 // TODO(eroman): this short-circuit can be relaxed. If the realm of
1306 // the preemptively used auth entry matches the realm of the subsequent
1307 // challenge, then we can invalidate the preemptively used entry.
1308 // Otherwise as-is we may send the failed credentials one extra time.
1309 if (auth_identity_[target].source == HttpAuth::IDENT_SRC_PATH_LOOKUP)
1310 return;
1311
1312 // Clear the cache entry for the identity we just failed on.
1313 // Note: we require the username/password to match before invalidating
1314 // since the entry in the cache may be newer than what we used last time.
1315 session_->auth_cache()->Remove(AuthOrigin(target),
[email protected]5d0153c512009-01-12 19:08:361316 auth_handler_[target]->realm(),
[email protected]f9ee6b52008-11-08 06:46:231317 auth_identity_[target].username,
1318 auth_identity_[target].password);
1319}
1320
1321bool HttpNetworkTransaction::SelectPreemptiveAuth(HttpAuth::Target target) {
1322 DCHECK(!HaveAuth(target));
1323
1324 // Don't do preemptive authorization if the URL contains a username/password,
1325 // since we must first be challenged in order to use the URL's identity.
1326 if (request_->url.has_username())
1327 return false;
1328
1329 // SelectPreemptiveAuth() is on the critical path for each request, so it
1330 // is expected to be fast. LookupByPath() is fast in the common case, since
1331 // the number of http auth cache entries is expected to be very small.
1332 // (For most users in fact, it will be 0.)
1333
1334 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByPath(
1335 AuthOrigin(target), AuthPath(target));
1336
[email protected]3f918782009-02-28 01:29:241337 // We don't support preemptive authentication for connection-based
1338 // authentication schemes because they can't reuse entry->handler().
1339 // Hopefully we can remove this limitation in the future.
1340 if (entry && !entry->handler()->is_connection_based()) {
[email protected]f9ee6b52008-11-08 06:46:231341 auth_identity_[target].source = HttpAuth::IDENT_SRC_PATH_LOOKUP;
1342 auth_identity_[target].invalid = false;
1343 auth_identity_[target].username = entry->username();
1344 auth_identity_[target].password = entry->password();
1345 auth_handler_[target] = entry->handler();
1346 return true;
1347 }
1348 return false;
1349}
1350
1351bool HttpNetworkTransaction::SelectNextAuthIdentityToTry(
1352 HttpAuth::Target target) {
1353 DCHECK(auth_handler_[target]);
1354 DCHECK(auth_identity_[target].invalid);
1355
1356 // Try to use the username/password encoded into the URL first.
1357 // (By checking source == IDENT_SRC_NONE, we make sure that this
1358 // is only done once for the transaction.)
1359 if (target == HttpAuth::AUTH_SERVER && request_->url.has_username() &&
1360 auth_identity_[target].source == HttpAuth::IDENT_SRC_NONE) {
1361 auth_identity_[target].source = HttpAuth::IDENT_SRC_URL;
1362 auth_identity_[target].invalid = false;
[email protected]77848d12008-11-14 00:00:221363 // TODO(wtc) It may be necessary to unescape the username and password
1364 // after extracting them from the URL. We should be careful about
1365 // embedded nulls in that case.
1366 auth_identity_[target].username = ASCIIToWide(request_->url.username());
1367 auth_identity_[target].password = ASCIIToWide(request_->url.password());
[email protected]f9ee6b52008-11-08 06:46:231368 // TODO(eroman): If the password is blank, should we also try combining
1369 // with a password from the cache?
1370 return true;
1371 }
1372
1373 // Check the auth cache for a realm entry.
1374 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByRealm(
1375 AuthOrigin(target), auth_handler_[target]->realm());
1376
1377 if (entry) {
1378 // Disallow re-using of identity if the scheme of the originating challenge
1379 // does not match. This protects against the following situation:
1380 // 1. Browser prompts user to sign into DIGEST realm="Foo".
1381 // 2. Since the auth-scheme is not BASIC, the user is reasured that it
1382 // will not be sent over the wire in clear text. So they use their
1383 // most trusted password.
1384 // 3. Next, the browser receives a challenge for BASIC realm="Foo". This
1385 // is the same realm that we have a cached identity for. However if
1386 // we use that identity, it would get sent over the wire in
1387 // clear text (which isn't what the user agreed to when entering it).
1388 if (entry->handler()->scheme() != auth_handler_[target]->scheme()) {
1389 LOG(WARNING) << "The scheme of realm " << auth_handler_[target]->realm()
1390 << " has changed from " << entry->handler()->scheme()
1391 << " to " << auth_handler_[target]->scheme();
1392 return false;
1393 }
1394
1395 auth_identity_[target].source = HttpAuth::IDENT_SRC_REALM_LOOKUP;
1396 auth_identity_[target].invalid = false;
1397 auth_identity_[target].username = entry->username();
1398 auth_identity_[target].password = entry->password();
1399 return true;
1400 }
1401 return false;
1402}
1403
1404int HttpNetworkTransaction::HandleAuthChallenge() {
[email protected]c3b35c22008-09-27 03:19:421405 DCHECK(response_.headers);
1406
1407 int status = response_.headers->response_code();
1408 if (status != 401 && status != 407)
1409 return OK;
1410 HttpAuth::Target target = status == 407 ?
1411 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1412
[email protected]038e9a32008-10-08 22:40:161413 if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1414 return ERR_UNEXPECTED_PROXY_AUTH;
[email protected]c3b35c22008-09-27 03:19:421415
[email protected]f9ee6b52008-11-08 06:46:231416 // The auth we tried just failed, hence it can't be valid. Remove it from
[email protected]3f918782009-02-28 01:29:241417 // the cache so it won't be used again, unless it's a null identity.
1418 if (HaveAuth(target) &&
1419 auth_identity_[target].source != HttpAuth::IDENT_SRC_NONE)
[email protected]f9ee6b52008-11-08 06:46:231420 InvalidateRejectedAuthFromCache(target);
1421
1422 auth_identity_[target].invalid = true;
1423
[email protected]c3b35c22008-09-27 03:19:421424 // Find the best authentication challenge that we support.
[email protected]f9ee6b52008-11-08 06:46:231425 HttpAuth::ChooseBestChallenge(response_.headers.get(),
1426 target,
1427 &auth_handler_[target]);
[email protected]c3b35c22008-09-27 03:19:421428
[email protected]c744cf22009-02-27 07:28:081429 if (!auth_handler_[target]) {
1430 if (establishing_tunnel_) {
1431 // We are establishing a tunnel, we can't show the error page because an
1432 // active network attacker could control its contents. Instead, we just
1433 // fail to establish the tunnel.
[email protected]9f9f86c2009-03-12 22:32:421434 DCHECK(target == HttpAuth::AUTH_PROXY);
[email protected]c744cf22009-02-27 07:28:081435 return ERR_PROXY_AUTH_REQUESTED;
1436 }
1437 // We found no supported challenge -- let the transaction continue
1438 // so we end up displaying the error page.
[email protected]c3b35c22008-09-27 03:19:421439 return OK;
[email protected]c744cf22009-02-27 07:28:081440 }
[email protected]c3b35c22008-09-27 03:19:421441
[email protected]3f918782009-02-28 01:29:241442 bool has_identity_to_try;
1443 if (auth_handler_[target]->NeedsIdentity()) {
1444 // Pick a new auth identity to try, by looking to the URL and auth cache.
1445 // If an identity to try is found, it is saved to auth_identity_[target].
1446 has_identity_to_try = SelectNextAuthIdentityToTry(target);
1447 } else {
1448 // Proceed with a null identity.
1449 //
1450 // TODO(wtc): Add a safeguard against infinite transaction restarts, if
1451 // the server keeps returning "NTLM".
1452 auth_identity_[target].source = HttpAuth::IDENT_SRC_NONE;
1453 auth_identity_[target].invalid = false;
1454 auth_identity_[target].username.clear();
1455 auth_identity_[target].password.clear();
1456 has_identity_to_try = true;
1457 }
[email protected]f9ee6b52008-11-08 06:46:231458 DCHECK(has_identity_to_try == !auth_identity_[target].invalid);
1459
1460 if (has_identity_to_try) {
1461 DCHECK(user_callback_);
1462 PrepareForAuthRestart(target);
1463 return WILL_RESTART_TRANSACTION;
[email protected]f9ee6b52008-11-08 06:46:231464 }
1465
[email protected]74da3732009-01-30 23:45:031466 // We have exhausted all identity possibilities, all we can do now is
1467 // pass the challenge information back to the client.
1468 PopulateAuthChallenge(target);
[email protected]f9ee6b52008-11-08 06:46:231469 return OK;
1470}
1471
1472void HttpNetworkTransaction::PopulateAuthChallenge(HttpAuth::Target target) {
1473 // Populates response_.auth_challenge with the authentication challenge info.
1474 // This info is consumed by URLRequestHttpJob::GetAuthChallengeInfo().
1475
1476 AuthChallengeInfo* auth_info = new AuthChallengeInfo;
[email protected]c3b35c22008-09-27 03:19:421477 auth_info->is_proxy = target == HttpAuth::AUTH_PROXY;
[email protected]f9ee6b52008-11-08 06:46:231478 auth_info->scheme = ASCIIToWide(auth_handler_[target]->scheme());
[email protected]c3b35c22008-09-27 03:19:421479 // TODO(eroman): decode realm according to RFC 2047.
[email protected]f9ee6b52008-11-08 06:46:231480 auth_info->realm = ASCIIToWide(auth_handler_[target]->realm());
[email protected]c3b35c22008-09-27 03:19:421481 if (target == HttpAuth::AUTH_PROXY) {
[email protected]f6fb2de2009-02-19 08:11:421482 auth_info->host = ASCIIToWide(proxy_info_.proxy_server().host_and_port());
[email protected]c3b35c22008-09-27 03:19:421483 } else {
1484 DCHECK(target == HttpAuth::AUTH_SERVER);
1485 auth_info->host = ASCIIToWide(request_->url.host());
1486 }
[email protected]f9ee6b52008-11-08 06:46:231487 response_.auth_challenge = auth_info;
[email protected]c3b35c22008-09-27 03:19:421488}
1489
1490} // namespace net