blob: 2a41c6ace0510013b6d12bbdcbc483bb0d682824 [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);
[email protected]af89ba62009-03-16 20:26:38219 LogBlockedTunnelResponse(response_.headers->response_code());
[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 }
initial.commit586acc5fe2008-07-26 22:42:52655
[email protected]6b9833e2008-09-10 20:32:25656 const char* buf = request_headers_.data() + request_headers_bytes_sent_;
657 int buf_len = static_cast<int>(request_headers_.size() -
658 request_headers_bytes_sent_);
659 DCHECK(buf_len > 0);
660
661 return connection_.socket()->Write(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52662}
663
664int HttpNetworkTransaction::DoWriteHeadersComplete(int result) {
665 if (result < 0)
666 return HandleIOError(result);
667
[email protected]96d570e42008-08-05 22:43:04668 request_headers_bytes_sent_ += result;
669 if (request_headers_bytes_sent_ < request_headers_.size()) {
initial.commit586acc5fe2008-07-26 22:42:52670 next_state_ = STATE_WRITE_HEADERS;
[email protected]6b9833e2008-09-10 20:32:25671 } else if (!establishing_tunnel_ && request_->upload_data) {
initial.commit586acc5fe2008-07-26 22:42:52672 next_state_ = STATE_WRITE_BODY;
673 } else {
674 next_state_ = STATE_READ_HEADERS;
675 }
676 return OK;
677}
678
679int HttpNetworkTransaction::DoWriteBody() {
680 next_state_ = STATE_WRITE_BODY_COMPLETE;
681
682 DCHECK(request_->upload_data);
683 DCHECK(request_body_stream_.get());
684
685 const char* buf = request_body_stream_->buf();
686 int buf_len = static_cast<int>(request_body_stream_->buf_len());
687
688 return connection_.socket()->Write(buf, buf_len, &io_callback_);
689}
690
691int HttpNetworkTransaction::DoWriteBodyComplete(int result) {
692 if (result < 0)
693 return HandleIOError(result);
694
695 request_body_stream_->DidConsume(result);
696
697 if (request_body_stream_->position() < request_body_stream_->size()) {
698 next_state_ = STATE_WRITE_BODY;
699 } else {
700 next_state_ = STATE_READ_HEADERS;
701 }
702 return OK;
703}
704
705int HttpNetworkTransaction::DoReadHeaders() {
706 next_state_ = STATE_READ_HEADERS_COMPLETE;
707
[email protected]6b9833e2008-09-10 20:32:25708 // Grow the read buffer if necessary.
709 if (header_buf_len_ == header_buf_capacity_) {
710 header_buf_capacity_ += kHeaderBufInitialSize;
711 header_buf_.reset(static_cast<char*>(
712 realloc(header_buf_.release(), header_buf_capacity_)));
713 }
714
715 char* buf = header_buf_.get() + header_buf_len_;
716 int buf_len = header_buf_capacity_ - header_buf_len_;
717
718 return connection_.socket()->Read(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52719}
720
[email protected]0e75a732008-10-16 20:36:09721int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
[email protected]aecfbf22008-10-16 02:02:47722 if (establishing_tunnel_) {
[email protected]0e75a732008-10-16 20:36:09723 // The connection was closed before the tunnel could be established.
[email protected]aecfbf22008-10-16 02:02:47724 return ERR_TUNNEL_CONNECTION_FAILED;
725 }
726
727 if (has_found_status_line_start()) {
728 // Assume EOF is end-of-headers.
729 header_buf_body_offset_ = header_buf_len_;
730 return OK;
731 }
732
733 // No status line was matched yet. Could have been a HTTP/0.9 response, or
734 // a partial HTTP/1.x response.
735
736 if (header_buf_len_ == 0) {
[email protected]0e75a732008-10-16 20:36:09737 // The connection was closed before any data was sent. Likely an error
738 // rather than empty HTTP/0.9 response.
[email protected]aecfbf22008-10-16 02:02:47739 return ERR_EMPTY_RESPONSE;
740 }
741
742 // Assume everything else is a HTTP/0.9 response (including responses
743 // of 'h', 'ht', 'htt').
744 header_buf_body_offset_ = 0;
745 return OK;
746}
747
initial.commit586acc5fe2008-07-26 22:42:52748int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
749 if (result < 0)
750 return HandleIOError(result);
751
[email protected]2a5c76b2008-09-25 22:15:16752 if (result == 0 && ShouldResendRequest())
753 return result;
754
initial.commit586acc5fe2008-07-26 22:42:52755 // Record our best estimate of the 'response time' as the time when we read
756 // the first bytes of the response headers.
757 if (header_buf_len_ == 0)
758 response_.response_time = Time::Now();
759
[email protected]231d5a32008-09-13 00:45:27760 // The socket was closed before we found end-of-headers.
initial.commit586acc5fe2008-07-26 22:42:52761 if (result == 0) {
[email protected]0e75a732008-10-16 20:36:09762 int rv = HandleConnectionClosedBeforeEndOfHeaders();
[email protected]aecfbf22008-10-16 02:02:47763 if (rv != OK)
764 return rv;
initial.commit586acc5fe2008-07-26 22:42:52765 } else {
766 header_buf_len_ += result;
767 DCHECK(header_buf_len_ <= header_buf_capacity_);
768
[email protected]231d5a32008-09-13 00:45:27769 // Look for the start of the status line, if it hasn't been found yet.
770 if (!has_found_status_line_start()) {
771 header_buf_http_offset_ = HttpUtil::LocateStartOfStatusLine(
772 header_buf_.get(), header_buf_len_);
initial.commit586acc5fe2008-07-26 22:42:52773 }
[email protected]231d5a32008-09-13 00:45:27774
775 if (has_found_status_line_start()) {
776 int eoh = HttpUtil::LocateEndOfHeaders(
777 header_buf_.get(), header_buf_len_, header_buf_http_offset_);
778 if (eoh == -1) {
[email protected]4ddaf2502008-10-23 18:26:19779 // Prevent growing the headers buffer indefinitely.
780 if (header_buf_len_ >= kMaxHeaderBufSize)
781 return ERR_RESPONSE_HEADERS_TOO_BIG;
782
[email protected]231d5a32008-09-13 00:45:27783 // Haven't found the end of headers yet, keep reading.
784 next_state_ = STATE_READ_HEADERS;
785 return OK;
786 }
787 header_buf_body_offset_ = eoh;
788 } else if (header_buf_len_ < 8) {
789 // Not enough data to decide whether this is HTTP/0.9 yet.
790 // 8 bytes = (4 bytes of junk) + "http".length()
791 next_state_ = STATE_READ_HEADERS;
792 return OK;
793 } else {
794 // Enough data was read -- there is no status line.
795 header_buf_body_offset_ = 0;
796 }
initial.commit586acc5fe2008-07-26 22:42:52797 }
[email protected]65f11402008-10-31 17:39:44798
[email protected]6b9833e2008-09-10 20:32:25799 // And, we are done with the Start or the SSL tunnel CONNECT sequence.
[email protected]27161fb2008-11-03 23:39:05800 return DidReadResponseHeaders();
initial.commit586acc5fe2008-07-26 22:42:52801}
802
803int HttpNetworkTransaction::DoReadBody() {
804 DCHECK(read_buf_);
805 DCHECK(read_buf_len_ > 0);
806 DCHECK(connection_.is_initialized());
807
808 next_state_ = STATE_READ_BODY_COMPLETE;
809
[email protected]f9d44aa2008-09-23 23:57:17810 // We may have already consumed the indicated content length.
[email protected]ef0faf2e72009-03-05 23:27:23811 if (response_body_length_ != -1 &&
812 response_body_read_ >= response_body_length_)
[email protected]f9d44aa2008-09-23 23:57:17813 return 0;
814
[email protected]96d570e42008-08-05 22:43:04815 // We may have some data remaining in the header buffer.
initial.commit586acc5fe2008-07-26 22:42:52816 if (header_buf_.get() && header_buf_body_offset_ < header_buf_len_) {
817 int n = std::min(read_buf_len_, header_buf_len_ - header_buf_body_offset_);
[email protected]9dea9e1f2009-01-29 00:30:47818 memcpy(read_buf_->data(), header_buf_.get() + header_buf_body_offset_, n);
initial.commit586acc5fe2008-07-26 22:42:52819 header_buf_body_offset_ += n;
[email protected]96d570e42008-08-05 22:43:04820 if (header_buf_body_offset_ == header_buf_len_) {
initial.commit586acc5fe2008-07-26 22:42:52821 header_buf_.reset();
[email protected]96d570e42008-08-05 22:43:04822 header_buf_capacity_ = 0;
823 header_buf_len_ = 0;
824 header_buf_body_offset_ = -1;
825 }
initial.commit586acc5fe2008-07-26 22:42:52826 return n;
827 }
828
[email protected]9dea9e1f2009-01-29 00:30:47829 return connection_.socket()->Read(read_buf_->data(), read_buf_len_,
830 &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52831}
832
833int HttpNetworkTransaction::DoReadBodyComplete(int result) {
834 // We are done with the Read call.
[email protected]c744cf22009-02-27 07:28:08835 DCHECK(!establishing_tunnel_) <<
836 "We should never read a response body of a tunnel.";
initial.commit586acc5fe2008-07-26 22:42:52837
[email protected]96d570e42008-08-05 22:43:04838 bool unfiltered_eof = (result == 0);
839
initial.commit586acc5fe2008-07-26 22:42:52840 // Filter incoming data if appropriate. FilterBuf may return an error.
841 if (result > 0 && chunked_decoder_.get()) {
[email protected]9dea9e1f2009-01-29 00:30:47842 result = chunked_decoder_->FilterBuf(read_buf_->data(), result);
[email protected]96d570e42008-08-05 22:43:04843 if (result == 0 && !chunked_decoder_->reached_eof()) {
initial.commit586acc5fe2008-07-26 22:42:52844 // Don't signal completion of the Read call yet or else it'll look like
845 // we received end-of-file. Wait for more data.
846 next_state_ = STATE_READ_BODY;
847 return OK;
848 }
849 }
850
851 bool done = false, keep_alive = false;
852 if (result < 0) {
853 // Error while reading the socket.
854 done = true;
855 } else {
[email protected]ef0faf2e72009-03-05 23:27:23856 response_body_read_ += result;
[email protected]96d570e42008-08-05 22:43:04857 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23858 (response_body_length_ != -1 &&
859 response_body_read_ >= response_body_length_) ||
initial.commit586acc5fe2008-07-26 22:42:52860 (chunked_decoder_.get() && chunked_decoder_->reached_eof())) {
861 done = true;
862 keep_alive = response_.headers->IsKeepAlive();
[email protected]96d570e42008-08-05 22:43:04863 // We can't reuse the connection if we read more than the advertised
[email protected]c744cf22009-02-27 07:28:08864 // content length.
[email protected]f4e426b2008-11-05 00:24:49865 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23866 (response_body_length_ != -1 &&
867 response_body_read_ > response_body_length_))
[email protected]96d570e42008-08-05 22:43:04868 keep_alive = false;
initial.commit586acc5fe2008-07-26 22:42:52869 }
870 }
871
[email protected]2d2697f92009-02-18 21:00:32872 // Clean up connection_ if we are done.
initial.commit586acc5fe2008-07-26 22:42:52873 if (done) {
[email protected]56300172008-11-06 18:42:55874 LogTransactionMetrics();
initial.commit586acc5fe2008-07-26 22:42:52875 if (!keep_alive)
876 connection_.set_socket(NULL);
877 connection_.Reset();
[email protected]96d570e42008-08-05 22:43:04878 // The next Read call will return 0 (EOF).
initial.commit586acc5fe2008-07-26 22:42:52879 }
880
881 // Clear these to avoid leaving around old state.
882 read_buf_ = NULL;
883 read_buf_len_ = 0;
884
885 return result;
886}
887
[email protected]2d2697f92009-02-18 21:00:32888int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
889 // This method differs from DoReadBody only in the next_state_. So we just
890 // call DoReadBody and override the next_state_. Perhaps there is a more
891 // elegant way for these two methods to share code.
892 int rv = DoReadBody();
893 DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
894 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
895 return rv;
896}
897
898// TODO(wtc): The first two thirds of this method and the DoReadBodyComplete
899// method are almost the same. Figure out a good way for these two methods
900// to share code.
901int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
902 bool unfiltered_eof = (result == 0);
903
904 // Filter incoming data if appropriate. FilterBuf may return an error.
905 if (result > 0 && chunked_decoder_.get()) {
906 result = chunked_decoder_->FilterBuf(read_buf_->data(), result);
907 if (result == 0 && !chunked_decoder_->reached_eof()) {
908 // Don't signal completion of the Read call yet or else it'll look like
909 // we received end-of-file. Wait for more data.
910 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
911 return OK;
912 }
913 }
914
915 bool done = false, keep_alive = false;
916 if (result < 0) {
917 // Error while reading the socket.
918 done = true;
919 } else {
[email protected]ef0faf2e72009-03-05 23:27:23920 response_body_read_ += result;
[email protected]2d2697f92009-02-18 21:00:32921 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23922 (response_body_length_ != -1 &&
923 response_body_read_ >= response_body_length_) ||
[email protected]2d2697f92009-02-18 21:00:32924 (chunked_decoder_.get() && chunked_decoder_->reached_eof())) {
925 done = true;
926 keep_alive = response_.headers->IsKeepAlive();
927 // We can't reuse the connection if we read more than the advertised
928 // content length.
929 if (unfiltered_eof ||
[email protected]ef0faf2e72009-03-05 23:27:23930 (response_body_length_ != -1 &&
931 response_body_read_ > response_body_length_))
[email protected]2d2697f92009-02-18 21:00:32932 keep_alive = false;
933 }
934 }
935
936 if (done) {
937 DidDrainBodyForAuthRestart(keep_alive);
938 } else {
939 // Keep draining.
940 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
941 }
942
943 return OK;
944}
945
[email protected]56300172008-11-06 18:42:55946void HttpNetworkTransaction::LogTransactionMetrics() const {
947 base::TimeDelta duration = base::Time::Now() - response_.request_time;
948 if (60 < duration.InMinutes())
949 return;
[email protected]553dba62009-02-24 19:08:23950 UMA_HISTOGRAM_LONG_TIMES("Net.Transaction_Latency", duration);
[email protected]56300172008-11-06 18:42:55951 if (!duration.InMilliseconds())
952 return;
[email protected]553dba62009-02-24 19:08:23953 UMA_HISTOGRAM_COUNTS("Net.Transaction_Bandwidth",
[email protected]ef0faf2e72009-03-05 23:27:23954 static_cast<int> (response_body_read_ / duration.InMilliseconds()));
[email protected]56300172008-11-06 18:42:55955}
956
[email protected]9f9f86c2009-03-12 22:32:42957void HttpNetworkTransaction::LogBlockedTunnelResponse(
[email protected]af89ba62009-03-16 20:26:38958 int response_code) const {
959 LOG(WARNING) << "Blocked proxy response with status " << response_code
960 << " to CONNECT request for " << request_->url.host() << ":"
[email protected]9f9f86c2009-03-12 22:32:42961 << request_->url.EffectiveIntPort() << ".";
962}
963
[email protected]27161fb2008-11-03 23:39:05964int HttpNetworkTransaction::DidReadResponseHeaders() {
[email protected]231d5a32008-09-13 00:45:27965 scoped_refptr<HttpResponseHeaders> headers;
966 if (has_found_status_line_start()) {
967 headers = new HttpResponseHeaders(
968 HttpUtil::AssembleRawHeaders(
969 header_buf_.get(), header_buf_body_offset_));
970 } else {
971 // Fabricate a status line to to preserve the HTTP/0.9 version.
972 // (otherwise HttpResponseHeaders will default it to HTTP/1.0).
973 headers = new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
974 }
975
[email protected]f9d44aa2008-09-23 23:57:17976 if (headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
977 // Require the "HTTP/1.x" status line for SSL CONNECT.
978 if (establishing_tunnel_)
979 return ERR_TUNNEL_CONNECTION_FAILED;
[email protected]231d5a32008-09-13 00:45:27980
[email protected]f9d44aa2008-09-23 23:57:17981 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
982 // indicates a buggy server. See:
983 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
984 if (request_->method == "PUT")
985 return ERR_METHOD_NOT_SUPPORTED;
986 }
initial.commit586acc5fe2008-07-26 22:42:52987
[email protected]d1ec59082009-02-11 02:48:15988 if (establishing_tunnel_) {
[email protected]c744cf22009-02-27 07:28:08989 switch (headers->response_code()) {
990 case 200: // OK
991 if (header_buf_body_offset_ != header_buf_len_) {
992 // The proxy sent extraneous data after the headers.
993 return ERR_TUNNEL_CONNECTION_FAILED;
994 }
995 next_state_ = STATE_SSL_CONNECT_OVER_TUNNEL;
996 // Reset for the real request and response headers.
997 request_headers_.clear();
998 request_headers_bytes_sent_ = 0;
999 header_buf_len_ = 0;
1000 header_buf_body_offset_ = 0;
1001 establishing_tunnel_ = false;
1002 return OK;
1003
1004 // We aren't able to CONNECT to the remote host through the proxy. We
1005 // need to be very suspicious about the response because an active network
1006 // attacker can force us into this state by masquerading as the proxy.
1007 // The only safe thing to do here is to fail the connection because our
1008 // client is expecting an SSL protected response.
1009 // See http://crbug.com/7338.
1010 case 407: // Proxy Authentication Required
1011 // We need this status code to allow proxy authentication. Our
1012 // authentication code is smart enough to avoid being tricked by an
1013 // active network attacker.
1014 break;
1015 default:
1016 // For all other status codes, we conservatively fail the CONNECT
1017 // request.
1018 // We lose something by doing this. We have seen proxy 403, 404, and
1019 // 501 response bodies that contain a useful error message. For
1020 // example, Squid uses a 404 response to report the DNS error: "The
1021 // domain name does not exist."
[email protected]af89ba62009-03-16 20:26:381022 LogBlockedTunnelResponse(headers->response_code());
[email protected]d1ec59082009-02-11 02:48:151023 return ERR_TUNNEL_CONNECTION_FAILED;
[email protected]d1ec59082009-02-11 02:48:151024 }
[email protected]d1ec59082009-02-11 02:48:151025 }
1026
initial.commit586acc5fe2008-07-26 22:42:521027 // Check for an intermediate 100 Continue response. An origin server is
1028 // allowed to send this response even if we didn't ask for it, so we just
1029 // need to skip over it.
1030 if (headers->response_code() == 100) {
[email protected]96d570e42008-08-05 22:43:041031 header_buf_len_ -= header_buf_body_offset_;
1032 // If we've already received some bytes after the 100 Continue response,
1033 // move them to the beginning of header_buf_.
1034 if (header_buf_len_) {
1035 memmove(header_buf_.get(), header_buf_.get() + header_buf_body_offset_,
1036 header_buf_len_);
1037 }
initial.commit586acc5fe2008-07-26 22:42:521038 header_buf_body_offset_ = -1;
1039 next_state_ = STATE_READ_HEADERS;
1040 return OK;
1041 }
1042
1043 response_.headers = headers;
1044 response_.vary_data.Init(*request_, *response_.headers);
1045
1046 // Figure how to determine EOF:
1047
[email protected]ef0faf2e72009-03-05 23:27:231048 // For certain responses, we know the content length is always 0. From
1049 // RFC 2616 Section 4.3 Message Body:
1050 //
1051 // For response messages, whether or not a message-body is included with
1052 // a message is dependent on both the request method and the response
1053 // status code (section 6.1.1). All responses to the HEAD request method
1054 // MUST NOT include a message-body, even though the presence of entity-
1055 // header fields might lead one to believe they do. All 1xx
1056 // (informational), 204 (no content), and 304 (not modified) responses
1057 // MUST NOT include a message-body. All other responses do include a
1058 // message-body, although it MAY be of zero length.
initial.commit586acc5fe2008-07-26 22:42:521059 switch (response_.headers->response_code()) {
[email protected]96d570e42008-08-05 22:43:041060 case 204: // No Content
1061 case 205: // Reset Content
1062 case 304: // Not Modified
[email protected]ef0faf2e72009-03-05 23:27:231063 response_body_length_ = 0;
initial.commit586acc5fe2008-07-26 22:42:521064 break;
1065 }
[email protected]ef0faf2e72009-03-05 23:27:231066 if (request_->method == "HEAD")
1067 response_body_length_ = 0;
initial.commit586acc5fe2008-07-26 22:42:521068
[email protected]ef0faf2e72009-03-05 23:27:231069 if (response_body_length_ == -1) {
initial.commit586acc5fe2008-07-26 22:42:521070 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
1071 // Otherwise "Transfer-Encoding: chunked" trumps "Content-Length: N"
[email protected]f9d44aa2008-09-23 23:57:171072 if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1) &&
initial.commit586acc5fe2008-07-26 22:42:521073 response_.headers->HasHeaderValue("Transfer-Encoding", "chunked")) {
1074 chunked_decoder_.reset(new HttpChunkedDecoder());
1075 } else {
[email protected]ef0faf2e72009-03-05 23:27:231076 response_body_length_ = response_.headers->GetContentLength();
1077 // If response_body_length_ is still -1, then we have to wait for the
1078 // server to close the connection.
initial.commit586acc5fe2008-07-26 22:42:521079 }
1080 }
1081
[email protected]2d2697f92009-02-18 21:00:321082 int rv = HandleAuthChallenge();
1083 if (rv == WILL_RESTART_TRANSACTION)
1084 return OK;
1085 if (rv != OK)
1086 return rv;
1087
[email protected]6b9833e2008-09-10 20:32:251088 if (using_ssl_ && !establishing_tunnel_) {
[email protected]4628a2a2008-08-14 20:33:251089 SSLClientSocket* ssl_socket =
1090 reinterpret_cast<SSLClientSocket*>(connection_.socket());
1091 ssl_socket->GetSSLInfo(&response_.ssl_info);
1092 }
1093
initial.commit586acc5fe2008-07-26 22:42:521094 return OK;
1095}
1096
[email protected]ccb40e52008-09-17 20:54:401097int HttpNetworkTransaction::HandleCertificateError(int error) {
1098 DCHECK(using_ssl_);
1099
1100 const int kCertFlags = LOAD_IGNORE_CERT_COMMON_NAME_INVALID |
1101 LOAD_IGNORE_CERT_DATE_INVALID |
1102 LOAD_IGNORE_CERT_AUTHORITY_INVALID |
1103 LOAD_IGNORE_CERT_WRONG_USAGE;
1104 if (request_->load_flags & kCertFlags) {
1105 switch (error) {
1106 case ERR_CERT_COMMON_NAME_INVALID:
1107 if (request_->load_flags & LOAD_IGNORE_CERT_COMMON_NAME_INVALID)
1108 error = OK;
1109 break;
1110 case ERR_CERT_DATE_INVALID:
1111 if (request_->load_flags & LOAD_IGNORE_CERT_DATE_INVALID)
1112 error = OK;
1113 break;
1114 case ERR_CERT_AUTHORITY_INVALID:
1115 if (request_->load_flags & LOAD_IGNORE_CERT_AUTHORITY_INVALID)
1116 error = OK;
1117 break;
1118 }
1119 }
1120
1121 if (error != OK) {
1122 SSLClientSocket* ssl_socket =
1123 reinterpret_cast<SSLClientSocket*>(connection_.socket());
1124 ssl_socket->GetSSLInfo(&response_.ssl_info);
1125 }
1126 return error;
1127}
1128
[email protected]c5949a32008-10-08 17:28:231129int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
[email protected]5a179bcc2008-10-13 18:10:591130 switch (error) {
1131 case ERR_SSL_PROTOCOL_ERROR:
1132 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
[email protected]aaead502008-10-15 00:20:111133 if (ssl_config_.tls1_enabled) {
[email protected]5a179bcc2008-10-13 18:10:591134 // This could be a TLS-intolerant server or an SSL 3.0 server that
1135 // chose a TLS-only cipher suite. Turn off TLS 1.0 and retry.
[email protected]aaead502008-10-15 00:20:111136 ssl_config_.tls1_enabled = false;
[email protected]5a179bcc2008-10-13 18:10:591137 connection_.set_socket(NULL);
1138 connection_.Reset();
1139 next_state_ = STATE_INIT_CONNECTION;
1140 error = OK;
1141 }
1142 break;
[email protected]c5949a32008-10-08 17:28:231143 }
[email protected]c5949a32008-10-08 17:28:231144 return error;
1145}
1146
[email protected]96d570e42008-08-05 22:43:041147// This method determines whether it is safe to resend the request after an
1148// IO error. It can only be called in response to request header or body
1149// write errors or response header read errors. It should not be used in
1150// other cases, such as a Connect error.
initial.commit586acc5fe2008-07-26 22:42:521151int HttpNetworkTransaction::HandleIOError(int error) {
1152 switch (error) {
1153 // If we try to reuse a connection that the server is in the process of
1154 // closing, we may end up successfully writing out our request (or a
1155 // portion of our request) only to find a connection error when we try to
1156 // read from (or finish writing to) the socket.
1157 case ERR_CONNECTION_RESET:
1158 case ERR_CONNECTION_CLOSED:
1159 case ERR_CONNECTION_ABORTED:
[email protected]2a5c76b2008-09-25 22:15:161160 if (ShouldResendRequest())
initial.commit586acc5fe2008-07-26 22:42:521161 error = OK;
initial.commit586acc5fe2008-07-26 22:42:521162 break;
1163 }
1164 return error;
1165}
1166
[email protected]c3b35c22008-09-27 03:19:421167void HttpNetworkTransaction::ResetStateForRestart() {
1168 header_buf_.reset();
1169 header_buf_capacity_ = 0;
1170 header_buf_len_ = 0;
1171 header_buf_body_offset_ = -1;
1172 header_buf_http_offset_ = -1;
[email protected]ef0faf2e72009-03-05 23:27:231173 response_body_length_ = -1;
1174 response_body_read_ = 0;
[email protected]c3b35c22008-09-27 03:19:421175 read_buf_ = NULL;
1176 read_buf_len_ = 0;
1177 request_headers_.clear();
1178 request_headers_bytes_sent_ = 0;
1179 chunked_decoder_.reset();
[email protected]89ceba9a2009-03-21 03:46:061180 // Reset all the members of response_.
1181 response_ = HttpResponseInfo();
[email protected]c3b35c22008-09-27 03:19:421182}
1183
[email protected]2a5c76b2008-09-25 22:15:161184bool HttpNetworkTransaction::ShouldResendRequest() {
1185 // NOTE: we resend a request only if we reused a keep-alive connection.
1186 // This automatically prevents an infinite resend loop because we'll run
1187 // out of the cached keep-alive connections eventually.
1188 if (establishing_tunnel_ ||
1189 !reused_socket_ || // We didn't reuse a keep-alive connection.
1190 header_buf_len_) { // We have received some response headers.
1191 return false;
1192 }
1193 connection_.set_socket(NULL);
1194 connection_.Reset();
[email protected]372d34a2008-11-05 21:30:511195 // There are two reasons we need to clear request_headers_. 1) It contains
1196 // the real request headers, but we may need to resend the CONNECT request
1197 // first to recreate the SSL tunnel. 2) An empty request_headers_ causes
1198 // BuildRequestHeaders to be called, which rewinds request_body_stream_ to
1199 // the beginning of request_->upload_data.
1200 request_headers_.clear();
[email protected]2a5c76b2008-09-25 22:15:161201 request_headers_bytes_sent_ = 0;
[email protected]2a5c76b2008-09-25 22:15:161202 next_state_ = STATE_INIT_CONNECTION; // Resend the request.
1203 return true;
1204}
1205
[email protected]86ec30d2008-09-29 21:53:541206int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
1207 DCHECK(!pac_request_);
1208
1209 // A failure to resolve the hostname or any error related to establishing a
1210 // TCP connection could be grounds for trying a new proxy configuration.
[email protected]7be51312008-09-29 23:21:301211 //
1212 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1213 // to proxy servers. The hostname in those URLs might fail to resolve if we
1214 // are still using a non-proxy config. We need to check if a proxy config
1215 // now exists that corresponds to a proxy server that could load the URL.
1216 //
[email protected]86ec30d2008-09-29 21:53:541217 switch (error) {
1218 case ERR_NAME_NOT_RESOLVED:
1219 case ERR_INTERNET_DISCONNECTED:
1220 case ERR_ADDRESS_UNREACHABLE:
1221 case ERR_CONNECTION_CLOSED:
1222 case ERR_CONNECTION_RESET:
1223 case ERR_CONNECTION_REFUSED:
1224 case ERR_CONNECTION_ABORTED:
1225 case ERR_TIMED_OUT:
1226 case ERR_TUNNEL_CONNECTION_FAILED:
1227 break;
1228 default:
1229 return error;
1230 }
1231
[email protected]677c90572008-12-10 09:03:151232 if (request_->load_flags & LOAD_BYPASS_PROXY) {
1233 return error;
1234 }
1235
[email protected]86ec30d2008-09-29 21:53:541236 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1237 request_->url, &proxy_info_, &io_callback_, &pac_request_);
1238 if (rv == OK || rv == ERR_IO_PENDING) {
1239 connection_.set_socket(NULL);
1240 connection_.Reset();
1241 DCHECK(!request_headers_bytes_sent_);
1242 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1243 } else {
1244 rv = error;
1245 }
1246
1247 return rv;
1248}
1249
[email protected]c3b35c22008-09-27 03:19:421250void HttpNetworkTransaction::AddAuthorizationHeader(HttpAuth::Target target) {
[email protected]f9ee6b52008-11-08 06:46:231251 // If we have no authentication information, check if we can select
1252 // a cache entry preemptively (based on the path).
[email protected]5d0153c512009-01-12 19:08:361253 if (!HaveAuth(target) && !SelectPreemptiveAuth(target))
[email protected]f9ee6b52008-11-08 06:46:231254 return;
license.botbf09a502008-08-24 00:55:551255
[email protected]f9ee6b52008-11-08 06:46:231256 DCHECK(HaveAuth(target));
[email protected]aaead502008-10-15 00:20:111257
[email protected]c3b35c22008-09-27 03:19:421258 // Add a Authorization/Proxy-Authorization header line.
1259 std::string credentials = auth_handler_[target]->GenerateCredentials(
[email protected]f9ee6b52008-11-08 06:46:231260 auth_identity_[target].username,
1261 auth_identity_[target].password,
[email protected]c3b35c22008-09-27 03:19:421262 request_,
1263 &proxy_info_);
1264 request_headers_ += HttpAuth::GetAuthorizationHeaderName(target) +
1265 ": " + credentials + "\r\n";
1266}
1267
1268void HttpNetworkTransaction::ApplyAuth() {
1269 // We expect using_proxy_ and using_tunnel_ to be mutually exclusive.
1270 DCHECK(!using_proxy_ || !using_tunnel_);
1271
1272 // Don't send proxy auth after tunnel has been established.
1273 bool should_apply_proxy_auth = using_proxy_ || establishing_tunnel_;
1274
1275 // Don't send origin server auth while establishing tunnel.
1276 bool should_apply_server_auth = !establishing_tunnel_;
1277
[email protected]f9ee6b52008-11-08 06:46:231278 if (should_apply_proxy_auth)
[email protected]c3b35c22008-09-27 03:19:421279 AddAuthorizationHeader(HttpAuth::AUTH_PROXY);
[email protected]f9ee6b52008-11-08 06:46:231280 if (should_apply_server_auth)
[email protected]c3b35c22008-09-27 03:19:421281 AddAuthorizationHeader(HttpAuth::AUTH_SERVER);
1282}
1283
[email protected]f9ee6b52008-11-08 06:46:231284GURL HttpNetworkTransaction::AuthOrigin(HttpAuth::Target target) const {
1285 return target == HttpAuth::AUTH_PROXY ?
[email protected]f6fb2de2009-02-19 08:11:421286 GURL("http://" + proxy_info_.proxy_server().host_and_port()) :
[email protected]f9ee6b52008-11-08 06:46:231287 request_->url.GetOrigin();
1288}
1289
1290std::string HttpNetworkTransaction::AuthPath(HttpAuth::Target target)
1291 const {
1292 // Proxy authentication realms apply to all paths. So we will use
1293 // empty string in place of an absolute path.
1294 return target == HttpAuth::AUTH_PROXY ?
1295 std::string() : request_->url.path();
1296}
1297
1298void HttpNetworkTransaction::InvalidateRejectedAuthFromCache(
1299 HttpAuth::Target target) {
1300 DCHECK(HaveAuth(target));
1301
1302 // TODO(eroman): this short-circuit can be relaxed. If the realm of
1303 // the preemptively used auth entry matches the realm of the subsequent
1304 // challenge, then we can invalidate the preemptively used entry.
1305 // Otherwise as-is we may send the failed credentials one extra time.
1306 if (auth_identity_[target].source == HttpAuth::IDENT_SRC_PATH_LOOKUP)
1307 return;
1308
1309 // Clear the cache entry for the identity we just failed on.
1310 // Note: we require the username/password to match before invalidating
1311 // since the entry in the cache may be newer than what we used last time.
1312 session_->auth_cache()->Remove(AuthOrigin(target),
[email protected]5d0153c512009-01-12 19:08:361313 auth_handler_[target]->realm(),
[email protected]f9ee6b52008-11-08 06:46:231314 auth_identity_[target].username,
1315 auth_identity_[target].password);
1316}
1317
1318bool HttpNetworkTransaction::SelectPreemptiveAuth(HttpAuth::Target target) {
1319 DCHECK(!HaveAuth(target));
1320
1321 // Don't do preemptive authorization if the URL contains a username/password,
1322 // since we must first be challenged in order to use the URL's identity.
1323 if (request_->url.has_username())
1324 return false;
1325
1326 // SelectPreemptiveAuth() is on the critical path for each request, so it
1327 // is expected to be fast. LookupByPath() is fast in the common case, since
1328 // the number of http auth cache entries is expected to be very small.
1329 // (For most users in fact, it will be 0.)
1330
1331 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByPath(
1332 AuthOrigin(target), AuthPath(target));
1333
[email protected]3f918782009-02-28 01:29:241334 // We don't support preemptive authentication for connection-based
1335 // authentication schemes because they can't reuse entry->handler().
1336 // Hopefully we can remove this limitation in the future.
1337 if (entry && !entry->handler()->is_connection_based()) {
[email protected]f9ee6b52008-11-08 06:46:231338 auth_identity_[target].source = HttpAuth::IDENT_SRC_PATH_LOOKUP;
1339 auth_identity_[target].invalid = false;
1340 auth_identity_[target].username = entry->username();
1341 auth_identity_[target].password = entry->password();
1342 auth_handler_[target] = entry->handler();
1343 return true;
1344 }
1345 return false;
1346}
1347
1348bool HttpNetworkTransaction::SelectNextAuthIdentityToTry(
1349 HttpAuth::Target target) {
1350 DCHECK(auth_handler_[target]);
1351 DCHECK(auth_identity_[target].invalid);
1352
1353 // Try to use the username/password encoded into the URL first.
1354 // (By checking source == IDENT_SRC_NONE, we make sure that this
1355 // is only done once for the transaction.)
1356 if (target == HttpAuth::AUTH_SERVER && request_->url.has_username() &&
1357 auth_identity_[target].source == HttpAuth::IDENT_SRC_NONE) {
1358 auth_identity_[target].source = HttpAuth::IDENT_SRC_URL;
1359 auth_identity_[target].invalid = false;
[email protected]77848d12008-11-14 00:00:221360 // TODO(wtc) It may be necessary to unescape the username and password
1361 // after extracting them from the URL. We should be careful about
1362 // embedded nulls in that case.
1363 auth_identity_[target].username = ASCIIToWide(request_->url.username());
1364 auth_identity_[target].password = ASCIIToWide(request_->url.password());
[email protected]f9ee6b52008-11-08 06:46:231365 // TODO(eroman): If the password is blank, should we also try combining
1366 // with a password from the cache?
1367 return true;
1368 }
1369
1370 // Check the auth cache for a realm entry.
1371 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByRealm(
1372 AuthOrigin(target), auth_handler_[target]->realm());
1373
1374 if (entry) {
1375 // Disallow re-using of identity if the scheme of the originating challenge
1376 // does not match. This protects against the following situation:
1377 // 1. Browser prompts user to sign into DIGEST realm="Foo".
1378 // 2. Since the auth-scheme is not BASIC, the user is reasured that it
1379 // will not be sent over the wire in clear text. So they use their
1380 // most trusted password.
1381 // 3. Next, the browser receives a challenge for BASIC realm="Foo". This
1382 // is the same realm that we have a cached identity for. However if
1383 // we use that identity, it would get sent over the wire in
1384 // clear text (which isn't what the user agreed to when entering it).
1385 if (entry->handler()->scheme() != auth_handler_[target]->scheme()) {
1386 LOG(WARNING) << "The scheme of realm " << auth_handler_[target]->realm()
1387 << " has changed from " << entry->handler()->scheme()
1388 << " to " << auth_handler_[target]->scheme();
1389 return false;
1390 }
1391
1392 auth_identity_[target].source = HttpAuth::IDENT_SRC_REALM_LOOKUP;
1393 auth_identity_[target].invalid = false;
1394 auth_identity_[target].username = entry->username();
1395 auth_identity_[target].password = entry->password();
1396 return true;
1397 }
1398 return false;
1399}
1400
1401int HttpNetworkTransaction::HandleAuthChallenge() {
[email protected]c3b35c22008-09-27 03:19:421402 DCHECK(response_.headers);
1403
1404 int status = response_.headers->response_code();
1405 if (status != 401 && status != 407)
1406 return OK;
1407 HttpAuth::Target target = status == 407 ?
1408 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1409
[email protected]038e9a32008-10-08 22:40:161410 if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1411 return ERR_UNEXPECTED_PROXY_AUTH;
[email protected]c3b35c22008-09-27 03:19:421412
[email protected]f9ee6b52008-11-08 06:46:231413 // The auth we tried just failed, hence it can't be valid. Remove it from
[email protected]3f918782009-02-28 01:29:241414 // the cache so it won't be used again, unless it's a null identity.
1415 if (HaveAuth(target) &&
1416 auth_identity_[target].source != HttpAuth::IDENT_SRC_NONE)
[email protected]f9ee6b52008-11-08 06:46:231417 InvalidateRejectedAuthFromCache(target);
1418
1419 auth_identity_[target].invalid = true;
1420
[email protected]c3b35c22008-09-27 03:19:421421 // Find the best authentication challenge that we support.
[email protected]f9ee6b52008-11-08 06:46:231422 HttpAuth::ChooseBestChallenge(response_.headers.get(),
1423 target,
1424 &auth_handler_[target]);
[email protected]c3b35c22008-09-27 03:19:421425
[email protected]c744cf22009-02-27 07:28:081426 if (!auth_handler_[target]) {
1427 if (establishing_tunnel_) {
[email protected]655bdba2009-03-13 23:35:381428 // Log an error message to help debug http://crbug.com/8771.
1429 std::string auth_target(target == HttpAuth::AUTH_PROXY ?
1430 "proxy" : "server");
1431 LOG(ERROR) << "Can't perform auth to the " << auth_target << " "
1432 << AuthOrigin(target).spec()
1433 << " when establishing a tunnel";
1434
1435 std::string challenge;
1436 void* iter = NULL;
1437 while (response_.headers->EnumerateHeader(&iter, "Proxy-Authenticate",
1438 &challenge)) {
1439 LOG(ERROR) << " Has header Proxy-Authenticate: " << challenge;
1440 }
1441
1442 iter = NULL;
1443 while (response_.headers->EnumerateHeader(&iter, "WWW-Authenticate",
1444 &challenge)) {
1445 LOG(ERROR) << " Has header WWW-Authenticate: " << challenge;
1446 }
1447
[email protected]c744cf22009-02-27 07:28:081448 // We are establishing a tunnel, we can't show the error page because an
1449 // active network attacker could control its contents. Instead, we just
1450 // fail to establish the tunnel.
[email protected]9f9f86c2009-03-12 22:32:421451 DCHECK(target == HttpAuth::AUTH_PROXY);
[email protected]c744cf22009-02-27 07:28:081452 return ERR_PROXY_AUTH_REQUESTED;
1453 }
1454 // We found no supported challenge -- let the transaction continue
1455 // so we end up displaying the error page.
[email protected]c3b35c22008-09-27 03:19:421456 return OK;
[email protected]c744cf22009-02-27 07:28:081457 }
[email protected]c3b35c22008-09-27 03:19:421458
[email protected]3f918782009-02-28 01:29:241459 bool has_identity_to_try;
1460 if (auth_handler_[target]->NeedsIdentity()) {
1461 // Pick a new auth identity to try, by looking to the URL and auth cache.
1462 // If an identity to try is found, it is saved to auth_identity_[target].
1463 has_identity_to_try = SelectNextAuthIdentityToTry(target);
1464 } else {
1465 // Proceed with a null identity.
1466 //
1467 // TODO(wtc): Add a safeguard against infinite transaction restarts, if
1468 // the server keeps returning "NTLM".
1469 auth_identity_[target].source = HttpAuth::IDENT_SRC_NONE;
1470 auth_identity_[target].invalid = false;
1471 auth_identity_[target].username.clear();
1472 auth_identity_[target].password.clear();
1473 has_identity_to_try = true;
1474 }
[email protected]f9ee6b52008-11-08 06:46:231475 DCHECK(has_identity_to_try == !auth_identity_[target].invalid);
1476
1477 if (has_identity_to_try) {
1478 DCHECK(user_callback_);
1479 PrepareForAuthRestart(target);
1480 return WILL_RESTART_TRANSACTION;
[email protected]f9ee6b52008-11-08 06:46:231481 }
1482
[email protected]74da3732009-01-30 23:45:031483 // We have exhausted all identity possibilities, all we can do now is
1484 // pass the challenge information back to the client.
1485 PopulateAuthChallenge(target);
[email protected]f9ee6b52008-11-08 06:46:231486 return OK;
1487}
1488
1489void HttpNetworkTransaction::PopulateAuthChallenge(HttpAuth::Target target) {
1490 // Populates response_.auth_challenge with the authentication challenge info.
1491 // This info is consumed by URLRequestHttpJob::GetAuthChallengeInfo().
1492
1493 AuthChallengeInfo* auth_info = new AuthChallengeInfo;
[email protected]c3b35c22008-09-27 03:19:421494 auth_info->is_proxy = target == HttpAuth::AUTH_PROXY;
[email protected]f9ee6b52008-11-08 06:46:231495 auth_info->scheme = ASCIIToWide(auth_handler_[target]->scheme());
[email protected]c3b35c22008-09-27 03:19:421496 // TODO(eroman): decode realm according to RFC 2047.
[email protected]f9ee6b52008-11-08 06:46:231497 auth_info->realm = ASCIIToWide(auth_handler_[target]->realm());
[email protected]c3b35c22008-09-27 03:19:421498 if (target == HttpAuth::AUTH_PROXY) {
[email protected]f6fb2de2009-02-19 08:11:421499 auth_info->host = ASCIIToWide(proxy_info_.proxy_server().host_and_port());
[email protected]c3b35c22008-09-27 03:19:421500 } else {
1501 DCHECK(target == HttpAuth::AUTH_SERVER);
1502 auth_info->host = ASCIIToWide(request_->url.host());
1503 }
[email protected]f9ee6b52008-11-08 06:46:231504 response_.auth_challenge = auth_info;
[email protected]c3b35c22008-09-27 03:19:421505}
1506
1507} // namespace net