blob: 9667cb0cad0ebcd16caa358c907e934175e7e9e4 [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"
16#include "net/base/load_flags.h"
[email protected]c3b35c22008-09-27 03:19:4217#include "net/base/net_util.h"
[email protected]4628a2a2008-08-14 20:33:2518#include "net/base/ssl_client_socket.h"
initial.commit586acc5fe2008-07-26 22:42:5219#include "net/base/upload_data_stream.h"
[email protected]c3b35c22008-09-27 03:19:4220#include "net/http/http_auth.h"
21#include "net/http/http_auth_handler.h"
initial.commit586acc5fe2008-07-26 22:42:5222#include "net/http/http_chunked_decoder.h"
23#include "net/http/http_network_session.h"
24#include "net/http/http_request_info.h"
25#include "net/http/http_util.h"
26
[email protected]e1acf6f2008-10-27 20:43:3327using base::Time;
28
initial.commit586acc5fe2008-07-26 22:42:5229namespace net {
30
31//-----------------------------------------------------------------------------
32
initial.commit586acc5fe2008-07-26 22:42:5233HttpNetworkTransaction::HttpNetworkTransaction(HttpNetworkSession* session,
34 ClientSocketFactory* csf)
[email protected]68bf9152008-09-25 19:47:3035 : ALLOW_THIS_IN_INITIALIZER_LIST(
36 io_callback_(this, &HttpNetworkTransaction::OnIOComplete)),
initial.commit586acc5fe2008-07-26 22:42:5237 user_callback_(NULL),
38 session_(session),
39 request_(NULL),
40 pac_request_(NULL),
41 socket_factory_(csf),
[email protected]e1e06262008-08-06 23:57:0742 connection_(session->connection_pool()),
initial.commit586acc5fe2008-07-26 22:42:5243 reused_socket_(false),
44 using_ssl_(false),
45 using_proxy_(false),
46 using_tunnel_(false),
[email protected]6b9833e2008-09-10 20:32:2547 establishing_tunnel_(false),
[email protected]96d570e42008-08-05 22:43:0448 request_headers_bytes_sent_(0),
initial.commit586acc5fe2008-07-26 22:42:5249 header_buf_capacity_(0),
50 header_buf_len_(0),
51 header_buf_body_offset_(-1),
[email protected]231d5a32008-09-13 00:45:2752 header_buf_http_offset_(-1),
initial.commit586acc5fe2008-07-26 22:42:5253 content_length_(-1), // -1 means unspecified.
54 content_read_(0),
initial.commit586acc5fe2008-07-26 22:42:5255 read_buf_len_(0),
56 next_state_(STATE_NONE) {
[email protected]2cd713f2008-10-21 17:54:2857#if defined(OS_WIN)
58 // TODO(port): Port the SSLConfigService class to Linux and Mac OS X.
59 session->ssl_config_service()->GetSSLConfig(&ssl_config_);
60#endif
initial.commit586acc5fe2008-07-26 22:42:5261}
62
[email protected]96d570e42008-08-05 22:43:0463int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
64 CompletionCallback* callback) {
[email protected]5d0153c512009-01-12 19:08:3665 UpdateConnectionTypeHistograms(CONNECTION_ANY);
66
[email protected]96d570e42008-08-05 22:43:0467 request_ = request_info;
68
69 next_state_ = STATE_RESOLVE_PROXY;
70 int rv = DoLoop(OK);
71 if (rv == ERR_IO_PENDING)
72 user_callback_ = callback;
73 return rv;
74}
75
76int HttpNetworkTransaction::RestartIgnoringLastError(
77 CompletionCallback* callback) {
[email protected]ccb40e52008-09-17 20:54:4078 // TODO(wtc): If the connection is no longer alive, call
79 // connection_.socket()->ReconnectIgnoringLastError().
80 next_state_ = STATE_WRITE_HEADERS;
81 int rv = DoLoop(OK);
82 if (rv == ERR_IO_PENDING)
83 user_callback_ = callback;
[email protected]aaead502008-10-15 00:20:1184 return rv;
[email protected]96d570e42008-08-05 22:43:0485}
86
87int HttpNetworkTransaction::RestartWithAuth(
88 const std::wstring& username,
89 const std::wstring& password,
90 CompletionCallback* callback) {
[email protected]c3b35c22008-09-27 03:19:4291
92 DCHECK(NeedAuth(HttpAuth::AUTH_PROXY) ||
93 NeedAuth(HttpAuth::AUTH_SERVER));
94
95 // Figure out whether this username password is for proxy or server.
96 // Proxy gets set first, then server.
97 HttpAuth::Target target = NeedAuth(HttpAuth::AUTH_PROXY) ?
98 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
99
100 // Update the username/password.
[email protected]f9ee6b52008-11-08 06:46:23101 auth_identity_[target].source = HttpAuth::IDENT_SRC_EXTERNAL;
102 auth_identity_[target].invalid = false;
103 auth_identity_[target].username = username;
104 auth_identity_[target].password = password;
[email protected]c3b35c22008-09-27 03:19:42105
[email protected]f9ee6b52008-11-08 06:46:23106 PrepareForAuthRestart(target);
[email protected]c3b35c22008-09-27 03:19:42107
108 DCHECK(user_callback_ == NULL);
109 int rv = DoLoop(OK);
110 if (rv == ERR_IO_PENDING)
111 user_callback_ = callback;
112
113 return rv;
[email protected]96d570e42008-08-05 22:43:04114}
115
[email protected]f9ee6b52008-11-08 06:46:23116void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
117 DCHECK(HaveAuth(target));
118 DCHECK(auth_identity_[target].source != HttpAuth::IDENT_SRC_PATH_LOOKUP);
119
120 // Add the auth entry to the cache before restarting. We don't know whether
121 // the identity is valid yet, but if it is valid we want other transactions
122 // to know about it. If an entry for (origin, handler->realm()) already
123 // exists, we update it.
124 session_->auth_cache()->Add(AuthOrigin(target), auth_handler_[target],
125 auth_identity_[target].username, auth_identity_[target].password,
126 AuthPath(target));
127
128 next_state_ = STATE_INIT_CONNECTION;
129 connection_.set_socket(NULL);
130 connection_.Reset();
131
132 // Reset the other member variables.
133 ResetStateForRestart();
134}
135
[email protected]9dea9e1f2009-01-29 00:30:47136int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
[email protected]96d570e42008-08-05 22:43:04137 CompletionCallback* callback) {
138 DCHECK(response_.headers);
139 DCHECK(buf);
140 DCHECK(buf_len > 0);
141
142 if (!connection_.is_initialized())
143 return 0; // connection_ has been reset. Treat like EOF.
144
145 read_buf_ = buf;
146 read_buf_len_ = buf_len;
147
148 next_state_ = STATE_READ_BODY;
149 int rv = DoLoop(OK);
150 if (rv == ERR_IO_PENDING)
151 user_callback_ = callback;
152 return rv;
153}
154
155const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
[email protected]4628a2a2008-08-14 20:33:25156 return (response_.headers || response_.ssl_info.cert) ? &response_ : NULL;
[email protected]96d570e42008-08-05 22:43:04157}
158
159LoadState HttpNetworkTransaction::GetLoadState() const {
160 // TODO(wtc): Define a new LoadState value for the
161 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
162 switch (next_state_) {
163 case STATE_RESOLVE_PROXY_COMPLETE:
164 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
165 case STATE_RESOLVE_HOST_COMPLETE:
166 return LOAD_STATE_RESOLVING_HOST;
167 case STATE_CONNECT_COMPLETE:
168 return LOAD_STATE_CONNECTING;
169 case STATE_WRITE_HEADERS_COMPLETE:
170 case STATE_WRITE_BODY_COMPLETE:
171 return LOAD_STATE_SENDING_REQUEST;
172 case STATE_READ_HEADERS_COMPLETE:
173 return LOAD_STATE_WAITING_FOR_RESPONSE;
174 case STATE_READ_BODY_COMPLETE:
175 return LOAD_STATE_READING_RESPONSE;
176 default:
177 return LOAD_STATE_IDLE;
178 }
179}
180
181uint64 HttpNetworkTransaction::GetUploadProgress() const {
182 if (!request_body_stream_.get())
183 return 0;
184
185 return request_body_stream_->position();
186}
187
initial.commit586acc5fe2008-07-26 22:42:52188HttpNetworkTransaction::~HttpNetworkTransaction() {
189 // If we still have an open socket, then make sure to close it so we don't
190 // try to reuse it later on.
191 if (connection_.is_initialized())
192 connection_.set_socket(NULL);
193
194 if (pac_request_)
195 session_->proxy_service()->CancelPacRequest(pac_request_);
196}
197
198void HttpNetworkTransaction::BuildRequestHeaders() {
[email protected]3130a8532008-09-15 18:37:11199 // For proxy use the full url. Otherwise just the absolute path.
200 // This strips out any reference/username/password.
201 std::string path = using_proxy_ ?
202 HttpUtil::SpecForRequest(request_->url) :
203 HttpUtil::PathForRequest(request_->url);
initial.commit586acc5fe2008-07-26 22:42:52204
[email protected]c7af8b22008-08-25 20:41:46205 request_headers_ = request_->method + " " + path +
206 " HTTP/1.1\r\nHost: " + request_->url.host();
initial.commit586acc5fe2008-07-26 22:42:52207 if (request_->url.IntPort() != -1)
208 request_headers_ += ":" + request_->url.port();
209 request_headers_ += "\r\n";
210
211 // For compat with HTTP/1.0 servers and proxies:
212 if (using_proxy_)
213 request_headers_ += "Proxy-";
214 request_headers_ += "Connection: keep-alive\r\n";
215
216 if (!request_->user_agent.empty())
217 request_headers_ += "User-Agent: " + request_->user_agent + "\r\n";
218
219 // Our consumer should have made sure that this is a safe referrer. See for
220 // instance WebCore::FrameLoader::HideReferrer.
221 if (request_->referrer.is_valid())
222 request_headers_ += "Referer: " + request_->referrer.spec() + "\r\n";
223
224 // Add a content length header?
225 if (request_->upload_data) {
226 request_body_stream_.reset(new UploadDataStream(request_->upload_data));
227 request_headers_ +=
228 "Content-Length: " + Uint64ToString(request_body_stream_->size()) +
229 "\r\n";
230 } else if (request_->method == "POST" || request_->method == "PUT" ||
231 request_->method == "HEAD") {
232 // An empty POST/PUT request still needs a content length. As for HEAD,
233 // IE and Safari also add a content length header. Presumably it is to
234 // support sending a HEAD request to an URL that only expects to be sent a
235 // POST or some other method that normally would have a message body.
236 request_headers_ += "Content-Length: 0\r\n";
237 }
238
239 // Honor load flags that impact proxy caches.
240 if (request_->load_flags & LOAD_BYPASS_CACHE) {
241 request_headers_ += "Pragma: no-cache\r\nCache-Control: no-cache\r\n";
242 } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
243 request_headers_ += "Cache-Control: max-age=0\r\n";
244 }
245
[email protected]c3b35c22008-09-27 03:19:42246 ApplyAuth();
247
initial.commit586acc5fe2008-07-26 22:42:52248 // TODO(darin): Need to prune out duplicate headers.
249
250 request_headers_ += request_->extra_headers;
251 request_headers_ += "\r\n";
252}
253
[email protected]c7af8b22008-08-25 20:41:46254// The HTTP CONNECT method for establishing a tunnel connection is documented
[email protected]6b9833e2008-09-10 20:32:25255// in draft-luotonen-web-proxy-tunneling-01.txt and RFC 2817, Sections 5.2 and
[email protected]c7af8b22008-08-25 20:41:46256// 5.3.
257void HttpNetworkTransaction::BuildTunnelRequest() {
[email protected]c7af8b22008-08-25 20:41:46258 // RFC 2616 Section 9 says the Host request-header field MUST accompany all
259 // HTTP/1.1 requests.
[email protected]6d748ec2008-10-08 22:11:39260 request_headers_ = StringPrintf("CONNECT %s:%d HTTP/1.1\r\n",
261 request_->url.host().c_str(), request_->url.EffectiveIntPort());
262 request_headers_ += "Host: " + request_->url.host();
263 if (request_->url.has_port())
[email protected]c7af8b22008-08-25 20:41:46264 request_headers_ += ":" + request_->url.port();
265 request_headers_ += "\r\n";
266
267 if (!request_->user_agent.empty())
268 request_headers_ += "User-Agent: " + request_->user_agent + "\r\n";
269
[email protected]c3b35c22008-09-27 03:19:42270 ApplyAuth();
[email protected]c7af8b22008-08-25 20:41:46271
272 request_headers_ += "\r\n";
273}
274
initial.commit586acc5fe2008-07-26 22:42:52275void HttpNetworkTransaction::DoCallback(int rv) {
276 DCHECK(rv != ERR_IO_PENDING);
277 DCHECK(user_callback_);
278
[email protected]96d570e42008-08-05 22:43:04279 // Since Run may result in Read being called, clear user_callback_ up front.
initial.commit586acc5fe2008-07-26 22:42:52280 CompletionCallback* c = user_callback_;
281 user_callback_ = NULL;
282 c->Run(rv);
283}
284
285void HttpNetworkTransaction::OnIOComplete(int result) {
286 int rv = DoLoop(result);
287 if (rv != ERR_IO_PENDING)
288 DoCallback(rv);
289}
290
291int HttpNetworkTransaction::DoLoop(int result) {
292 DCHECK(next_state_ != STATE_NONE);
293
294 int rv = result;
295 do {
296 State state = next_state_;
297 next_state_ = STATE_NONE;
298 switch (state) {
299 case STATE_RESOLVE_PROXY:
[email protected]96d570e42008-08-05 22:43:04300 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55301 TRACE_EVENT_BEGIN("http.resolve_proxy", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52302 rv = DoResolveProxy();
303 break;
304 case STATE_RESOLVE_PROXY_COMPLETE:
305 rv = DoResolveProxyComplete(rv);
[email protected]113ab132008-09-18 20:42:55306 TRACE_EVENT_END("http.resolve_proxy", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52307 break;
308 case STATE_INIT_CONNECTION:
[email protected]96d570e42008-08-05 22:43:04309 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55310 TRACE_EVENT_BEGIN("http.init_conn", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52311 rv = DoInitConnection();
312 break;
313 case STATE_INIT_CONNECTION_COMPLETE:
314 rv = DoInitConnectionComplete(rv);
[email protected]113ab132008-09-18 20:42:55315 TRACE_EVENT_END("http.init_conn", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52316 break;
317 case STATE_RESOLVE_HOST:
[email protected]96d570e42008-08-05 22:43:04318 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55319 TRACE_EVENT_BEGIN("http.resolve_host", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52320 rv = DoResolveHost();
321 break;
322 case STATE_RESOLVE_HOST_COMPLETE:
323 rv = DoResolveHostComplete(rv);
[email protected]113ab132008-09-18 20:42:55324 TRACE_EVENT_END("http.resolve_host", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52325 break;
326 case STATE_CONNECT:
[email protected]96d570e42008-08-05 22:43:04327 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55328 TRACE_EVENT_BEGIN("http.connect", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52329 rv = DoConnect();
330 break;
331 case STATE_CONNECT_COMPLETE:
332 rv = DoConnectComplete(rv);
[email protected]113ab132008-09-18 20:42:55333 TRACE_EVENT_END("http.connect", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52334 break;
[email protected]c7af8b22008-08-25 20:41:46335 case STATE_SSL_CONNECT_OVER_TUNNEL:
336 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55337 TRACE_EVENT_BEGIN("http.ssl_tunnel", request_, request_->url.spec());
[email protected]c7af8b22008-08-25 20:41:46338 rv = DoSSLConnectOverTunnel();
339 break;
340 case STATE_SSL_CONNECT_OVER_TUNNEL_COMPLETE:
341 rv = DoSSLConnectOverTunnelComplete(rv);
[email protected]113ab132008-09-18 20:42:55342 TRACE_EVENT_END("http.ssl_tunnel", request_, request_->url.spec());
[email protected]c7af8b22008-08-25 20:41:46343 break;
initial.commit586acc5fe2008-07-26 22:42:52344 case STATE_WRITE_HEADERS:
[email protected]96d570e42008-08-05 22:43:04345 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55346 TRACE_EVENT_BEGIN("http.write_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52347 rv = DoWriteHeaders();
348 break;
349 case STATE_WRITE_HEADERS_COMPLETE:
350 rv = DoWriteHeadersComplete(rv);
[email protected]113ab132008-09-18 20:42:55351 TRACE_EVENT_END("http.write_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52352 break;
353 case STATE_WRITE_BODY:
[email protected]96d570e42008-08-05 22:43:04354 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55355 TRACE_EVENT_BEGIN("http.write_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52356 rv = DoWriteBody();
357 break;
358 case STATE_WRITE_BODY_COMPLETE:
359 rv = DoWriteBodyComplete(rv);
[email protected]113ab132008-09-18 20:42:55360 TRACE_EVENT_END("http.write_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52361 break;
362 case STATE_READ_HEADERS:
[email protected]96d570e42008-08-05 22:43:04363 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55364 TRACE_EVENT_BEGIN("http.read_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52365 rv = DoReadHeaders();
366 break;
367 case STATE_READ_HEADERS_COMPLETE:
368 rv = DoReadHeadersComplete(rv);
[email protected]113ab132008-09-18 20:42:55369 TRACE_EVENT_END("http.read_headers", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52370 break;
371 case STATE_READ_BODY:
[email protected]96d570e42008-08-05 22:43:04372 DCHECK(rv == OK);
[email protected]113ab132008-09-18 20:42:55373 TRACE_EVENT_BEGIN("http.read_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52374 rv = DoReadBody();
375 break;
376 case STATE_READ_BODY_COMPLETE:
377 rv = DoReadBodyComplete(rv);
[email protected]113ab132008-09-18 20:42:55378 TRACE_EVENT_END("http.read_body", request_, request_->url.spec());
initial.commit586acc5fe2008-07-26 22:42:52379 break;
380 default:
381 NOTREACHED() << "bad state";
382 rv = ERR_FAILED;
[email protected]96d570e42008-08-05 22:43:04383 break;
initial.commit586acc5fe2008-07-26 22:42:52384 }
385 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
386
387 return rv;
388}
389
390int HttpNetworkTransaction::DoResolveProxy() {
391 DCHECK(!pac_request_);
392
393 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
394
[email protected]677c90572008-12-10 09:03:15395 if (request_->load_flags & LOAD_BYPASS_PROXY) {
396 proxy_info_.UseDirect();
397 return OK;
398 }
399
initial.commit586acc5fe2008-07-26 22:42:52400 return session_->proxy_service()->ResolveProxy(
401 request_->url, &proxy_info_, &io_callback_, &pac_request_);
402}
403
404int HttpNetworkTransaction::DoResolveProxyComplete(int result) {
405 next_state_ = STATE_INIT_CONNECTION;
406
407 pac_request_ = NULL;
408
409 if (result != OK) {
410 DLOG(ERROR) << "Failed to resolve proxy: " << result;
411 proxy_info_.UseDirect();
412 }
413 return OK;
414}
415
416int HttpNetworkTransaction::DoInitConnection() {
417 DCHECK(!connection_.is_initialized());
418
419 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
420
421 using_ssl_ = request_->url.SchemeIs("https");
422 using_proxy_ = !proxy_info_.is_direct() && !using_ssl_;
423 using_tunnel_ = !proxy_info_.is_direct() && using_ssl_;
424
425 // Build the string used to uniquely identify connections of this type.
426 std::string connection_group;
427 if (using_proxy_ || using_tunnel_)
[email protected]82f954e2008-08-12 05:11:38428 connection_group = "proxy/" + proxy_info_.proxy_server() + "/";
initial.commit586acc5fe2008-07-26 22:42:52429 if (!using_proxy_)
430 connection_group.append(request_->url.GetOrigin().spec());
431
[email protected]96d570e42008-08-05 22:43:04432 DCHECK(!connection_group.empty());
initial.commit586acc5fe2008-07-26 22:42:52433 return connection_.Init(connection_group, &io_callback_);
434}
435
436int HttpNetworkTransaction::DoInitConnectionComplete(int result) {
437 if (result < 0)
438 return result;
439
440 DCHECK(connection_.is_initialized());
441
442 // Set the reused_socket_ flag to indicate that we are using a keep-alive
443 // connection. This flag is used to handle errors that occur while we are
444 // trying to reuse a keep-alive connection.
[email protected]049d4ee2008-10-23 21:42:07445 reused_socket_ = (connection_.socket() != NULL);
446 if (reused_socket_) {
initial.commit586acc5fe2008-07-26 22:42:52447 next_state_ = STATE_WRITE_HEADERS;
448 } else {
449 next_state_ = STATE_RESOLVE_HOST;
450 }
451 return OK;
452}
453
454int HttpNetworkTransaction::DoResolveHost() {
455 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
456
initial.commit586acc5fe2008-07-26 22:42:52457 std::string host;
458 int port;
459
460 // Determine the host and port to connect to.
461 if (using_proxy_ || using_tunnel_) {
[email protected]82f954e2008-08-12 05:11:38462 const std::string& proxy = proxy_info_.proxy_server();
initial.commit586acc5fe2008-07-26 22:42:52463 StringTokenizer t(proxy, ":");
464 // TODO(darin): Handle errors here. Perhaps HttpProxyInfo should do this
465 // before claiming a proxy server configuration.
466 t.GetNext();
467 host = t.token();
468 t.GetNext();
[email protected]6d748ec2008-10-08 22:11:39469 port = StringToInt(t.token());
initial.commit586acc5fe2008-07-26 22:42:52470 } else {
[email protected]96d570e42008-08-05 22:43:04471 // Direct connection
initial.commit586acc5fe2008-07-26 22:42:52472 host = request_->url.host();
[email protected]6d748ec2008-10-08 22:11:39473 port = request_->url.EffectiveIntPort();
initial.commit586acc5fe2008-07-26 22:42:52474 }
475
[email protected]8947da62008-10-24 19:11:10476 DidStartDnsResolution(host, this);
[email protected]96d570e42008-08-05 22:43:04477 return resolver_.Resolve(host, port, &addresses_, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52478}
479
480int HttpNetworkTransaction::DoResolveHostComplete(int result) {
[email protected]8947da62008-10-24 19:11:10481 bool ok = (result == OK);
[email protected]77848d12008-11-14 00:00:22482 DidFinishDnsResolutionWithStatus(ok, request_->referrer, this);
[email protected]8947da62008-10-24 19:11:10483 if (ok) {
initial.commit586acc5fe2008-07-26 22:42:52484 next_state_ = STATE_CONNECT;
[email protected]86ec30d2008-09-29 21:53:54485 } else {
486 result = ReconsiderProxyAfterError(result);
487 }
initial.commit586acc5fe2008-07-26 22:42:52488 return result;
489}
490
491int HttpNetworkTransaction::DoConnect() {
492 next_state_ = STATE_CONNECT_COMPLETE;
493
494 DCHECK(!connection_.socket());
495
496 ClientSocket* s = socket_factory_->CreateTCPClientSocket(addresses_);
497
498 // If we are using a direct SSL connection, then go ahead and create the SSL
499 // wrapper socket now. Otherwise, we need to first issue a CONNECT request.
500 if (using_ssl_ && !using_tunnel_)
[email protected]c5949a32008-10-08 17:28:23501 s = socket_factory_->CreateSSLClientSocket(s, request_->url.host(),
[email protected]aaead502008-10-15 00:20:11502 ssl_config_);
initial.commit586acc5fe2008-07-26 22:42:52503
504 connection_.set_socket(s);
505 return connection_.socket()->Connect(&io_callback_);
506}
507
508int HttpNetworkTransaction::DoConnectComplete(int result) {
[email protected]771d0c2b2008-09-30 00:26:17509 if (IsCertificateError(result))
510 result = HandleCertificateError(result);
511
[email protected]c7af8b22008-08-25 20:41:46512 if (result == OK) {
[email protected]6b9833e2008-09-10 20:32:25513 next_state_ = STATE_WRITE_HEADERS;
[email protected]27161fb2008-11-03 23:39:05514 if (using_tunnel_)
[email protected]6b9833e2008-09-10 20:32:25515 establishing_tunnel_ = true;
[email protected]86ec30d2008-09-29 21:53:54516 } else {
[email protected]5a179bcc2008-10-13 18:10:59517 result = HandleSSLHandshakeError(result);
518 if (result != OK)
519 result = ReconsiderProxyAfterError(result);
[email protected]c7af8b22008-08-25 20:41:46520 }
521 return result;
522}
523
[email protected]c7af8b22008-08-25 20:41:46524int HttpNetworkTransaction::DoSSLConnectOverTunnel() {
525 next_state_ = STATE_SSL_CONNECT_OVER_TUNNEL_COMPLETE;
526
[email protected]86ec30d2008-09-29 21:53:54527 // Add a SSL socket on top of our existing transport socket.
[email protected]c7af8b22008-08-25 20:41:46528 ClientSocket* s = connection_.release_socket();
[email protected]c5949a32008-10-08 17:28:23529 s = socket_factory_->CreateSSLClientSocket(s, request_->url.host(),
[email protected]aaead502008-10-15 00:20:11530 ssl_config_);
[email protected]c7af8b22008-08-25 20:41:46531 connection_.set_socket(s);
532 return connection_.socket()->Connect(&io_callback_);
533}
534
535int HttpNetworkTransaction::DoSSLConnectOverTunnelComplete(int result) {
[email protected]771d0c2b2008-09-30 00:26:17536 if (IsCertificateError(result))
[email protected]ccb40e52008-09-17 20:54:40537 result = HandleCertificateError(result);
[email protected]771d0c2b2008-09-30 00:26:17538
[email protected]c5949a32008-10-08 17:28:23539 if (result == OK) {
[email protected]771d0c2b2008-09-30 00:26:17540 next_state_ = STATE_WRITE_HEADERS;
[email protected]5a179bcc2008-10-13 18:10:59541 } else {
[email protected]c5949a32008-10-08 17:28:23542 result = HandleSSLHandshakeError(result);
543 }
initial.commit586acc5fe2008-07-26 22:42:52544 return result;
545}
546
547int HttpNetworkTransaction::DoWriteHeaders() {
548 next_state_ = STATE_WRITE_HEADERS_COMPLETE;
549
550 // This is constructed lazily (instead of within our Start method), so that
551 // we have proxy info available.
[email protected]6b9833e2008-09-10 20:32:25552 if (request_headers_.empty()) {
553 if (establishing_tunnel_) {
554 BuildTunnelRequest();
555 } else {
556 BuildRequestHeaders();
557 }
558 }
initial.commit586acc5fe2008-07-26 22:42:52559
560 // Record our best estimate of the 'request time' as the time when we send
561 // out the first bytes of the request headers.
[email protected]87a1a952009-01-13 18:06:03562 if (request_headers_bytes_sent_ == 0) {
initial.commit586acc5fe2008-07-26 22:42:52563 response_.request_time = Time::Now();
[email protected]87a1a952009-01-13 18:06:03564 response_.was_cached = false;
565 }
initial.commit586acc5fe2008-07-26 22:42:52566
[email protected]6b9833e2008-09-10 20:32:25567 const char* buf = request_headers_.data() + request_headers_bytes_sent_;
568 int buf_len = static_cast<int>(request_headers_.size() -
569 request_headers_bytes_sent_);
570 DCHECK(buf_len > 0);
571
572 return connection_.socket()->Write(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52573}
574
575int HttpNetworkTransaction::DoWriteHeadersComplete(int result) {
576 if (result < 0)
577 return HandleIOError(result);
578
[email protected]96d570e42008-08-05 22:43:04579 request_headers_bytes_sent_ += result;
580 if (request_headers_bytes_sent_ < request_headers_.size()) {
initial.commit586acc5fe2008-07-26 22:42:52581 next_state_ = STATE_WRITE_HEADERS;
[email protected]6b9833e2008-09-10 20:32:25582 } else if (!establishing_tunnel_ && request_->upload_data) {
initial.commit586acc5fe2008-07-26 22:42:52583 next_state_ = STATE_WRITE_BODY;
584 } else {
585 next_state_ = STATE_READ_HEADERS;
586 }
587 return OK;
588}
589
590int HttpNetworkTransaction::DoWriteBody() {
591 next_state_ = STATE_WRITE_BODY_COMPLETE;
592
593 DCHECK(request_->upload_data);
594 DCHECK(request_body_stream_.get());
595
596 const char* buf = request_body_stream_->buf();
597 int buf_len = static_cast<int>(request_body_stream_->buf_len());
598
599 return connection_.socket()->Write(buf, buf_len, &io_callback_);
600}
601
602int HttpNetworkTransaction::DoWriteBodyComplete(int result) {
603 if (result < 0)
604 return HandleIOError(result);
605
606 request_body_stream_->DidConsume(result);
607
608 if (request_body_stream_->position() < request_body_stream_->size()) {
609 next_state_ = STATE_WRITE_BODY;
610 } else {
611 next_state_ = STATE_READ_HEADERS;
612 }
613 return OK;
614}
615
616int HttpNetworkTransaction::DoReadHeaders() {
617 next_state_ = STATE_READ_HEADERS_COMPLETE;
618
[email protected]6b9833e2008-09-10 20:32:25619 // Grow the read buffer if necessary.
620 if (header_buf_len_ == header_buf_capacity_) {
621 header_buf_capacity_ += kHeaderBufInitialSize;
622 header_buf_.reset(static_cast<char*>(
623 realloc(header_buf_.release(), header_buf_capacity_)));
624 }
625
626 char* buf = header_buf_.get() + header_buf_len_;
627 int buf_len = header_buf_capacity_ - header_buf_len_;
628
629 return connection_.socket()->Read(buf, buf_len, &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52630}
631
[email protected]0e75a732008-10-16 20:36:09632int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
[email protected]aecfbf22008-10-16 02:02:47633 if (establishing_tunnel_) {
[email protected]0e75a732008-10-16 20:36:09634 // The connection was closed before the tunnel could be established.
[email protected]aecfbf22008-10-16 02:02:47635 return ERR_TUNNEL_CONNECTION_FAILED;
636 }
637
638 if (has_found_status_line_start()) {
639 // Assume EOF is end-of-headers.
640 header_buf_body_offset_ = header_buf_len_;
641 return OK;
642 }
643
644 // No status line was matched yet. Could have been a HTTP/0.9 response, or
645 // a partial HTTP/1.x response.
646
647 if (header_buf_len_ == 0) {
[email protected]0e75a732008-10-16 20:36:09648 // The connection was closed before any data was sent. Likely an error
649 // rather than empty HTTP/0.9 response.
[email protected]aecfbf22008-10-16 02:02:47650 return ERR_EMPTY_RESPONSE;
651 }
652
653 // Assume everything else is a HTTP/0.9 response (including responses
654 // of 'h', 'ht', 'htt').
655 header_buf_body_offset_ = 0;
656 return OK;
657}
658
initial.commit586acc5fe2008-07-26 22:42:52659int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
660 if (result < 0)
661 return HandleIOError(result);
662
[email protected]2a5c76b2008-09-25 22:15:16663 if (result == 0 && ShouldResendRequest())
664 return result;
665
initial.commit586acc5fe2008-07-26 22:42:52666 // Record our best estimate of the 'response time' as the time when we read
667 // the first bytes of the response headers.
668 if (header_buf_len_ == 0)
669 response_.response_time = Time::Now();
670
[email protected]231d5a32008-09-13 00:45:27671 // The socket was closed before we found end-of-headers.
initial.commit586acc5fe2008-07-26 22:42:52672 if (result == 0) {
[email protected]0e75a732008-10-16 20:36:09673 int rv = HandleConnectionClosedBeforeEndOfHeaders();
[email protected]aecfbf22008-10-16 02:02:47674 if (rv != OK)
675 return rv;
initial.commit586acc5fe2008-07-26 22:42:52676 } else {
677 header_buf_len_ += result;
678 DCHECK(header_buf_len_ <= header_buf_capacity_);
679
[email protected]231d5a32008-09-13 00:45:27680 // Look for the start of the status line, if it hasn't been found yet.
681 if (!has_found_status_line_start()) {
682 header_buf_http_offset_ = HttpUtil::LocateStartOfStatusLine(
683 header_buf_.get(), header_buf_len_);
initial.commit586acc5fe2008-07-26 22:42:52684 }
[email protected]231d5a32008-09-13 00:45:27685
686 if (has_found_status_line_start()) {
687 int eoh = HttpUtil::LocateEndOfHeaders(
688 header_buf_.get(), header_buf_len_, header_buf_http_offset_);
689 if (eoh == -1) {
[email protected]4ddaf2502008-10-23 18:26:19690 // Prevent growing the headers buffer indefinitely.
691 if (header_buf_len_ >= kMaxHeaderBufSize)
692 return ERR_RESPONSE_HEADERS_TOO_BIG;
693
[email protected]231d5a32008-09-13 00:45:27694 // Haven't found the end of headers yet, keep reading.
695 next_state_ = STATE_READ_HEADERS;
696 return OK;
697 }
698 header_buf_body_offset_ = eoh;
699 } else if (header_buf_len_ < 8) {
700 // Not enough data to decide whether this is HTTP/0.9 yet.
701 // 8 bytes = (4 bytes of junk) + "http".length()
702 next_state_ = STATE_READ_HEADERS;
703 return OK;
704 } else {
705 // Enough data was read -- there is no status line.
706 header_buf_body_offset_ = 0;
707 }
initial.commit586acc5fe2008-07-26 22:42:52708 }
[email protected]65f11402008-10-31 17:39:44709
[email protected]6b9833e2008-09-10 20:32:25710 // And, we are done with the Start or the SSL tunnel CONNECT sequence.
[email protected]27161fb2008-11-03 23:39:05711 return DidReadResponseHeaders();
initial.commit586acc5fe2008-07-26 22:42:52712}
713
714int HttpNetworkTransaction::DoReadBody() {
715 DCHECK(read_buf_);
716 DCHECK(read_buf_len_ > 0);
717 DCHECK(connection_.is_initialized());
718
719 next_state_ = STATE_READ_BODY_COMPLETE;
720
[email protected]f9d44aa2008-09-23 23:57:17721 // We may have already consumed the indicated content length.
722 if (content_length_ != -1 && content_read_ >= content_length_)
723 return 0;
724
[email protected]96d570e42008-08-05 22:43:04725 // We may have some data remaining in the header buffer.
initial.commit586acc5fe2008-07-26 22:42:52726 if (header_buf_.get() && header_buf_body_offset_ < header_buf_len_) {
727 int n = std::min(read_buf_len_, header_buf_len_ - header_buf_body_offset_);
[email protected]9dea9e1f2009-01-29 00:30:47728 memcpy(read_buf_->data(), header_buf_.get() + header_buf_body_offset_, n);
initial.commit586acc5fe2008-07-26 22:42:52729 header_buf_body_offset_ += n;
[email protected]96d570e42008-08-05 22:43:04730 if (header_buf_body_offset_ == header_buf_len_) {
initial.commit586acc5fe2008-07-26 22:42:52731 header_buf_.reset();
[email protected]96d570e42008-08-05 22:43:04732 header_buf_capacity_ = 0;
733 header_buf_len_ = 0;
734 header_buf_body_offset_ = -1;
735 }
initial.commit586acc5fe2008-07-26 22:42:52736 return n;
737 }
738
[email protected]9dea9e1f2009-01-29 00:30:47739 return connection_.socket()->Read(read_buf_->data(), read_buf_len_,
740 &io_callback_);
initial.commit586acc5fe2008-07-26 22:42:52741}
742
743int HttpNetworkTransaction::DoReadBodyComplete(int result) {
744 // We are done with the Read call.
745
[email protected]96d570e42008-08-05 22:43:04746 bool unfiltered_eof = (result == 0);
747
initial.commit586acc5fe2008-07-26 22:42:52748 // Filter incoming data if appropriate. FilterBuf may return an error.
749 if (result > 0 && chunked_decoder_.get()) {
[email protected]9dea9e1f2009-01-29 00:30:47750 result = chunked_decoder_->FilterBuf(read_buf_->data(), result);
[email protected]96d570e42008-08-05 22:43:04751 if (result == 0 && !chunked_decoder_->reached_eof()) {
initial.commit586acc5fe2008-07-26 22:42:52752 // Don't signal completion of the Read call yet or else it'll look like
753 // we received end-of-file. Wait for more data.
754 next_state_ = STATE_READ_BODY;
755 return OK;
756 }
757 }
758
759 bool done = false, keep_alive = false;
760 if (result < 0) {
761 // Error while reading the socket.
762 done = true;
763 } else {
764 content_read_ += result;
[email protected]96d570e42008-08-05 22:43:04765 if (unfiltered_eof ||
766 (content_length_ != -1 && content_read_ >= content_length_) ||
initial.commit586acc5fe2008-07-26 22:42:52767 (chunked_decoder_.get() && chunked_decoder_->reached_eof())) {
768 done = true;
769 keep_alive = response_.headers->IsKeepAlive();
[email protected]96d570e42008-08-05 22:43:04770 // We can't reuse the connection if we read more than the advertised
[email protected]f4e426b2008-11-05 00:24:49771 // content length, or if the tunnel was not established successfully.
772 if (unfiltered_eof ||
773 (content_length_ != -1 && content_read_ > content_length_) ||
774 establishing_tunnel_)
[email protected]96d570e42008-08-05 22:43:04775 keep_alive = false;
initial.commit586acc5fe2008-07-26 22:42:52776 }
777 }
778
[email protected]96d570e42008-08-05 22:43:04779 // Clean up the HttpConnection if we are done.
initial.commit586acc5fe2008-07-26 22:42:52780 if (done) {
[email protected]56300172008-11-06 18:42:55781 LogTransactionMetrics();
initial.commit586acc5fe2008-07-26 22:42:52782 if (!keep_alive)
783 connection_.set_socket(NULL);
784 connection_.Reset();
[email protected]96d570e42008-08-05 22:43:04785 // The next Read call will return 0 (EOF).
initial.commit586acc5fe2008-07-26 22:42:52786 }
787
788 // Clear these to avoid leaving around old state.
789 read_buf_ = NULL;
790 read_buf_len_ = 0;
791
792 return result;
793}
794
[email protected]56300172008-11-06 18:42:55795void HttpNetworkTransaction::LogTransactionMetrics() const {
796 base::TimeDelta duration = base::Time::Now() - response_.request_time;
797 if (60 < duration.InMinutes())
798 return;
799 UMA_HISTOGRAM_LONG_TIMES(L"Net.Transaction_Latency", duration);
800 if (!duration.InMilliseconds())
801 return;
802 UMA_HISTOGRAM_COUNTS(L"Net.Transaction_Bandwidth",
803 static_cast<int> (content_read_ / duration.InMilliseconds()));
804}
805
[email protected]27161fb2008-11-03 23:39:05806int HttpNetworkTransaction::DidReadResponseHeaders() {
[email protected]231d5a32008-09-13 00:45:27807 scoped_refptr<HttpResponseHeaders> headers;
808 if (has_found_status_line_start()) {
809 headers = new HttpResponseHeaders(
810 HttpUtil::AssembleRawHeaders(
811 header_buf_.get(), header_buf_body_offset_));
812 } else {
813 // Fabricate a status line to to preserve the HTTP/0.9 version.
814 // (otherwise HttpResponseHeaders will default it to HTTP/1.0).
815 headers = new HttpResponseHeaders(std::string("HTTP/0.9 200 OK"));
816 }
817
[email protected]f9d44aa2008-09-23 23:57:17818 if (headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
819 // Require the "HTTP/1.x" status line for SSL CONNECT.
820 if (establishing_tunnel_)
821 return ERR_TUNNEL_CONNECTION_FAILED;
[email protected]231d5a32008-09-13 00:45:27822
[email protected]f9d44aa2008-09-23 23:57:17823 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
824 // indicates a buggy server. See:
825 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
826 if (request_->method == "PUT")
827 return ERR_METHOD_NOT_SUPPORTED;
828 }
initial.commit586acc5fe2008-07-26 22:42:52829
[email protected]d1ec59082009-02-11 02:48:15830 if (establishing_tunnel_) {
831 if (headers->response_code() == 200) {
832 if (header_buf_body_offset_ != header_buf_len_) {
833 // The proxy sent extraneous data after the headers.
834 return ERR_TUNNEL_CONNECTION_FAILED;
835 }
836 next_state_ = STATE_SSL_CONNECT_OVER_TUNNEL;
837 // Reset for the real request and response headers.
838 request_headers_.clear();
839 request_headers_bytes_sent_ = 0;
840 header_buf_len_ = 0;
841 header_buf_body_offset_ = 0;
842 establishing_tunnel_ = false;
843 return OK;
844 }
845 // Sanitize any illegal response code for CONNECT to prevent us from
846 // handling it by mistake. See http://crbug.com/7338.
847 if (headers->response_code() < 400 || headers->response_code() > 599)
848 headers->set_response_code(500); // Masquerade as a 500.
849 }
850
initial.commit586acc5fe2008-07-26 22:42:52851 // Check for an intermediate 100 Continue response. An origin server is
852 // allowed to send this response even if we didn't ask for it, so we just
853 // need to skip over it.
854 if (headers->response_code() == 100) {
[email protected]96d570e42008-08-05 22:43:04855 header_buf_len_ -= header_buf_body_offset_;
856 // If we've already received some bytes after the 100 Continue response,
857 // move them to the beginning of header_buf_.
858 if (header_buf_len_) {
859 memmove(header_buf_.get(), header_buf_.get() + header_buf_body_offset_,
860 header_buf_len_);
861 }
initial.commit586acc5fe2008-07-26 22:42:52862 header_buf_body_offset_ = -1;
863 next_state_ = STATE_READ_HEADERS;
864 return OK;
865 }
866
867 response_.headers = headers;
868 response_.vary_data.Init(*request_, *response_.headers);
869
[email protected]f9ee6b52008-11-08 06:46:23870 int rv = HandleAuthChallenge();
871 if (rv == WILL_RESTART_TRANSACTION) {
872 DCHECK(next_state_ == STATE_INIT_CONNECTION);
873 return OK;
874 }
[email protected]c3b35c22008-09-27 03:19:42875 if (rv != OK)
876 return rv;
877
initial.commit586acc5fe2008-07-26 22:42:52878 // Figure how to determine EOF:
879
880 // For certain responses, we know the content length is always 0.
881 switch (response_.headers->response_code()) {
[email protected]96d570e42008-08-05 22:43:04882 case 204: // No Content
883 case 205: // Reset Content
884 case 304: // Not Modified
initial.commit586acc5fe2008-07-26 22:42:52885 content_length_ = 0;
886 break;
887 }
888
889 if (content_length_ == -1) {
890 // Ignore spurious chunked responses from HTTP/1.0 servers and proxies.
891 // Otherwise "Transfer-Encoding: chunked" trumps "Content-Length: N"
[email protected]f9d44aa2008-09-23 23:57:17892 if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1) &&
initial.commit586acc5fe2008-07-26 22:42:52893 response_.headers->HasHeaderValue("Transfer-Encoding", "chunked")) {
894 chunked_decoder_.reset(new HttpChunkedDecoder());
895 } else {
896 content_length_ = response_.headers->GetContentLength();
897 // If content_length_ is still -1, then we have to wait for the server to
898 // close the connection.
899 }
900 }
901
[email protected]6b9833e2008-09-10 20:32:25902 if (using_ssl_ && !establishing_tunnel_) {
[email protected]4628a2a2008-08-14 20:33:25903 SSLClientSocket* ssl_socket =
904 reinterpret_cast<SSLClientSocket*>(connection_.socket());
905 ssl_socket->GetSSLInfo(&response_.ssl_info);
906 }
907
initial.commit586acc5fe2008-07-26 22:42:52908 return OK;
909}
910
[email protected]ccb40e52008-09-17 20:54:40911int HttpNetworkTransaction::HandleCertificateError(int error) {
912 DCHECK(using_ssl_);
913
914 const int kCertFlags = LOAD_IGNORE_CERT_COMMON_NAME_INVALID |
915 LOAD_IGNORE_CERT_DATE_INVALID |
916 LOAD_IGNORE_CERT_AUTHORITY_INVALID |
917 LOAD_IGNORE_CERT_WRONG_USAGE;
918 if (request_->load_flags & kCertFlags) {
919 switch (error) {
920 case ERR_CERT_COMMON_NAME_INVALID:
921 if (request_->load_flags & LOAD_IGNORE_CERT_COMMON_NAME_INVALID)
922 error = OK;
923 break;
924 case ERR_CERT_DATE_INVALID:
925 if (request_->load_flags & LOAD_IGNORE_CERT_DATE_INVALID)
926 error = OK;
927 break;
928 case ERR_CERT_AUTHORITY_INVALID:
929 if (request_->load_flags & LOAD_IGNORE_CERT_AUTHORITY_INVALID)
930 error = OK;
931 break;
932 }
933 }
934
935 if (error != OK) {
936 SSLClientSocket* ssl_socket =
937 reinterpret_cast<SSLClientSocket*>(connection_.socket());
938 ssl_socket->GetSSLInfo(&response_.ssl_info);
939 }
940 return error;
941}
942
[email protected]c5949a32008-10-08 17:28:23943int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
[email protected]5a179bcc2008-10-13 18:10:59944 switch (error) {
945 case ERR_SSL_PROTOCOL_ERROR:
946 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
[email protected]aaead502008-10-15 00:20:11947 if (ssl_config_.tls1_enabled) {
[email protected]5a179bcc2008-10-13 18:10:59948 // This could be a TLS-intolerant server or an SSL 3.0 server that
949 // chose a TLS-only cipher suite. Turn off TLS 1.0 and retry.
[email protected]aaead502008-10-15 00:20:11950 ssl_config_.tls1_enabled = false;
[email protected]5a179bcc2008-10-13 18:10:59951 connection_.set_socket(NULL);
952 connection_.Reset();
953 next_state_ = STATE_INIT_CONNECTION;
954 error = OK;
955 }
956 break;
[email protected]c5949a32008-10-08 17:28:23957 }
[email protected]c5949a32008-10-08 17:28:23958 return error;
959}
960
[email protected]96d570e42008-08-05 22:43:04961// This method determines whether it is safe to resend the request after an
962// IO error. It can only be called in response to request header or body
963// write errors or response header read errors. It should not be used in
964// other cases, such as a Connect error.
initial.commit586acc5fe2008-07-26 22:42:52965int HttpNetworkTransaction::HandleIOError(int error) {
966 switch (error) {
967 // If we try to reuse a connection that the server is in the process of
968 // closing, we may end up successfully writing out our request (or a
969 // portion of our request) only to find a connection error when we try to
970 // read from (or finish writing to) the socket.
971 case ERR_CONNECTION_RESET:
972 case ERR_CONNECTION_CLOSED:
973 case ERR_CONNECTION_ABORTED:
[email protected]2a5c76b2008-09-25 22:15:16974 if (ShouldResendRequest())
initial.commit586acc5fe2008-07-26 22:42:52975 error = OK;
initial.commit586acc5fe2008-07-26 22:42:52976 break;
977 }
978 return error;
979}
980
[email protected]c3b35c22008-09-27 03:19:42981void HttpNetworkTransaction::ResetStateForRestart() {
982 header_buf_.reset();
983 header_buf_capacity_ = 0;
984 header_buf_len_ = 0;
985 header_buf_body_offset_ = -1;
986 header_buf_http_offset_ = -1;
987 content_length_ = -1;
988 content_read_ = 0;
989 read_buf_ = NULL;
990 read_buf_len_ = 0;
991 request_headers_.clear();
992 request_headers_bytes_sent_ = 0;
993 chunked_decoder_.reset();
[email protected]038e9a32008-10-08 22:40:16994 // Reset the scoped_refptr
995 response_.headers = NULL;
996 response_.auth_challenge = NULL;
[email protected]c3b35c22008-09-27 03:19:42997}
998
[email protected]2a5c76b2008-09-25 22:15:16999bool HttpNetworkTransaction::ShouldResendRequest() {
1000 // NOTE: we resend a request only if we reused a keep-alive connection.
1001 // This automatically prevents an infinite resend loop because we'll run
1002 // out of the cached keep-alive connections eventually.
1003 if (establishing_tunnel_ ||
1004 !reused_socket_ || // We didn't reuse a keep-alive connection.
1005 header_buf_len_) { // We have received some response headers.
1006 return false;
1007 }
1008 connection_.set_socket(NULL);
1009 connection_.Reset();
[email protected]372d34a2008-11-05 21:30:511010 // There are two reasons we need to clear request_headers_. 1) It contains
1011 // the real request headers, but we may need to resend the CONNECT request
1012 // first to recreate the SSL tunnel. 2) An empty request_headers_ causes
1013 // BuildRequestHeaders to be called, which rewinds request_body_stream_ to
1014 // the beginning of request_->upload_data.
1015 request_headers_.clear();
[email protected]2a5c76b2008-09-25 22:15:161016 request_headers_bytes_sent_ = 0;
[email protected]2a5c76b2008-09-25 22:15:161017 next_state_ = STATE_INIT_CONNECTION; // Resend the request.
1018 return true;
1019}
1020
[email protected]86ec30d2008-09-29 21:53:541021int HttpNetworkTransaction::ReconsiderProxyAfterError(int error) {
1022 DCHECK(!pac_request_);
1023
1024 // A failure to resolve the hostname or any error related to establishing a
1025 // TCP connection could be grounds for trying a new proxy configuration.
[email protected]7be51312008-09-29 23:21:301026 //
1027 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1028 // to proxy servers. The hostname in those URLs might fail to resolve if we
1029 // are still using a non-proxy config. We need to check if a proxy config
1030 // now exists that corresponds to a proxy server that could load the URL.
1031 //
[email protected]86ec30d2008-09-29 21:53:541032 switch (error) {
1033 case ERR_NAME_NOT_RESOLVED:
1034 case ERR_INTERNET_DISCONNECTED:
1035 case ERR_ADDRESS_UNREACHABLE:
1036 case ERR_CONNECTION_CLOSED:
1037 case ERR_CONNECTION_RESET:
1038 case ERR_CONNECTION_REFUSED:
1039 case ERR_CONNECTION_ABORTED:
1040 case ERR_TIMED_OUT:
1041 case ERR_TUNNEL_CONNECTION_FAILED:
1042 break;
1043 default:
1044 return error;
1045 }
1046
[email protected]677c90572008-12-10 09:03:151047 if (request_->load_flags & LOAD_BYPASS_PROXY) {
1048 return error;
1049 }
1050
[email protected]86ec30d2008-09-29 21:53:541051 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1052 request_->url, &proxy_info_, &io_callback_, &pac_request_);
1053 if (rv == OK || rv == ERR_IO_PENDING) {
1054 connection_.set_socket(NULL);
1055 connection_.Reset();
1056 DCHECK(!request_headers_bytes_sent_);
1057 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1058 } else {
1059 rv = error;
1060 }
1061
1062 return rv;
1063}
1064
[email protected]c3b35c22008-09-27 03:19:421065void HttpNetworkTransaction::AddAuthorizationHeader(HttpAuth::Target target) {
[email protected]f9ee6b52008-11-08 06:46:231066 // If we have no authentication information, check if we can select
1067 // a cache entry preemptively (based on the path).
[email protected]5d0153c512009-01-12 19:08:361068 if (!HaveAuth(target) && !SelectPreemptiveAuth(target))
[email protected]f9ee6b52008-11-08 06:46:231069 return;
license.botbf09a502008-08-24 00:55:551070
[email protected]f9ee6b52008-11-08 06:46:231071 DCHECK(HaveAuth(target));
[email protected]aaead502008-10-15 00:20:111072
[email protected]c3b35c22008-09-27 03:19:421073 // Add a Authorization/Proxy-Authorization header line.
1074 std::string credentials = auth_handler_[target]->GenerateCredentials(
[email protected]f9ee6b52008-11-08 06:46:231075 auth_identity_[target].username,
1076 auth_identity_[target].password,
[email protected]c3b35c22008-09-27 03:19:421077 request_,
1078 &proxy_info_);
1079 request_headers_ += HttpAuth::GetAuthorizationHeaderName(target) +
1080 ": " + credentials + "\r\n";
1081}
1082
1083void HttpNetworkTransaction::ApplyAuth() {
1084 // We expect using_proxy_ and using_tunnel_ to be mutually exclusive.
1085 DCHECK(!using_proxy_ || !using_tunnel_);
1086
1087 // Don't send proxy auth after tunnel has been established.
1088 bool should_apply_proxy_auth = using_proxy_ || establishing_tunnel_;
1089
1090 // Don't send origin server auth while establishing tunnel.
1091 bool should_apply_server_auth = !establishing_tunnel_;
1092
[email protected]f9ee6b52008-11-08 06:46:231093 if (should_apply_proxy_auth)
[email protected]c3b35c22008-09-27 03:19:421094 AddAuthorizationHeader(HttpAuth::AUTH_PROXY);
[email protected]f9ee6b52008-11-08 06:46:231095 if (should_apply_server_auth)
[email protected]c3b35c22008-09-27 03:19:421096 AddAuthorizationHeader(HttpAuth::AUTH_SERVER);
1097}
1098
[email protected]f9ee6b52008-11-08 06:46:231099GURL HttpNetworkTransaction::AuthOrigin(HttpAuth::Target target) const {
1100 return target == HttpAuth::AUTH_PROXY ?
1101 GURL("http://" + proxy_info_.proxy_server()) :
1102 request_->url.GetOrigin();
1103}
1104
1105std::string HttpNetworkTransaction::AuthPath(HttpAuth::Target target)
1106 const {
1107 // Proxy authentication realms apply to all paths. So we will use
1108 // empty string in place of an absolute path.
1109 return target == HttpAuth::AUTH_PROXY ?
1110 std::string() : request_->url.path();
1111}
1112
1113void HttpNetworkTransaction::InvalidateRejectedAuthFromCache(
1114 HttpAuth::Target target) {
1115 DCHECK(HaveAuth(target));
1116
1117 // TODO(eroman): this short-circuit can be relaxed. If the realm of
1118 // the preemptively used auth entry matches the realm of the subsequent
1119 // challenge, then we can invalidate the preemptively used entry.
1120 // Otherwise as-is we may send the failed credentials one extra time.
1121 if (auth_identity_[target].source == HttpAuth::IDENT_SRC_PATH_LOOKUP)
1122 return;
1123
1124 // Clear the cache entry for the identity we just failed on.
1125 // Note: we require the username/password to match before invalidating
1126 // since the entry in the cache may be newer than what we used last time.
1127 session_->auth_cache()->Remove(AuthOrigin(target),
[email protected]5d0153c512009-01-12 19:08:361128 auth_handler_[target]->realm(),
[email protected]f9ee6b52008-11-08 06:46:231129 auth_identity_[target].username,
1130 auth_identity_[target].password);
1131}
1132
1133bool HttpNetworkTransaction::SelectPreemptiveAuth(HttpAuth::Target target) {
1134 DCHECK(!HaveAuth(target));
1135
1136 // Don't do preemptive authorization if the URL contains a username/password,
1137 // since we must first be challenged in order to use the URL's identity.
1138 if (request_->url.has_username())
1139 return false;
1140
1141 // SelectPreemptiveAuth() is on the critical path for each request, so it
1142 // is expected to be fast. LookupByPath() is fast in the common case, since
1143 // the number of http auth cache entries is expected to be very small.
1144 // (For most users in fact, it will be 0.)
1145
1146 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByPath(
1147 AuthOrigin(target), AuthPath(target));
1148
1149 if (entry) {
1150 auth_identity_[target].source = HttpAuth::IDENT_SRC_PATH_LOOKUP;
1151 auth_identity_[target].invalid = false;
1152 auth_identity_[target].username = entry->username();
1153 auth_identity_[target].password = entry->password();
1154 auth_handler_[target] = entry->handler();
1155 return true;
1156 }
1157 return false;
1158}
1159
1160bool HttpNetworkTransaction::SelectNextAuthIdentityToTry(
1161 HttpAuth::Target target) {
1162 DCHECK(auth_handler_[target]);
1163 DCHECK(auth_identity_[target].invalid);
1164
1165 // Try to use the username/password encoded into the URL first.
1166 // (By checking source == IDENT_SRC_NONE, we make sure that this
1167 // is only done once for the transaction.)
1168 if (target == HttpAuth::AUTH_SERVER && request_->url.has_username() &&
1169 auth_identity_[target].source == HttpAuth::IDENT_SRC_NONE) {
1170 auth_identity_[target].source = HttpAuth::IDENT_SRC_URL;
1171 auth_identity_[target].invalid = false;
[email protected]77848d12008-11-14 00:00:221172 // TODO(wtc) It may be necessary to unescape the username and password
1173 // after extracting them from the URL. We should be careful about
1174 // embedded nulls in that case.
1175 auth_identity_[target].username = ASCIIToWide(request_->url.username());
1176 auth_identity_[target].password = ASCIIToWide(request_->url.password());
[email protected]f9ee6b52008-11-08 06:46:231177 // TODO(eroman): If the password is blank, should we also try combining
1178 // with a password from the cache?
1179 return true;
1180 }
1181
1182 // Check the auth cache for a realm entry.
1183 HttpAuthCache::Entry* entry = session_->auth_cache()->LookupByRealm(
1184 AuthOrigin(target), auth_handler_[target]->realm());
1185
1186 if (entry) {
1187 // Disallow re-using of identity if the scheme of the originating challenge
1188 // does not match. This protects against the following situation:
1189 // 1. Browser prompts user to sign into DIGEST realm="Foo".
1190 // 2. Since the auth-scheme is not BASIC, the user is reasured that it
1191 // will not be sent over the wire in clear text. So they use their
1192 // most trusted password.
1193 // 3. Next, the browser receives a challenge for BASIC realm="Foo". This
1194 // is the same realm that we have a cached identity for. However if
1195 // we use that identity, it would get sent over the wire in
1196 // clear text (which isn't what the user agreed to when entering it).
1197 if (entry->handler()->scheme() != auth_handler_[target]->scheme()) {
1198 LOG(WARNING) << "The scheme of realm " << auth_handler_[target]->realm()
1199 << " has changed from " << entry->handler()->scheme()
1200 << " to " << auth_handler_[target]->scheme();
1201 return false;
1202 }
1203
1204 auth_identity_[target].source = HttpAuth::IDENT_SRC_REALM_LOOKUP;
1205 auth_identity_[target].invalid = false;
1206 auth_identity_[target].username = entry->username();
1207 auth_identity_[target].password = entry->password();
1208 return true;
1209 }
1210 return false;
1211}
1212
1213int HttpNetworkTransaction::HandleAuthChallenge() {
[email protected]c3b35c22008-09-27 03:19:421214 DCHECK(response_.headers);
1215
1216 int status = response_.headers->response_code();
1217 if (status != 401 && status != 407)
1218 return OK;
1219 HttpAuth::Target target = status == 407 ?
1220 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1221
[email protected]038e9a32008-10-08 22:40:161222 if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1223 return ERR_UNEXPECTED_PROXY_AUTH;
[email protected]c3b35c22008-09-27 03:19:421224
[email protected]d1ec59082009-02-11 02:48:151225 if (target == HttpAuth::AUTH_SERVER && establishing_tunnel_)
1226 return ERR_UNEXPECTED_SERVER_AUTH;
1227
[email protected]f9ee6b52008-11-08 06:46:231228 // The auth we tried just failed, hence it can't be valid. Remove it from
1229 // the cache so it won't be used again.
1230 if (HaveAuth(target))
1231 InvalidateRejectedAuthFromCache(target);
1232
1233 auth_identity_[target].invalid = true;
1234
[email protected]c3b35c22008-09-27 03:19:421235 // Find the best authentication challenge that we support.
[email protected]f9ee6b52008-11-08 06:46:231236 HttpAuth::ChooseBestChallenge(response_.headers.get(),
1237 target,
1238 &auth_handler_[target]);
[email protected]c3b35c22008-09-27 03:19:421239
1240 // We found no supported challenge -- let the transaction continue
1241 // so we end up displaying the error page.
[email protected]f9ee6b52008-11-08 06:46:231242 if (!auth_handler_[target])
[email protected]c3b35c22008-09-27 03:19:421243 return OK;
1244
[email protected]f9ee6b52008-11-08 06:46:231245 // Pick a new auth identity to try, by looking to the URL and auth cache.
1246 // If an identity to try is found, it is saved to auth_identity_[target].
1247 bool has_identity_to_try = SelectNextAuthIdentityToTry(target);
1248 DCHECK(has_identity_to_try == !auth_identity_[target].invalid);
1249
1250 if (has_identity_to_try) {
1251 DCHECK(user_callback_);
1252 PrepareForAuthRestart(target);
1253 return WILL_RESTART_TRANSACTION;
[email protected]f9ee6b52008-11-08 06:46:231254 }
1255
[email protected]74da3732009-01-30 23:45:031256 // We have exhausted all identity possibilities, all we can do now is
1257 // pass the challenge information back to the client.
1258 PopulateAuthChallenge(target);
[email protected]f9ee6b52008-11-08 06:46:231259 return OK;
1260}
1261
1262void HttpNetworkTransaction::PopulateAuthChallenge(HttpAuth::Target target) {
1263 // Populates response_.auth_challenge with the authentication challenge info.
1264 // This info is consumed by URLRequestHttpJob::GetAuthChallengeInfo().
1265
1266 AuthChallengeInfo* auth_info = new AuthChallengeInfo;
[email protected]c3b35c22008-09-27 03:19:421267 auth_info->is_proxy = target == HttpAuth::AUTH_PROXY;
[email protected]f9ee6b52008-11-08 06:46:231268 auth_info->scheme = ASCIIToWide(auth_handler_[target]->scheme());
[email protected]c3b35c22008-09-27 03:19:421269 // TODO(eroman): decode realm according to RFC 2047.
[email protected]f9ee6b52008-11-08 06:46:231270 auth_info->realm = ASCIIToWide(auth_handler_[target]->realm());
[email protected]c3b35c22008-09-27 03:19:421271 if (target == HttpAuth::AUTH_PROXY) {
1272 auth_info->host = ASCIIToWide(proxy_info_.proxy_server());
1273 } else {
1274 DCHECK(target == HttpAuth::AUTH_SERVER);
1275 auth_info->host = ASCIIToWide(request_->url.host());
1276 }
[email protected]f9ee6b52008-11-08 06:46:231277 response_.auth_challenge = auth_info;
[email protected]c3b35c22008-09-27 03:19:421278}
1279
1280} // namespace net