blob: e2cd99da864fce7822eb1e635d9f5c0664c0530c [file] [log] [blame]
[email protected]fecef222012-01-05 02:26:151// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// 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
[email protected]175adac2008-07-30 17:28:045#include "net/url_request/url_request_http_job.h"
initial.commit586acc5fe2008-07-26 22:42:526
[email protected]4ed2755f2008-12-15 09:01:337#include "base/base_switches.h"
[email protected]4f9e5c82011-11-17 16:04:568#include "base/bind.h"
[email protected]084262c2011-12-01 21:12:479#include "base/bind_helpers.h"
[email protected]4ed2755f2008-12-15 09:01:3310#include "base/command_line.h"
[email protected]39ce5c02008-08-22 04:03:4411#include "base/compiler_specific.h"
[email protected]60889422008-09-23 01:18:1612#include "base/file_util.h"
13#include "base/file_version_info.h"
initial.commit586acc5fe2008-07-26 22:42:5214#include "base/message_loop.h"
[email protected]8684a8812011-03-22 13:59:3815#include "base/metrics/field_trial.h"
[email protected]ec23f522011-02-22 21:01:3816#include "base/metrics/histogram.h"
[email protected]5b90b5d2009-04-30 23:06:0117#include "base/rand_util.h"
initial.commit586acc5fe2008-07-26 22:42:5218#include "base/string_util.h"
[email protected]dd29bcd72011-03-24 00:03:4419#include "base/time.h"
[email protected]a9cea7542009-05-20 04:30:2320#include "net/base/cert_status_flags.h"
[email protected]423041b2008-10-27 17:39:2821#include "net/base/filter.h"
[email protected]6d81b482011-02-22 19:47:1922#include "net/base/host_port_pair.h"
[email protected]b8430722008-09-17 20:05:4423#include "net/base/load_flags.h"
[email protected]dd29bcd72011-03-24 00:03:4424#include "net/base/mime_util.h"
initial.commit586acc5fe2008-07-26 22:42:5225#include "net/base/net_errors.h"
26#include "net/base/net_util.h"
[email protected]636eccd2011-06-28 12:28:0127#include "net/base/network_delegate.h"
[email protected]60889422008-09-23 01:18:1628#include "net/base/sdch_manager.h"
[email protected]aa84a7e2012-03-15 21:29:0629#include "net/cookies/cookie_monster.h"
[email protected]7a299a92012-10-24 23:54:5030#include "net/http/http_network_session.h"
[email protected]8c76ae22010-04-20 22:15:4331#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2132#include "net/http/http_response_headers.h"
initial.commit586acc5fe2008-07-26 22:42:5233#include "net/http/http_response_info.h"
[email protected]9094b602012-02-27 21:44:5834#include "net/http/http_status_code.h"
initial.commit586acc5fe2008-07-26 22:42:5235#include "net/http/http_transaction.h"
[email protected]5a07c192012-07-30 20:18:2236#include "net/http/http_transaction_delegate.h"
initial.commit586acc5fe2008-07-26 22:42:5237#include "net/http/http_transaction_factory.h"
[email protected]0757e7702009-03-27 04:00:2238#include "net/http/http_util.h"
[email protected]536fd0b2013-03-14 17:41:5739#include "net/ssl/ssl_cert_request_info.h"
40#include "net/ssl/ssl_config_service.h"
[email protected]7f269182011-10-16 01:58:3441#include "net/url_request/fraudulent_certificate_reporter.h"
[email protected]ee4c30d2012-11-07 15:08:4342#include "net/url_request/http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5243#include "net/url_request/url_request.h"
[email protected]319d9e6f2009-02-18 19:47:2144#include "net/url_request/url_request_context.h"
initial.commit586acc5fe2008-07-26 22:42:5245#include "net/url_request/url_request_error_job.h"
[email protected]06965e02009-09-04 21:36:4246#include "net/url_request/url_request_redirect_job.h"
[email protected]6b3f9642010-11-25 02:29:0647#include "net/url_request/url_request_throttler_header_adapter.h"
48#include "net/url_request/url_request_throttler_manager.h"
initial.commit586acc5fe2008-07-26 22:42:5249
[email protected]8c76ae22010-04-20 22:15:4350static const char kAvailDictionaryHeader[] = "Avail-Dictionary";
51
[email protected]4f5656c62010-12-13 10:47:0952namespace net {
53
[email protected]2e92354c2011-03-25 20:49:5354class URLRequestHttpJob::HttpFilterContext : public FilterContext {
55 public:
56 explicit HttpFilterContext(URLRequestHttpJob* job);
57 virtual ~HttpFilterContext();
58
59 // FilterContext implementation.
[email protected]1e43b6812012-08-19 19:14:0060 virtual bool GetMimeType(std::string* mime_type) const OVERRIDE;
61 virtual bool GetURL(GURL* gurl) const OVERRIDE;
62 virtual base::Time GetRequestTime() const OVERRIDE;
63 virtual bool IsCachedContent() const OVERRIDE;
64 virtual bool IsDownload() const OVERRIDE;
65 virtual bool IsSdchResponse() const OVERRIDE;
66 virtual int64 GetByteReadCount() const OVERRIDE;
67 virtual int GetResponseCode() const OVERRIDE;
68 virtual void RecordPacketStats(StatisticSelector statistic) const OVERRIDE;
[email protected]2e92354c2011-03-25 20:49:5369
[email protected]46668fe52011-05-04 19:03:2370 // Method to allow us to reset filter context for a response that should have
71 // been SDCH encoded when there is an update due to an explicit HTTP header.
72 void ResetSdchResponseToFalse();
73
[email protected]2e92354c2011-03-25 20:49:5374 private:
75 URLRequestHttpJob* job_;
76
77 DISALLOW_COPY_AND_ASSIGN(HttpFilterContext);
78};
79
[email protected]5a07c192012-07-30 20:18:2280class URLRequestHttpJob::HttpTransactionDelegateImpl
81 : public HttpTransactionDelegate {
82 public:
[email protected]cc05edc2013-03-08 18:04:4183 HttpTransactionDelegateImpl(
84 URLRequest* request, NetworkDelegate* network_delegate)
[email protected]5a07c192012-07-30 20:18:2285 : request_(request),
[email protected]cc05edc2013-03-08 18:04:4186 network_delegate_(network_delegate),
[email protected]a9e0d1412012-08-20 22:13:0187 cache_active_(false),
88 network_active_(false) {
[email protected]5a07c192012-07-30 20:18:2289 }
90 virtual ~HttpTransactionDelegateImpl() {
91 OnDetachRequest();
92 }
93 void OnDetachRequest() {
94 if (request_ == NULL || network_delegate_ == NULL)
95 return;
[email protected]a9e0d1412012-08-20 22:13:0196 network_delegate_->NotifyRequestWaitStateChange(
[email protected]5a07c192012-07-30 20:18:2297 *request_,
[email protected]a9e0d1412012-08-20 22:13:0198 NetworkDelegate::REQUEST_WAIT_STATE_RESET);
99 cache_active_ = false;
100 network_active_ = false;
[email protected]5a07c192012-07-30 20:18:22101 request_ = NULL;
102 }
103 virtual void OnCacheActionStart() OVERRIDE {
104 if (request_ == NULL || network_delegate_ == NULL)
105 return;
[email protected]a9e0d1412012-08-20 22:13:01106 DCHECK(!cache_active_ && !network_active_);
107 cache_active_ = true;
108 network_delegate_->NotifyRequestWaitStateChange(
[email protected]5a07c192012-07-30 20:18:22109 *request_,
[email protected]a9e0d1412012-08-20 22:13:01110 NetworkDelegate::REQUEST_WAIT_STATE_CACHE_START);
[email protected]5a07c192012-07-30 20:18:22111 }
112 virtual void OnCacheActionFinish() OVERRIDE {
113 if (request_ == NULL || network_delegate_ == NULL)
114 return;
[email protected]a9e0d1412012-08-20 22:13:01115 DCHECK(cache_active_ && !network_active_);
116 cache_active_ = false;
117 network_delegate_->NotifyRequestWaitStateChange(
[email protected]5a07c192012-07-30 20:18:22118 *request_,
[email protected]a9e0d1412012-08-20 22:13:01119 NetworkDelegate::REQUEST_WAIT_STATE_CACHE_FINISH);
120 }
121 virtual void OnNetworkActionStart() OVERRIDE {
122 if (request_ == NULL || network_delegate_ == NULL)
123 return;
124 DCHECK(!cache_active_ && !network_active_);
125 network_active_ = true;
126 network_delegate_->NotifyRequestWaitStateChange(
127 *request_,
128 NetworkDelegate::REQUEST_WAIT_STATE_NETWORK_START);
129 }
130 virtual void OnNetworkActionFinish() OVERRIDE {
131 if (request_ == NULL || network_delegate_ == NULL)
132 return;
133 DCHECK(!cache_active_ && network_active_);
134 network_active_ = false;
135 network_delegate_->NotifyRequestWaitStateChange(
136 *request_,
137 NetworkDelegate::REQUEST_WAIT_STATE_NETWORK_FINISH);
[email protected]5a07c192012-07-30 20:18:22138 }
139 private:
140 URLRequest* request_;
141 NetworkDelegate* network_delegate_;
[email protected]a9e0d1412012-08-20 22:13:01142 bool cache_active_;
143 bool network_active_;
[email protected]5a07c192012-07-30 20:18:22144};
145
[email protected]fc01f232011-03-17 19:06:01146URLRequestHttpJob::HttpFilterContext::HttpFilterContext(URLRequestHttpJob* job)
147 : job_(job) {
148 DCHECK(job_);
149}
150
151URLRequestHttpJob::HttpFilterContext::~HttpFilterContext() {
152}
153
154bool URLRequestHttpJob::HttpFilterContext::GetMimeType(
155 std::string* mime_type) const {
156 return job_->GetMimeType(mime_type);
157}
158
159bool URLRequestHttpJob::HttpFilterContext::GetURL(GURL* gurl) const {
160 if (!job_->request())
161 return false;
162 *gurl = job_->request()->url();
163 return true;
164}
165
166base::Time URLRequestHttpJob::HttpFilterContext::GetRequestTime() const {
167 return job_->request() ? job_->request()->request_time() : base::Time();
168}
169
170bool URLRequestHttpJob::HttpFilterContext::IsCachedContent() const {
[email protected]dd29bcd72011-03-24 00:03:44171 return job_->is_cached_content_;
[email protected]fc01f232011-03-17 19:06:01172}
173
174bool URLRequestHttpJob::HttpFilterContext::IsDownload() const {
175 return (job_->request_info_.load_flags & LOAD_IS_DOWNLOAD) != 0;
176}
177
[email protected]46668fe52011-05-04 19:03:23178void URLRequestHttpJob::HttpFilterContext::ResetSdchResponseToFalse() {
179 DCHECK(job_->sdch_dictionary_advertised_);
180 job_->sdch_dictionary_advertised_ = false;
181}
182
[email protected]fc01f232011-03-17 19:06:01183bool URLRequestHttpJob::HttpFilterContext::IsSdchResponse() const {
184 return job_->sdch_dictionary_advertised_;
185}
186
187int64 URLRequestHttpJob::HttpFilterContext::GetByteReadCount() const {
188 return job_->filter_input_byte_count();
189}
190
191int URLRequestHttpJob::HttpFilterContext::GetResponseCode() const {
192 return job_->GetResponseCode();
193}
194
195void URLRequestHttpJob::HttpFilterContext::RecordPacketStats(
196 StatisticSelector statistic) const {
197 job_->RecordPacketStats(statistic);
198}
199
initial.commit586acc5fe2008-07-26 22:42:52200// TODO(darin): make sure the port blocking code is not lost
initial.commit586acc5fe2008-07-26 22:42:52201// static
[email protected]4f5656c62010-12-13 10:47:09202URLRequestJob* URLRequestHttpJob::Factory(URLRequest* request,
[email protected]9f170462012-08-24 01:06:58203 NetworkDelegate* network_delegate,
[email protected]4f5656c62010-12-13 10:47:09204 const std::string& scheme) {
initial.commit586acc5fe2008-07-26 22:42:52205 DCHECK(scheme == "http" || scheme == "https");
206
[email protected]81293f482012-08-13 19:35:45207 if (!request->context()->http_transaction_factory()) {
initial.commit586acc5fe2008-07-26 22:42:52208 NOTREACHED() << "requires a valid context";
[email protected]9f170462012-08-24 01:06:58209 return new URLRequestErrorJob(
210 request, network_delegate, ERR_INVALID_ARGUMENT);
initial.commit586acc5fe2008-07-26 22:42:52211 }
212
[email protected]ce572df2012-05-04 19:47:17213 GURL redirect_url;
[email protected]8ccc69f2012-11-28 19:52:14214 if (request->GetHSTSRedirect(&redirect_url)) {
215 return new URLRequestRedirectJob(
216 request, network_delegate, redirect_url,
217 // Use status code 307 to preserve the method, so POST requests work.
218 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT);
219 }
[email protected]ee4c30d2012-11-07 15:08:43220 return new URLRequestHttpJob(request,
221 network_delegate,
222 request->context()->http_user_agent_settings());
initial.commit586acc5fe2008-07-26 22:42:52223}
224
[email protected]5394e422011-01-20 22:07:43225
[email protected]ee4c30d2012-11-07 15:08:43226URLRequestHttpJob::URLRequestHttpJob(
227 URLRequest* request,
228 NetworkDelegate* network_delegate,
229 const HttpUserAgentSettings* http_user_agent_settings)
[email protected]9f170462012-08-24 01:06:58230 : URLRequestJob(request, network_delegate),
[email protected]5033ab82013-03-22 20:17:46231 priority_(DEFAULT_PRIORITY),
initial.commit586acc5fe2008-07-26 22:42:52232 response_info_(NULL),
[email protected]34602282010-02-03 22:14:15233 response_cookies_save_index_(0),
[email protected]4f5656c62010-12-13 10:47:09234 proxy_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
235 server_auth_state_(AUTH_STATE_DONT_NEED_AUTH),
[email protected]34602282010-02-03 22:14:15236 ALLOW_THIS_IN_INITIALIZER_LIST(start_callback_(
[email protected]49639fa2011-12-20 23:22:41237 base::Bind(&URLRequestHttpJob::OnStartCompleted,
238 base::Unretained(this)))),
[email protected]636eccd2011-06-28 12:28:01239 ALLOW_THIS_IN_INITIALIZER_LIST(notify_before_headers_sent_callback_(
[email protected]084262c2011-12-01 21:12:47240 base::Bind(&URLRequestHttpJob::NotifyBeforeSendHeadersCallback,
241 base::Unretained(this)))),
[email protected]3589e552008-08-20 23:11:34242 read_in_progress_(false),
[email protected]2aecf7382009-06-17 04:14:27243 transaction_(NULL),
[email protected]a73a2802012-05-02 19:20:15244 throttling_entry_(NULL),
[email protected]5b90b5d2009-04-30 23:06:01245 sdch_dictionary_advertised_(false),
246 sdch_test_activated_(false),
[email protected]d8fd5132009-05-15 01:06:53247 sdch_test_control_(false),
[email protected]00e48bf2010-12-03 06:15:42248 is_cached_content_(false),
[email protected]ec23f522011-02-22 21:01:38249 request_creation_time_(),
[email protected]dd29bcd72011-03-24 00:03:44250 packet_timing_enabled_(false),
[email protected]bbaea8f2011-06-24 00:11:01251 done_(false),
[email protected]dd29bcd72011-03-24 00:03:44252 bytes_observed_in_packets_(0),
[email protected]dd29bcd72011-03-24 00:03:44253 request_time_snapshot_(),
254 final_packet_time_(),
[email protected]2e92354c2011-03-25 20:49:53255 ALLOW_THIS_IN_INITIALIZER_LIST(
256 filter_context_(new HttpFilterContext(this))),
[email protected]098b29112011-12-20 21:12:34257 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
[email protected]084262c2011-12-01 21:12:47258 ALLOW_THIS_IN_INITIALIZER_LIST(on_headers_received_callback_(
259 base::Bind(&URLRequestHttpJob::OnHeadersReceivedCallback,
260 base::Unretained(this)))),
[email protected]5a07c192012-07-30 20:18:22261 awaiting_callback_(false),
[email protected]cc05edc2013-03-08 18:04:41262 http_transaction_delegate_(new HttpTransactionDelegateImpl(
263 request, network_delegate)),
[email protected]ee4c30d2012-11-07 15:08:43264 http_user_agent_settings_(http_user_agent_settings) {
[email protected]a73a2802012-05-02 19:20:15265 URLRequestThrottlerManager* manager = request->context()->throttler_manager();
266 if (manager)
267 throttling_entry_ = manager->RegisterRequestUrl(request->url());
268
[email protected]ec23f522011-02-22 21:01:38269 ResetTimer();
initial.commit586acc5fe2008-07-26 22:42:52270}
271
[email protected]5033ab82013-03-22 20:17:46272URLRequestHttpJob::~URLRequestHttpJob() {
273 CHECK(!awaiting_callback_);
274
275 DCHECK(!sdch_test_control_ || !sdch_test_activated_);
276 if (!is_cached_content_) {
277 if (sdch_test_control_)
278 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_HOLDBACK);
279 if (sdch_test_activated_)
280 RecordPacketStats(FilterContext::SDCH_EXPERIMENT_DECODE);
281 }
282 // Make sure SDCH filters are told to emit histogram data while
283 // filter_context_ is still alive.
284 DestroyFilters();
285
286 if (sdch_dictionary_url_.is_valid()) {
287 // Prior to reaching the destructor, request_ has been set to a NULL
288 // pointer, so request_->url() is no longer valid in the destructor, and we
289 // use an alternate copy |request_info_.url|.
290 SdchManager* manager = SdchManager::Global();
291 // To be extra safe, since this is a "different time" from when we decided
292 // to get the dictionary, we'll validate that an SdchManager is available.
293 // At shutdown time, care is taken to be sure that we don't delete this
294 // globally useful instance "too soon," so this check is just defensive
295 // coding to assure that IF the system is shutting down, we don't have any
296 // problem if the manager was deleted ahead of time.
297 if (manager) // Defensive programming.
298 manager->FetchDictionary(request_info_.url, sdch_dictionary_url_);
299 }
300 DoneWithRequest(ABORTED);
301}
302
303void URLRequestHttpJob::SetPriority(RequestPriority priority) {
304 priority_ = priority;
305 if (transaction_)
306 transaction_->SetPriority(priority_);
307}
308
309void URLRequestHttpJob::Start() {
310 DCHECK(!transaction_.get());
311
312 // Ensure that we do not send username and password fields in the referrer.
313 GURL referrer(request_->GetSanitizedReferrer());
314
315 request_info_.url = request_->url();
316 request_info_.method = request_->method();
317 request_info_.load_flags = request_->load_flags();
318 request_info_.request_id = request_->identifier();
319
320 // Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
321 // from overriding headers that are controlled using other means. Otherwise a
322 // plugin could set a referrer although sending the referrer is inhibited.
323 request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kReferer);
324
325 // Our consumer should have made sure that this is a safe referrer. See for
326 // instance WebCore::FrameLoader::HideReferrer.
327 if (referrer.is_valid()) {
328 request_info_.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
329 referrer.spec());
330 }
331
332 request_info_.extra_headers.SetHeaderIfMissing(
333 HttpRequestHeaders::kUserAgent,
334 http_user_agent_settings_ ?
335 http_user_agent_settings_->GetUserAgent(request_->url()) :
336 EmptyString());
337
338 AddExtraHeaders();
339 AddCookieHeaderAndStart();
340}
341
342void URLRequestHttpJob::Kill() {
343 http_transaction_delegate_->OnDetachRequest();
344
345 if (!transaction_.get())
346 return;
347
348 weak_factory_.InvalidateWeakPtrs();
349 DestroyTransaction();
350 URLRequestJob::Kill();
351}
352
[email protected]175adac2008-07-30 17:28:04353void URLRequestHttpJob::NotifyHeadersComplete() {
initial.commit586acc5fe2008-07-26 22:42:52354 DCHECK(!response_info_);
355
356 response_info_ = transaction_->GetResponseInfo();
357
[email protected]d8fd5132009-05-15 01:06:53358 // Save boolean, as we'll need this info at destruction time, and filters may
359 // also need this info.
360 is_cached_content_ = response_info_->was_cached;
361
[email protected]a73a2802012-05-02 19:20:15362 if (!is_cached_content_ && throttling_entry_) {
[email protected]ea8141e2011-10-05 13:12:51363 URLRequestThrottlerHeaderAdapter response_adapter(GetResponseHeaders());
[email protected]2fd33ee92011-03-25 22:30:21364 throttling_entry_->UpdateWithResponse(request_info_.url.host(),
365 &response_adapter);
[email protected]6b3f9642010-11-25 02:29:06366 }
367
[email protected]fecef222012-01-05 02:26:15368 // The ordering of these calls is not important.
[email protected]77f6fb432009-09-05 14:21:09369 ProcessStrictTransportSecurityHeader();
[email protected]fecef222012-01-05 02:26:15370 ProcessPublicKeyPinsHeader();
[email protected]a9cea7542009-05-20 04:30:23371
[email protected]fe219872008-09-23 02:17:00372 if (SdchManager::Global() &&
373 SdchManager::Global()->IsInSupportedDomain(request_->url())) {
[email protected]264300242011-11-07 06:03:30374 const std::string name = "Get-Dictionary";
[email protected]60889422008-09-23 01:18:16375 std::string url_text;
376 void* iter = NULL;
377 // TODO(jar): We need to not fetch dictionaries the first time they are
378 // seen, but rather wait until we can justify their usefulness.
379 // For now, we will only fetch the first dictionary, which will at least
380 // require multiple suggestions before we get additional ones for this site.
381 // Eventually we should wait until a dictionary is requested several times
382 // before we even download it (so that we don't waste memory or bandwidth).
[email protected]ea8141e2011-10-05 13:12:51383 if (GetResponseHeaders()->EnumerateHeader(&iter, name, &url_text)) {
[email protected]d55ad15d2009-02-17 19:40:50384 // request_->url() won't be valid in the destructor, so we use an
385 // alternate copy.
[email protected]dd29bcd72011-03-24 00:03:44386 DCHECK_EQ(request_->url(), request_info_.url);
[email protected]d55ad15d2009-02-17 19:40:50387 // Resolve suggested URL relative to request url.
388 sdch_dictionary_url_ = request_info_.url.Resolve(url_text);
[email protected]60889422008-09-23 01:18:16389 }
390 }
391
[email protected]0757e7702009-03-27 04:00:22392 // The HTTP transaction may be restarted several times for the purposes
393 // of sending authorization information. Each time it restarts, we get
394 // notified of the headers completion so that we can update the cookie store.
395 if (transaction_->IsReadyToRestartForAuth()) {
396 DCHECK(!response_info_->auth_challenge.get());
[email protected]87a09a92011-07-14 15:50:50397 // TODO(battre): This breaks the webrequest API for
398 // URLRequestTestHTTP.BasicAuthWithCookies
[email protected]5796dc942011-07-14 19:26:10399 // where OnBeforeSendHeaders -> OnSendHeaders -> OnBeforeSendHeaders
[email protected]87a09a92011-07-14 15:50:50400 // occurs.
[email protected]f3cf9802011-10-28 18:44:58401 RestartTransactionWithAuth(AuthCredentials());
[email protected]0757e7702009-03-27 04:00:22402 return;
403 }
404
[email protected]4f5656c62010-12-13 10:47:09405 URLRequestJob::NotifyHeadersComplete();
initial.commit586acc5fe2008-07-26 22:42:52406}
407
[email protected]85c1dce2011-07-06 12:01:29408void URLRequestHttpJob::NotifyDone(const URLRequestStatus& status) {
[email protected]bbaea8f2011-06-24 00:11:01409 DoneWithRequest(FINISHED);
[email protected]dd29bcd72011-03-24 00:03:44410 URLRequestJob::NotifyDone(status);
411}
412
[email protected]175adac2008-07-30 17:28:04413void URLRequestHttpJob::DestroyTransaction() {
[email protected]c6a4eb92010-03-03 23:51:19414 DCHECK(transaction_.get());
initial.commit586acc5fe2008-07-26 22:42:52415
[email protected]bbaea8f2011-06-24 00:11:01416 DoneWithRequest(ABORTED);
[email protected]af4876d2008-10-21 23:10:57417 transaction_.reset();
initial.commit586acc5fe2008-07-26 22:42:52418 response_info_ = NULL;
419}
420
[email protected]175adac2008-07-30 17:28:04421void URLRequestHttpJob::StartTransaction() {
[email protected]cc05edc2013-03-08 18:04:41422 if (network_delegate()) {
423 int rv = network_delegate()->NotifyBeforeSendHeaders(
[email protected]084262c2011-12-01 21:12:47424 request_, notify_before_headers_sent_callback_,
[email protected]636eccd2011-06-28 12:28:01425 &request_info_.extra_headers);
426 // If an extension blocks the request, we rely on the callback to
[email protected]b4438d32012-09-27 06:15:30427 // MaybeStartTransactionInternal().
[email protected]636eccd2011-06-28 12:28:01428 if (rv == ERR_IO_PENDING) {
[email protected]9c235f042011-08-10 22:28:21429 SetBlockedOnDelegate();
[email protected]636eccd2011-06-28 12:28:01430 return;
431 }
[email protected]b4438d32012-09-27 06:15:30432 MaybeStartTransactionInternal(rv);
433 return;
[email protected]636eccd2011-06-28 12:28:01434 }
435 StartTransactionInternal();
436}
437
438void URLRequestHttpJob::NotifyBeforeSendHeadersCallback(int result) {
[email protected]9c235f042011-08-10 22:28:21439 SetUnblockedOnDelegate();
[email protected]636eccd2011-06-28 12:28:01440
[email protected]9045b8822012-01-13 20:35:35441 // Check that there are no callbacks to already canceled requests.
442 DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
443
[email protected]b4438d32012-09-27 06:15:30444 MaybeStartTransactionInternal(result);
445}
446
447void URLRequestHttpJob::MaybeStartTransactionInternal(int result) {
[email protected]636eccd2011-06-28 12:28:01448 if (result == OK) {
449 StartTransactionInternal();
450 } else {
[email protected]55b8a6c12012-06-13 22:03:42451 std::string source("delegate");
[email protected]636eccd2011-06-28 12:28:01452 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
[email protected]55b8a6c12012-06-13 22:03:42453 NetLog::StringCallback("source", &source));
[email protected]636eccd2011-06-28 12:28:01454 NotifyCanceled();
[email protected]b4438d32012-09-27 06:15:30455 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
[email protected]636eccd2011-06-28 12:28:01456 }
457}
458
459void URLRequestHttpJob::StartTransactionInternal() {
initial.commit586acc5fe2008-07-26 22:42:52460 // NOTE: This method assumes that request_info_ is already setup properly.
461
[email protected]34602282010-02-03 22:14:15462 // If we already have a transaction, then we should restart the transaction
[email protected]f3cf9802011-10-28 18:44:58463 // with auth provided by auth_credentials_.
initial.commit586acc5fe2008-07-26 22:42:52464
[email protected]99c07902010-08-17 18:59:52465 int rv;
[email protected]6b3f9642010-11-25 02:29:06466
[email protected]cc05edc2013-03-08 18:04:41467 if (network_delegate()) {
468 network_delegate()->NotifySendHeaders(
[email protected]5796dc942011-07-14 19:26:10469 request_, request_info_.extra_headers);
470 }
471
[email protected]34602282010-02-03 22:14:15472 if (transaction_.get()) {
[email protected]49639fa2011-12-20 23:22:41473 rv = transaction_->RestartWithAuth(auth_credentials_, start_callback_);
[email protected]f3cf9802011-10-28 18:44:58474 auth_credentials_ = AuthCredentials();
[email protected]34602282010-02-03 22:14:15475 } else {
[email protected]34602282010-02-03 22:14:15476 DCHECK(request_->context()->http_transaction_factory());
initial.commit586acc5fe2008-07-26 22:42:52477
[email protected]99c07902010-08-17 18:59:52478 rv = request_->context()->http_transaction_factory()->CreateTransaction(
[email protected]5033ab82013-03-22 20:17:46479 priority_, &transaction_, http_transaction_delegate_.get());
[email protected]4f5656c62010-12-13 10:47:09480 if (rv == OK) {
[email protected]a1d4ab072012-06-07 13:21:15481 if (!throttling_entry_ ||
482 !throttling_entry_->ShouldRejectRequest(*request_)) {
[email protected]227b0e82011-03-25 21:11:53483 rv = transaction_->Start(
[email protected]49639fa2011-12-20 23:22:41484 &request_info_, start_callback_, request_->net_log());
[email protected]bbaea8f2011-06-24 00:11:01485 start_time_ = base::TimeTicks::Now();
[email protected]227b0e82011-03-25 21:11:53486 } else {
487 // Special error code for the exponential back-off module.
488 rv = ERR_TEMPORARILY_THROTTLED;
489 }
[email protected]34602282010-02-03 22:14:15490 }
initial.commit586acc5fe2008-07-26 22:42:52491 }
492
[email protected]4f5656c62010-12-13 10:47:09493 if (rv == ERR_IO_PENDING)
[email protected]34602282010-02-03 22:14:15494 return;
495
initial.commit586acc5fe2008-07-26 22:42:52496 // The transaction started synchronously, but we need to notify the
[email protected]4f5656c62010-12-13 10:47:09497 // URLRequest delegate via the message loop.
[email protected]00e48bf2010-12-03 06:15:42498 MessageLoop::current()->PostTask(
499 FROM_HERE,
[email protected]098b29112011-12-20 21:12:34500 base::Bind(&URLRequestHttpJob::OnStartCompleted,
501 weak_factory_.GetWeakPtr(), rv));
initial.commit586acc5fe2008-07-26 22:42:52502}
503
[email protected]175adac2008-07-30 17:28:04504void URLRequestHttpJob::AddExtraHeaders() {
[email protected]c7bef94c2011-06-21 18:05:51505 // Supply Accept-Encoding field only if it is not already provided.
506 // It should be provided IF the content is known to have restrictions on
507 // potential encoding, such as streaming multi-media.
508 // For details see bug 47381.
509 // TODO(jar, enal): jpeg files etc. should set up a request header if
510 // possible. Right now it is done only by buffered_resource_loader and
511 // simple_data_source.
512 if (!request_info_.extra_headers.HasHeader(
513 HttpRequestHeaders::kAcceptEncoding)) {
514 bool advertise_sdch = SdchManager::Global() &&
515 SdchManager::Global()->IsInSupportedDomain(request_->url());
516 std::string avail_dictionaries;
517 if (advertise_sdch) {
518 SdchManager::Global()->GetAvailDictionaryList(request_->url(),
519 &avail_dictionaries);
[email protected]5b90b5d2009-04-30 23:06:01520
[email protected]c7bef94c2011-06-21 18:05:51521 // The AllowLatencyExperiment() is only true if we've successfully done a
522 // full SDCH compression recently in this browser session for this host.
523 // Note that for this path, there might be no applicable dictionaries,
524 // and hence we can't participate in the experiment.
525 if (!avail_dictionaries.empty() &&
526 SdchManager::Global()->AllowLatencyExperiment(request_->url())) {
527 // We are participating in the test (or control), and hence we'll
528 // eventually record statistics via either SDCH_EXPERIMENT_DECODE or
529 // SDCH_EXPERIMENT_HOLDBACK, and we'll need some packet timing data.
530 packet_timing_enabled_ = true;
531 if (base::RandDouble() < .01) {
532 sdch_test_control_ = true; // 1% probability.
533 advertise_sdch = false;
534 } else {
535 sdch_test_activated_ = true;
536 }
[email protected]5b90b5d2009-04-30 23:06:01537 }
538 }
[email protected]5b90b5d2009-04-30 23:06:01539
[email protected]c7bef94c2011-06-21 18:05:51540 // Supply Accept-Encoding headers first so that it is more likely that they
541 // will be in the first transmitted packet. This can sometimes make it
542 // easier to filter and analyze the streams to assure that a proxy has not
543 // damaged these headers. Some proxies deliberately corrupt Accept-Encoding
544 // headers.
545 if (!advertise_sdch) {
546 // Tell the server what compression formats we support (other than SDCH).
[email protected]8c76ae22010-04-20 22:15:43547 request_info_.extra_headers.SetHeader(
[email protected]c7bef94c2011-06-21 18:05:51548 HttpRequestHeaders::kAcceptEncoding, "gzip,deflate");
549 } else {
550 // Include SDCH in acceptable list.
551 request_info_.extra_headers.SetHeader(
552 HttpRequestHeaders::kAcceptEncoding, "gzip,deflate,sdch");
553 if (!avail_dictionaries.empty()) {
554 request_info_.extra_headers.SetHeader(
555 kAvailDictionaryHeader,
556 avail_dictionaries);
557 sdch_dictionary_advertised_ = true;
558 // Since we're tagging this transaction as advertising a dictionary,
559 // we'll definitely employ an SDCH filter (or tentative sdch filter)
560 // when we get a response. When done, we'll record histograms via
561 // SDCH_DECODE or SDCH_PASSTHROUGH. Hence we need to record packet
562 // arrival times.
563 packet_timing_enabled_ = true;
564 }
[email protected]423041b2008-10-27 17:39:28565 }
[email protected]423041b2008-10-27 17:39:28566 }
567
[email protected]ee4c30d2012-11-07 15:08:43568 if (http_user_agent_settings_) {
[email protected]84f05432013-03-15 01:00:12569 // Only add default Accept-Language if the request didn't have it
570 // specified.
[email protected]ee4c30d2012-11-07 15:08:43571 std::string accept_language =
572 http_user_agent_settings_->GetAcceptLanguage();
573 if (!accept_language.empty()) {
574 request_info_.extra_headers.SetHeaderIfMissing(
575 HttpRequestHeaders::kAcceptLanguage,
576 accept_language);
577 }
initial.commit586acc5fe2008-07-26 22:42:52578 }
initial.commit586acc5fe2008-07-26 22:42:52579}
580
[email protected]34602282010-02-03 22:14:15581void URLRequestHttpJob::AddCookieHeaderAndStart() {
582 // No matter what, we want to report our status as IO pending since we will
583 // be notifying our consumer asynchronously via OnStartCompleted.
584 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
[email protected]861fcd52009-08-26 02:33:46585
[email protected]ed24fad2011-05-10 22:44:01586 // If the request was destroyed, then there is no more work to do.
587 if (!request_)
588 return;
[email protected]34602282010-02-03 22:14:15589
[email protected]81293f482012-08-13 19:35:45590 CookieStore* cookie_store = request_->context()->cookie_store();
[email protected]1a6fff52011-10-20 21:00:16591 if (cookie_store && !(request_info_.load_flags & LOAD_DO_NOT_SEND_COOKIES)) {
592 net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
593 if (cookie_monster) {
594 cookie_monster->GetAllCookiesForURLAsync(
595 request_->url(),
596 base::Bind(&URLRequestHttpJob::CheckCookiePolicyAndLoad,
[email protected]098b29112011-12-20 21:12:34597 weak_factory_.GetWeakPtr()));
[email protected]1a6fff52011-10-20 21:00:16598 } else {
[email protected]cec80c3d2012-12-04 12:17:41599 CheckCookiePolicyAndLoad(CookieList());
[email protected]1a6fff52011-10-20 21:00:16600 }
[email protected]03d845f2011-07-29 19:06:26601 } else {
602 DoStartTransaction();
603 }
604}
605
[email protected]1a6fff52011-10-20 21:00:16606void URLRequestHttpJob::DoLoadCookies() {
607 CookieOptions options;
608 options.set_include_httponly();
[email protected]dedec0b2013-02-28 04:50:10609 request_->context()->cookie_store()->GetCookiesWithOptionsAsync(
[email protected]1a6fff52011-10-20 21:00:16610 request_->url(), options,
611 base::Bind(&URLRequestHttpJob::OnCookiesLoaded,
[email protected]098b29112011-12-20 21:12:34612 weak_factory_.GetWeakPtr()));
[email protected]1a6fff52011-10-20 21:00:16613}
614
[email protected]03d845f2011-07-29 19:06:26615void URLRequestHttpJob::CheckCookiePolicyAndLoad(
616 const CookieList& cookie_list) {
[email protected]1a6fff52011-10-20 21:00:16617 if (CanGetCookies(cookie_list))
618 DoLoadCookies();
619 else
[email protected]54f4c9362011-07-25 21:54:46620 DoStartTransaction();
[email protected]54f4c9362011-07-25 21:54:46621}
622
[email protected]dedec0b2013-02-28 04:50:10623void URLRequestHttpJob::OnCookiesLoaded(const std::string& cookie_line) {
[email protected]218aa6a12011-09-13 17:38:38624 if (!cookie_line.empty()) {
[email protected]54f4c9362011-07-25 21:54:46625 request_info_.extra_headers.SetHeader(
[email protected]218aa6a12011-09-13 17:38:38626 HttpRequestHeaders::kCookie, cookie_line);
[email protected]54f4c9362011-07-25 21:54:46627 }
[email protected]54f4c9362011-07-25 21:54:46628 DoStartTransaction();
629}
630
631void URLRequestHttpJob::DoStartTransaction() {
[email protected]03d845f2011-07-29 19:06:26632 // We may have been canceled while retrieving cookies.
[email protected]9025016c2011-05-12 15:51:23633 if (GetStatus().is_success()) {
634 StartTransaction();
635 } else {
636 NotifyCanceled();
637 }
[email protected]0757e7702009-03-27 04:00:22638}
639
[email protected]ea8141e2011-10-05 13:12:51640void URLRequestHttpJob::SaveCookiesAndNotifyHeadersComplete(int result) {
641 if (result != net::OK) {
[email protected]55b8a6c12012-06-13 22:03:42642 std::string source("delegate");
[email protected]ea8141e2011-10-05 13:12:51643 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
[email protected]55b8a6c12012-06-13 22:03:42644 NetLog::StringCallback("source", &source));
[email protected]ea8141e2011-10-05 13:12:51645 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
646 return;
647 }
648
[email protected]34602282010-02-03 22:14:15649 DCHECK(transaction_.get());
initial.commit586acc5fe2008-07-26 22:42:52650
[email protected]4f5656c62010-12-13 10:47:09651 const HttpResponseInfo* response_info = transaction_->GetResponseInfo();
[email protected]34602282010-02-03 22:14:15652 DCHECK(response_info);
653
654 response_cookies_.clear();
655 response_cookies_save_index_ = 0;
656
[email protected]ea8141e2011-10-05 13:12:51657 FetchResponseCookies(&response_cookies_);
[email protected]34602282010-02-03 22:14:15658
[email protected]5095cd72012-11-01 10:29:16659 if (!GetResponseHeaders()->GetDateValue(&response_date_))
660 response_date_ = base::Time();
661
[email protected]34602282010-02-03 22:14:15662 // Now, loop over the response cookies, and attempt to persist each.
663 SaveNextCookie();
664}
665
[email protected]263163f2012-06-14 22:40:34666// If the save occurs synchronously, SaveNextCookie will loop and save the next
667// cookie. If the save is deferred, the callback is responsible for continuing
668// to iterate through the cookies.
669// TODO(erikwright): Modify the CookieStore API to indicate via return value
670// whether it completed synchronously or asynchronously.
671// See http://crbug.com/131066.
[email protected]34602282010-02-03 22:14:15672void URLRequestHttpJob::SaveNextCookie() {
[email protected]263163f2012-06-14 22:40:34673 // No matter what, we want to report our status as IO pending since we will
674 // be notifying our consumer asynchronously via OnStartCompleted.
675 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
676
677 // Used to communicate with the callback. See the implementation of
678 // OnCookieSaved.
679 scoped_refptr<SharedBoolean> callback_pending = new SharedBoolean(false);
680 scoped_refptr<SharedBoolean> save_next_cookie_running =
681 new SharedBoolean(true);
682
683 if (!(request_info_.load_flags & LOAD_DO_NOT_SAVE_COOKIES) &&
684 request_->context()->cookie_store() &&
685 response_cookies_.size() > 0) {
686 CookieOptions options;
687 options.set_include_httponly();
[email protected]5095cd72012-11-01 10:29:16688 options.set_server_time(response_date_);
[email protected]263163f2012-06-14 22:40:34689
690 net::CookieStore::SetCookiesCallback callback(
691 base::Bind(&URLRequestHttpJob::OnCookieSaved,
692 weak_factory_.GetWeakPtr(),
693 save_next_cookie_running,
694 callback_pending));
695
696 // Loop through the cookies as long as SetCookieWithOptionsAsync completes
697 // synchronously.
698 while (!callback_pending->data &&
699 response_cookies_save_index_ < response_cookies_.size()) {
700 if (CanSetCookie(
701 response_cookies_[response_cookies_save_index_], &options)) {
702 callback_pending->data = true;
703 request_->context()->cookie_store()->SetCookieWithOptionsAsync(
704 request_->url(), response_cookies_[response_cookies_save_index_],
705 options, callback);
706 }
707 ++response_cookies_save_index_;
708 }
709 }
710
711 save_next_cookie_running->data = false;
712
713 if (!callback_pending->data) {
[email protected]34602282010-02-03 22:14:15714 response_cookies_.clear();
715 response_cookies_save_index_ = 0;
716 SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
717 NotifyHeadersComplete();
718 return;
719 }
[email protected]263163f2012-06-14 22:40:34720}
[email protected]34602282010-02-03 22:14:15721
[email protected]263163f2012-06-14 22:40:34722// |save_next_cookie_running| is true when the callback is bound and set to
723// false when SaveNextCookie exits, allowing the callback to determine if the
724// save occurred synchronously or asynchronously.
725// |callback_pending| is false when the callback is invoked and will be set to
726// true by the callback, allowing SaveNextCookie to detect whether the save
727// occurred synchronously.
728// See SaveNextCookie() for more information.
729void URLRequestHttpJob::OnCookieSaved(
730 scoped_refptr<SharedBoolean> save_next_cookie_running,
731 scoped_refptr<SharedBoolean> callback_pending,
732 bool cookie_status) {
733 callback_pending->data = false;
[email protected]34602282010-02-03 22:14:15734
[email protected]263163f2012-06-14 22:40:34735 // If we were called synchronously, return.
736 if (save_next_cookie_running->data) {
737 return;
[email protected]34602282010-02-03 22:14:15738 }
739
[email protected]263163f2012-06-14 22:40:34740 // We were called asynchronously, so trigger the next save.
[email protected]9025016c2011-05-12 15:51:23741 // We may have been canceled within OnSetCookie.
742 if (GetStatus().is_success()) {
743 SaveNextCookie();
744 } else {
745 NotifyCanceled();
746 }
[email protected]34602282010-02-03 22:14:15747}
748
749void URLRequestHttpJob::FetchResponseCookies(
[email protected]34602282010-02-03 22:14:15750 std::vector<std::string>* cookies) {
[email protected]264300242011-11-07 06:03:30751 const std::string name = "Set-Cookie";
initial.commit586acc5fe2008-07-26 22:42:52752 std::string value;
753
754 void* iter = NULL;
[email protected]ea8141e2011-10-05 13:12:51755 HttpResponseHeaders* headers = GetResponseHeaders();
756 while (headers->EnumerateHeader(&iter, name, &value)) {
[email protected]2adf2882010-09-27 08:30:37757 if (!value.empty())
758 cookies->push_back(value);
759 }
initial.commit586acc5fe2008-07-26 22:42:52760}
[email protected]a9cea7542009-05-20 04:30:23761
[email protected]000d9df02012-01-18 20:01:46762// NOTE: |ProcessStrictTransportSecurityHeader| and
763// |ProcessPublicKeyPinsHeader| have very similar structures, by design.
[email protected]77f6fb432009-09-05 14:21:09764void URLRequestHttpJob::ProcessStrictTransportSecurityHeader() {
[email protected]a9cea7542009-05-20 04:30:23765 DCHECK(response_info_);
[email protected]6ed72be2013-01-08 22:07:33766 TransportSecurityState* security_state =
767 request_->context()->transport_security_state();
[email protected]e88006f2012-01-11 06:15:07768 const SSLInfo& ssl_info = response_info_->ssl_info;
[email protected]a9cea7542009-05-20 04:30:23769
[email protected]6ed72be2013-01-08 22:07:33770 // Only accept HSTS headers on HTTPS connections that have no
771 // certificate errors.
[email protected]e88006f2012-01-11 06:15:07772 if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
[email protected]6ed72be2013-01-08 22:07:33773 !security_state)
[email protected]e88006f2012-01-11 06:15:07774 return;
[email protected]326e6792009-12-11 21:04:42775
[email protected]242d8562012-10-30 21:20:46776 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec:
777 //
778 // If a UA receives more than one STS header field in a HTTP response
779 // message over secure transport, then the UA MUST process only the
780 // first such header field.
[email protected]6ed72be2013-01-08 22:07:33781 HttpResponseHeaders* headers = GetResponseHeaders();
782 std::string value;
783 if (headers->EnumerateHeader(NULL, "Strict-Transport-Security", &value))
784 security_state->AddHSTSHeader(request_info_.url.host(), value);
[email protected]a9cea7542009-05-20 04:30:23785}
[email protected]4f5656c62010-12-13 10:47:09786
[email protected]fecef222012-01-05 02:26:15787void URLRequestHttpJob::ProcessPublicKeyPinsHeader() {
788 DCHECK(response_info_);
[email protected]6ed72be2013-01-08 22:07:33789 TransportSecurityState* security_state =
790 request_->context()->transport_security_state();
[email protected]fecef222012-01-05 02:26:15791 const SSLInfo& ssl_info = response_info_->ssl_info;
792
[email protected]6ed72be2013-01-08 22:07:33793 // Only accept HPKP headers on HTTPS connections that have no
[email protected]e88006f2012-01-11 06:15:07794 // certificate errors.
[email protected]fecef222012-01-05 02:26:15795 if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status) ||
[email protected]6ed72be2013-01-08 22:07:33796 !security_state)
[email protected]fecef222012-01-05 02:26:15797 return;
[email protected]fecef222012-01-05 02:26:15798
[email protected]6ed72be2013-01-08 22:07:33799 // http://tools.ietf.org/html/draft-ietf-websec-key-pinning:
800 //
801 // If a UA receives more than one PKP header field in an HTTP
802 // response message over secure transport, then the UA MUST process
803 // only the first such header field.
[email protected]fecef222012-01-05 02:26:15804 HttpResponseHeaders* headers = GetResponseHeaders();
[email protected]fecef222012-01-05 02:26:15805 std::string value;
[email protected]6ed72be2013-01-08 22:07:33806 if (headers->EnumerateHeader(NULL, "Public-Key-Pins", &value))
807 security_state->AddHPKPHeader(request_info_.url.host(), value, ssl_info);
[email protected]fecef222012-01-05 02:26:15808}
809
[email protected]5394e422011-01-20 22:07:43810void URLRequestHttpJob::OnStartCompleted(int result) {
[email protected]ec23f522011-02-22 21:01:38811 RecordTimer();
812
[email protected]5394e422011-01-20 22:07:43813 // If the request was destroyed, then there is no more work to do.
[email protected]a83dd332011-07-13 10:41:01814 if (!request_)
[email protected]5394e422011-01-20 22:07:43815 return;
816
817 // If the transaction was destroyed, then the job was cancelled, and
818 // we can just ignore this notification.
819 if (!transaction_.get())
820 return;
821
822 // Clear the IO_PENDING status
823 SetStatus(URLRequestStatus());
824
[email protected]ef2bf422012-05-11 03:27:09825 const URLRequestContext* context = request_->context();
826
[email protected]f3572592011-12-12 21:36:31827 if (result == ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN &&
828 transaction_->GetResponseInfo() != NULL) {
829 FraudulentCertificateReporter* reporter =
[email protected]ef2bf422012-05-11 03:27:09830 context->fraudulent_certificate_reporter();
[email protected]f3572592011-12-12 21:36:31831 if (reporter != NULL) {
832 const SSLInfo& ssl_info = transaction_->GetResponseInfo()->ssl_info;
[email protected]551ff5172011-11-10 18:35:31833 bool sni_available = SSLConfigService::IsSNIAvailable(
[email protected]ef2bf422012-05-11 03:27:09834 context->ssl_config_service());
[email protected]f3572592011-12-12 21:36:31835 const std::string& host = request_->url().host();
[email protected]b7996452011-10-31 19:30:56836
[email protected]f3572592011-12-12 21:36:31837 reporter->SendReport(host, ssl_info, sni_available);
[email protected]381e8852011-04-14 14:30:58838 }
839 }
[email protected]551ff5172011-11-10 18:35:31840
[email protected]5394e422011-01-20 22:07:43841 if (result == OK) {
[email protected]ea8141e2011-10-05 13:12:51842 scoped_refptr<HttpResponseHeaders> headers = GetResponseHeaders();
[email protected]cc05edc2013-03-08 18:04:41843 if (network_delegate()) {
[email protected]ea8141e2011-10-05 13:12:51844 // Note that |this| may not be deleted until
845 // |on_headers_received_callback_| or
846 // |NetworkDelegate::URLRequestDestroyed()| has been called.
[email protected]cc05edc2013-03-08 18:04:41847 int error = network_delegate()->NotifyHeadersReceived(
848 request_, on_headers_received_callback_,
849 headers, &override_response_headers_);
[email protected]ea8141e2011-10-05 13:12:51850 if (error != net::OK) {
851 if (error == net::ERR_IO_PENDING) {
852 awaiting_callback_ = true;
[email protected]0a12e452012-11-14 05:04:30853 SetBlockedOnDelegate();
[email protected]ea8141e2011-10-05 13:12:51854 } else {
[email protected]55b8a6c12012-06-13 22:03:42855 std::string source("delegate");
[email protected]ea8141e2011-10-05 13:12:51856 request_->net_log().AddEvent(NetLog::TYPE_CANCELLED,
[email protected]55b8a6c12012-06-13 22:03:42857 NetLog::StringCallback("source",
858 &source));
[email protected]ea8141e2011-10-05 13:12:51859 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, error));
860 }
861 return;
862 }
863 }
864
865 SaveCookiesAndNotifyHeadersComplete(net::OK);
[email protected]e5624f02011-09-27 19:43:53866 } else if (IsCertificateError(result)) {
[email protected]5394e422011-01-20 22:07:43867 // We encountered an SSL certificate error. Ask our delegate to decide
868 // what we should do.
[email protected]e5624f02011-09-27 19:43:53869
870 TransportSecurityState::DomainState domain_state;
[email protected]ef2bf422012-05-11 03:27:09871 const URLRequestContext* context = request_->context();
[email protected]843329e2013-01-22 22:06:09872 const bool fatal = context->transport_security_state() &&
[email protected]ef2bf422012-05-11 03:27:09873 context->transport_security_state()->GetDomainState(
[email protected]f43b89f32012-05-01 19:39:48874 request_info_.url.host(),
[email protected]ef2bf422012-05-11 03:27:09875 SSLConfigService::IsSNIAvailable(context->ssl_config_service()),
[email protected]843329e2013-01-22 22:06:09876 &domain_state) &&
877 domain_state.ShouldSSLErrorsBeFatal();
[email protected]46d117e2012-01-18 01:53:14878 NotifySSLCertificateError(transaction_->GetResponseInfo()->ssl_info, fatal);
[email protected]5394e422011-01-20 22:07:43879 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
[email protected]a83dd332011-07-13 10:41:01880 NotifyCertificateRequested(
881 transaction_->GetResponseInfo()->cert_request_info);
[email protected]5394e422011-01-20 22:07:43882 } else {
883 NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
884 }
885}
886
[email protected]ea8141e2011-10-05 13:12:51887void URLRequestHttpJob::OnHeadersReceivedCallback(int result) {
[email protected]0a12e452012-11-14 05:04:30888 SetUnblockedOnDelegate();
[email protected]ea8141e2011-10-05 13:12:51889 awaiting_callback_ = false;
[email protected]9045b8822012-01-13 20:35:35890
891 // Check that there are no callbacks to already canceled requests.
892 DCHECK_NE(URLRequestStatus::CANCELED, GetStatus().status());
893
[email protected]ea8141e2011-10-05 13:12:51894 SaveCookiesAndNotifyHeadersComplete(result);
895}
896
[email protected]5394e422011-01-20 22:07:43897void URLRequestHttpJob::OnReadCompleted(int result) {
898 read_in_progress_ = false;
899
[email protected]f001bd6a2011-12-08 04:31:37900 if (ShouldFixMismatchedContentLength(result))
[email protected]5543cbb2012-04-20 16:35:23901 result = OK;
[email protected]f001bd6a2011-12-08 04:31:37902
[email protected]5543cbb2012-04-20 16:35:23903 if (result == OK) {
[email protected]5394e422011-01-20 22:07:43904 NotifyDone(URLRequestStatus());
905 } else if (result < 0) {
906 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, result));
907 } else {
908 // Clear the IO_PENDING status
909 SetStatus(URLRequestStatus());
910 }
911
912 NotifyReadComplete(result);
913}
914
[email protected]5394e422011-01-20 22:07:43915void URLRequestHttpJob::RestartTransactionWithAuth(
[email protected]f3cf9802011-10-28 18:44:58916 const AuthCredentials& credentials) {
917 auth_credentials_ = credentials;
[email protected]5394e422011-01-20 22:07:43918
919 // These will be reset in OnStartCompleted.
920 response_info_ = NULL;
921 response_cookies_.clear();
922
[email protected]ec23f522011-02-22 21:01:38923 ResetTimer();
924
[email protected]5394e422011-01-20 22:07:43925 // Update the cookies, since the cookie store may have been updated from the
926 // headers in the 401/407. Since cookies were already appended to
927 // extra_headers, we need to strip them out before adding them again.
[email protected]ea8141e2011-10-05 13:12:51928 request_info_.extra_headers.RemoveHeader(HttpRequestHeaders::kCookie);
[email protected]5394e422011-01-20 22:07:43929
930 AddCookieHeaderAndStart();
931}
932
[email protected]0736d9e2012-11-28 19:50:40933void URLRequestHttpJob::SetUpload(UploadDataStream* upload) {
[email protected]5394e422011-01-20 22:07:43934 DCHECK(!transaction_.get()) << "cannot change once started";
[email protected]0736d9e2012-11-28 19:50:40935 request_info_.upload_data_stream = upload;
[email protected]5394e422011-01-20 22:07:43936}
937
938void URLRequestHttpJob::SetExtraRequestHeaders(
939 const HttpRequestHeaders& headers) {
940 DCHECK(!transaction_.get()) << "cannot change once started";
941 request_info_.extra_headers.CopyFrom(headers);
942}
943
[email protected]5394e422011-01-20 22:07:43944LoadState URLRequestHttpJob::GetLoadState() const {
945 return transaction_.get() ?
946 transaction_->GetLoadState() : LOAD_STATE_IDLE;
947}
948
[email protected]7335ab02012-08-30 22:30:42949UploadProgress URLRequestHttpJob::GetUploadProgress() const {
950 return transaction_.get() ?
951 transaction_->GetUploadProgress() : UploadProgress();
[email protected]5394e422011-01-20 22:07:43952}
953
954bool URLRequestHttpJob::GetMimeType(std::string* mime_type) const {
955 DCHECK(transaction_.get());
956
957 if (!response_info_)
958 return false;
959
[email protected]ea8141e2011-10-05 13:12:51960 return GetResponseHeaders()->GetMimeType(mime_type);
[email protected]5394e422011-01-20 22:07:43961}
962
963bool URLRequestHttpJob::GetCharset(std::string* charset) {
964 DCHECK(transaction_.get());
965
966 if (!response_info_)
967 return false;
968
[email protected]ea8141e2011-10-05 13:12:51969 return GetResponseHeaders()->GetCharset(charset);
[email protected]5394e422011-01-20 22:07:43970}
971
972void URLRequestHttpJob::GetResponseInfo(HttpResponseInfo* info) {
973 DCHECK(request_);
974 DCHECK(transaction_.get());
975
[email protected]ea8141e2011-10-05 13:12:51976 if (response_info_) {
[email protected]5394e422011-01-20 22:07:43977 *info = *response_info_;
[email protected]ea8141e2011-10-05 13:12:51978 if (override_response_headers_)
979 info->headers = override_response_headers_;
980 }
[email protected]5394e422011-01-20 22:07:43981}
982
[email protected]58e32bb2013-01-21 18:23:25983void URLRequestHttpJob::GetLoadTimingInfo(
984 LoadTimingInfo* load_timing_info) const {
985 if (transaction_)
986 transaction_->GetLoadTimingInfo(load_timing_info);
987}
988
[email protected]ea8141e2011-10-05 13:12:51989bool URLRequestHttpJob::GetResponseCookies(std::vector<std::string>* cookies) {
[email protected]5394e422011-01-20 22:07:43990 DCHECK(transaction_.get());
991
992 if (!response_info_)
993 return false;
994
995 // TODO(darin): Why are we extracting response cookies again? Perhaps we
996 // should just leverage response_cookies_.
997
998 cookies->clear();
[email protected]ea8141e2011-10-05 13:12:51999 FetchResponseCookies(cookies);
[email protected]5394e422011-01-20 22:07:431000 return true;
1001}
1002
1003int URLRequestHttpJob::GetResponseCode() const {
1004 DCHECK(transaction_.get());
1005
1006 if (!response_info_)
1007 return -1;
1008
[email protected]ea8141e2011-10-05 13:12:511009 return GetResponseHeaders()->response_code();
[email protected]5394e422011-01-20 22:07:431010}
1011
[email protected]5a3b4d32011-03-17 01:24:051012Filter* URLRequestHttpJob::SetupFilter() const {
[email protected]5394e422011-01-20 22:07:431013 DCHECK(transaction_.get());
1014 if (!response_info_)
[email protected]5a3b4d32011-03-17 01:24:051015 return NULL;
[email protected]5394e422011-01-20 22:07:431016
[email protected]5a3b4d32011-03-17 01:24:051017 std::vector<Filter::FilterType> encoding_types;
[email protected]5394e422011-01-20 22:07:431018 std::string encoding_type;
[email protected]ea8141e2011-10-05 13:12:511019 HttpResponseHeaders* headers = GetResponseHeaders();
[email protected]5394e422011-01-20 22:07:431020 void* iter = NULL;
[email protected]ea8141e2011-10-05 13:12:511021 while (headers->EnumerateHeader(&iter, "Content-Encoding", &encoding_type)) {
[email protected]5a3b4d32011-03-17 01:24:051022 encoding_types.push_back(Filter::ConvertEncodingToType(encoding_type));
[email protected]5394e422011-01-20 22:07:431023 }
1024
[email protected]46668fe52011-05-04 19:03:231025 if (filter_context_->IsSdchResponse()) {
1026 // We are wary of proxies that discard or damage SDCH encoding. If a server
1027 // explicitly states that this is not SDCH content, then we can correct our
1028 // assumption that this is an SDCH response, and avoid the need to recover
1029 // as though the content is corrupted (when we discover it is not SDCH
1030 // encoded).
1031 std::string sdch_response_status;
1032 iter = NULL;
[email protected]ea8141e2011-10-05 13:12:511033 while (headers->EnumerateHeader(&iter, "X-Sdch-Encode",
1034 &sdch_response_status)) {
[email protected]46668fe52011-05-04 19:03:231035 if (sdch_response_status == "0") {
1036 filter_context_->ResetSdchResponseToFalse();
1037 break;
1038 }
1039 }
1040 }
1041
[email protected]5394e422011-01-20 22:07:431042 // Even if encoding types are empty, there is a chance that we need to add
1043 // some decoding, as some proxies strip encoding completely. In such cases,
1044 // we may need to add (for example) SDCH filtering (when the context suggests
1045 // it is appropriate).
[email protected]2e92354c2011-03-25 20:49:531046 Filter::FixupEncodingTypes(*filter_context_, &encoding_types);
[email protected]5394e422011-01-20 22:07:431047
[email protected]5a3b4d32011-03-17 01:24:051048 return !encoding_types.empty()
[email protected]2e92354c2011-03-25 20:49:531049 ? Filter::Factory(encoding_types, *filter_context_) : NULL;
[email protected]5394e422011-01-20 22:07:431050}
1051
[email protected]5394e422011-01-20 22:07:431052bool URLRequestHttpJob::IsSafeRedirect(const GURL& location) {
[email protected]e13c1462013-03-19 03:05:501053 // We only allow redirects to certain "safe" protocols. This does not
1054 // restrict redirects to externally handled protocols. Our consumer would
1055 // need to take care of those.
1056
1057 if (!URLRequest::IsHandledURL(location))
[email protected]5394e422011-01-20 22:07:431058 return true;
[email protected]e13c1462013-03-19 03:05:501059
1060 static const char* kSafeSchemes[] = {
1061 "http",
1062 "https",
1063 "ftp"
1064 };
1065
1066 for (size_t i = 0; i < arraysize(kSafeSchemes); ++i) {
1067 if (location.SchemeIs(kSafeSchemes[i]))
1068 return true;
[email protected]5394e422011-01-20 22:07:431069 }
[email protected]e13c1462013-03-19 03:05:501070
1071 return false;
[email protected]5394e422011-01-20 22:07:431072}
1073
1074bool URLRequestHttpJob::NeedsAuth() {
1075 int code = GetResponseCode();
1076 if (code == -1)
1077 return false;
1078
1079 // Check if we need either Proxy or WWW Authentication. This could happen
1080 // because we either provided no auth info, or provided incorrect info.
1081 switch (code) {
1082 case 407:
1083 if (proxy_auth_state_ == AUTH_STATE_CANCELED)
1084 return false;
1085 proxy_auth_state_ = AUTH_STATE_NEED_AUTH;
1086 return true;
1087 case 401:
1088 if (server_auth_state_ == AUTH_STATE_CANCELED)
1089 return false;
1090 server_auth_state_ = AUTH_STATE_NEED_AUTH;
1091 return true;
1092 }
1093 return false;
1094}
1095
1096void URLRequestHttpJob::GetAuthChallengeInfo(
1097 scoped_refptr<AuthChallengeInfo>* result) {
1098 DCHECK(transaction_.get());
1099 DCHECK(response_info_);
1100
1101 // sanity checks:
1102 DCHECK(proxy_auth_state_ == AUTH_STATE_NEED_AUTH ||
1103 server_auth_state_ == AUTH_STATE_NEED_AUTH);
[email protected]9094b602012-02-27 21:44:581104 DCHECK((GetResponseHeaders()->response_code() == HTTP_UNAUTHORIZED) ||
1105 (GetResponseHeaders()->response_code() ==
1106 HTTP_PROXY_AUTHENTICATION_REQUIRED));
[email protected]5394e422011-01-20 22:07:431107
1108 *result = response_info_->auth_challenge;
1109}
1110
[email protected]f3cf9802011-10-28 18:44:581111void URLRequestHttpJob::SetAuth(const AuthCredentials& credentials) {
[email protected]5394e422011-01-20 22:07:431112 DCHECK(transaction_.get());
1113
1114 // Proxy gets set first, then WWW.
1115 if (proxy_auth_state_ == AUTH_STATE_NEED_AUTH) {
1116 proxy_auth_state_ = AUTH_STATE_HAVE_AUTH;
1117 } else {
[email protected]dd29bcd72011-03-24 00:03:441118 DCHECK_EQ(server_auth_state_, AUTH_STATE_NEED_AUTH);
[email protected]5394e422011-01-20 22:07:431119 server_auth_state_ = AUTH_STATE_HAVE_AUTH;
1120 }
1121
[email protected]f3cf9802011-10-28 18:44:581122 RestartTransactionWithAuth(credentials);
[email protected]5394e422011-01-20 22:07:431123}
1124
1125void URLRequestHttpJob::CancelAuth() {
1126 // Proxy gets set first, then WWW.
1127 if (proxy_auth_state_ == AUTH_STATE_NEED_AUTH) {
1128 proxy_auth_state_ = AUTH_STATE_CANCELED;
1129 } else {
[email protected]dd29bcd72011-03-24 00:03:441130 DCHECK_EQ(server_auth_state_, AUTH_STATE_NEED_AUTH);
[email protected]5394e422011-01-20 22:07:431131 server_auth_state_ = AUTH_STATE_CANCELED;
1132 }
1133
1134 // These will be reset in OnStartCompleted.
1135 response_info_ = NULL;
1136 response_cookies_.clear();
1137
[email protected]ec23f522011-02-22 21:01:381138 ResetTimer();
1139
[email protected]5394e422011-01-20 22:07:431140 // OK, let the consumer read the error page...
1141 //
1142 // Because we set the AUTH_STATE_CANCELED flag, NeedsAuth will return false,
1143 // which will cause the consumer to receive OnResponseStarted instead of
1144 // OnAuthRequired.
1145 //
1146 // We have to do this via InvokeLater to avoid "recursing" the consumer.
1147 //
1148 MessageLoop::current()->PostTask(
1149 FROM_HERE,
[email protected]098b29112011-12-20 21:12:341150 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1151 weak_factory_.GetWeakPtr(), OK));
[email protected]5394e422011-01-20 22:07:431152}
1153
1154void URLRequestHttpJob::ContinueWithCertificate(
1155 X509Certificate* client_cert) {
1156 DCHECK(transaction_.get());
1157
1158 DCHECK(!response_info_) << "should not have a response yet";
1159
[email protected]ec23f522011-02-22 21:01:381160 ResetTimer();
1161
[email protected]5394e422011-01-20 22:07:431162 // No matter what, we want to report our status as IO pending since we will
1163 // be notifying our consumer asynchronously via OnStartCompleted.
1164 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1165
[email protected]49639fa2011-12-20 23:22:411166 int rv = transaction_->RestartWithCertificate(client_cert, start_callback_);
[email protected]5394e422011-01-20 22:07:431167 if (rv == ERR_IO_PENDING)
1168 return;
1169
1170 // The transaction started synchronously, but we need to notify the
1171 // URLRequest delegate via the message loop.
1172 MessageLoop::current()->PostTask(
1173 FROM_HERE,
[email protected]098b29112011-12-20 21:12:341174 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1175 weak_factory_.GetWeakPtr(), rv));
[email protected]5394e422011-01-20 22:07:431176}
1177
1178void URLRequestHttpJob::ContinueDespiteLastError() {
1179 // If the transaction was destroyed, then the job was cancelled.
1180 if (!transaction_.get())
1181 return;
1182
1183 DCHECK(!response_info_) << "should not have a response yet";
1184
[email protected]ec23f522011-02-22 21:01:381185 ResetTimer();
1186
[email protected]5394e422011-01-20 22:07:431187 // No matter what, we want to report our status as IO pending since we will
1188 // be notifying our consumer asynchronously via OnStartCompleted.
1189 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1190
[email protected]49639fa2011-12-20 23:22:411191 int rv = transaction_->RestartIgnoringLastError(start_callback_);
[email protected]5394e422011-01-20 22:07:431192 if (rv == ERR_IO_PENDING)
1193 return;
1194
1195 // The transaction started synchronously, but we need to notify the
1196 // URLRequest delegate via the message loop.
1197 MessageLoop::current()->PostTask(
1198 FROM_HERE,
[email protected]098b29112011-12-20 21:12:341199 base::Bind(&URLRequestHttpJob::OnStartCompleted,
1200 weak_factory_.GetWeakPtr(), rv));
[email protected]5394e422011-01-20 22:07:431201}
1202
[email protected]f001bd6a2011-12-08 04:31:371203bool URLRequestHttpJob::ShouldFixMismatchedContentLength(int rv) const {
1204 // Some servers send the body compressed, but specify the content length as
1205 // the uncompressed size. Although this violates the HTTP spec we want to
1206 // support it (as IE and FireFox do), but *only* for an exact match.
1207 // See http://crbug.com/79694.
[email protected]5543cbb2012-04-20 16:35:231208 if (rv == net::ERR_CONTENT_LENGTH_MISMATCH ||
1209 rv == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
[email protected]f001bd6a2011-12-08 04:31:371210 if (request_ && request_->response_headers()) {
1211 int64 expected_length = request_->response_headers()->GetContentLength();
1212 VLOG(1) << __FUNCTION__ << "() "
1213 << "\"" << request_->url().spec() << "\""
1214 << " content-length = " << expected_length
1215 << " pre total = " << prefilter_bytes_read()
1216 << " post total = " << postfilter_bytes_read();
1217 if (postfilter_bytes_read() == expected_length) {
1218 // Clear the error.
1219 return true;
1220 }
1221 }
1222 }
1223 return false;
1224}
1225
[email protected]5394e422011-01-20 22:07:431226bool URLRequestHttpJob::ReadRawData(IOBuffer* buf, int buf_size,
[email protected]b7996452011-10-31 19:30:561227 int* bytes_read) {
[email protected]5394e422011-01-20 22:07:431228 DCHECK_NE(buf_size, 0);
1229 DCHECK(bytes_read);
1230 DCHECK(!read_in_progress_);
1231
[email protected]49639fa2011-12-20 23:22:411232 int rv = transaction_->Read(
1233 buf, buf_size,
1234 base::Bind(&URLRequestHttpJob::OnReadCompleted, base::Unretained(this)));
[email protected]85c1dce2011-07-06 12:01:291235
[email protected]f001bd6a2011-12-08 04:31:371236 if (ShouldFixMismatchedContentLength(rv))
1237 rv = 0;
1238
[email protected]5394e422011-01-20 22:07:431239 if (rv >= 0) {
1240 *bytes_read = rv;
[email protected]bbaea8f2011-06-24 00:11:011241 if (!rv)
1242 DoneWithRequest(FINISHED);
[email protected]5394e422011-01-20 22:07:431243 return true;
1244 }
1245
1246 if (rv == ERR_IO_PENDING) {
1247 read_in_progress_ = true;
1248 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
1249 } else {
1250 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, rv));
1251 }
1252
1253 return false;
1254}
1255
1256void URLRequestHttpJob::StopCaching() {
1257 if (transaction_.get())
1258 transaction_->StopCaching();
1259}
1260
[email protected]5c04f722011-08-12 17:52:471261void URLRequestHttpJob::DoneReading() {
1262 if (transaction_.get())
1263 transaction_->DoneReading();
1264 DoneWithRequest(FINISHED);
1265}
1266
[email protected]6d81b482011-02-22 19:47:191267HostPortPair URLRequestHttpJob::GetSocketAddress() const {
1268 return response_info_ ? response_info_->socket_address : HostPortPair();
1269}
1270
[email protected]ec23f522011-02-22 21:01:381271void URLRequestHttpJob::RecordTimer() {
1272 if (request_creation_time_.is_null()) {
1273 NOTREACHED()
1274 << "The same transaction shouldn't start twice without new timing.";
1275 return;
1276 }
1277
[email protected]320a29f12011-03-21 14:47:411278 base::TimeDelta to_start = base::Time::Now() - request_creation_time_;
[email protected]ec23f522011-02-22 21:01:381279 request_creation_time_ = base::Time();
[email protected]8684a8812011-03-22 13:59:381280
[email protected]5c68d692011-08-24 04:59:411281 UMA_HISTOGRAM_MEDIUM_TIMES("Net.HttpTimeToFirstByte", to_start);
1282
[email protected]135c126a2012-10-31 15:39:251283 static const bool use_overlapped_read_histogram =
1284 base::FieldTrialList::TrialExists("OverlappedReadImpact");
1285 if (use_overlapped_read_histogram) {
1286 UMA_HISTOGRAM_MEDIUM_TIMES(
1287 base::FieldTrial::MakeName("Net.HttpTimeToFirstByte",
1288 "OverlappedReadImpact"),
1289 to_start);
1290 }
1291
[email protected]5c68d692011-08-24 04:59:411292 static const bool use_warm_socket_impact_histogram =
1293 base::FieldTrialList::TrialExists("WarmSocketImpact");
1294 if (use_warm_socket_impact_histogram) {
1295 UMA_HISTOGRAM_MEDIUM_TIMES(
1296 base::FieldTrial::MakeName("Net.HttpTimeToFirstByte",
1297 "WarmSocketImpact"),
1298 to_start);
1299 }
1300
[email protected]ce0a5a92011-12-27 19:56:141301 static const bool use_prefetch_histogram =
1302 base::FieldTrialList::TrialExists("Prefetch");
1303 if (use_prefetch_histogram) {
1304 UMA_HISTOGRAM_MEDIUM_TIMES(
1305 base::FieldTrial::MakeName("Net.HttpTimeToFirstByte",
1306 "Prefetch"),
1307 to_start);
1308 }
[email protected]ca17f372011-12-27 17:44:431309 static const bool use_prerender_histogram =
1310 base::FieldTrialList::TrialExists("Prerender");
1311 if (use_prerender_histogram) {
[email protected]8684a8812011-03-22 13:59:381312 UMA_HISTOGRAM_MEDIUM_TIMES(
1313 base::FieldTrial::MakeName("Net.HttpTimeToFirstByte",
[email protected]ca17f372011-12-27 17:44:431314 "Prerender"),
[email protected]8684a8812011-03-22 13:59:381315 to_start);
1316 }
[email protected]ec23f522011-02-22 21:01:381317}
1318
1319void URLRequestHttpJob::ResetTimer() {
1320 if (!request_creation_time_.is_null()) {
1321 NOTREACHED()
1322 << "The timer was reset before it was recorded.";
1323 return;
1324 }
1325 request_creation_time_ = base::Time::Now();
1326}
1327
[email protected]dd29bcd72011-03-24 00:03:441328void URLRequestHttpJob::UpdatePacketReadTimes() {
1329 if (!packet_timing_enabled_)
1330 return;
1331
1332 if (filter_input_byte_count() <= bytes_observed_in_packets_) {
1333 DCHECK_EQ(filter_input_byte_count(), bytes_observed_in_packets_);
1334 return; // No new bytes have arrived.
1335 }
1336
[email protected]d6b55392011-08-05 04:04:351337 final_packet_time_ = base::Time::Now();
[email protected]dd29bcd72011-03-24 00:03:441338 if (!bytes_observed_in_packets_)
1339 request_time_snapshot_ = request_ ? request_->request_time() : base::Time();
1340
[email protected]dd29bcd72011-03-24 00:03:441341 bytes_observed_in_packets_ = filter_input_byte_count();
1342}
1343
1344void URLRequestHttpJob::RecordPacketStats(
1345 FilterContext::StatisticSelector statistic) const {
1346 if (!packet_timing_enabled_ || (final_packet_time_ == base::Time()))
1347 return;
1348
1349 base::TimeDelta duration = final_packet_time_ - request_time_snapshot_;
1350 switch (statistic) {
1351 case FilterContext::SDCH_DECODE: {
[email protected]dd29bcd72011-03-24 00:03:441352 UMA_HISTOGRAM_CUSTOM_COUNTS("Sdch3.Network_Decode_Bytes_Processed_b",
1353 static_cast<int>(bytes_observed_in_packets_), 500, 100000, 100);
[email protected]dd29bcd72011-03-24 00:03:441354 return;
1355 }
1356 case FilterContext::SDCH_PASSTHROUGH: {
1357 // Despite advertising a dictionary, we handled non-sdch compressed
1358 // content.
[email protected]dd29bcd72011-03-24 00:03:441359 return;
1360 }
1361
1362 case FilterContext::SDCH_EXPERIMENT_DECODE: {
[email protected]d6b55392011-08-05 04:04:351363 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment2_Decode",
[email protected]dd29bcd72011-03-24 00:03:441364 duration,
1365 base::TimeDelta::FromMilliseconds(20),
1366 base::TimeDelta::FromMinutes(10), 100);
[email protected]dd29bcd72011-03-24 00:03:441367 return;
1368 }
1369 case FilterContext::SDCH_EXPERIMENT_HOLDBACK: {
[email protected]d6b55392011-08-05 04:04:351370 UMA_HISTOGRAM_CUSTOM_TIMES("Sdch3.Experiment2_Holdback",
[email protected]dd29bcd72011-03-24 00:03:441371 duration,
1372 base::TimeDelta::FromMilliseconds(20),
1373 base::TimeDelta::FromMinutes(10), 100);
[email protected]dd29bcd72011-03-24 00:03:441374 return;
1375 }
1376 default:
1377 NOTREACHED();
1378 return;
1379 }
1380}
1381
1382// The common type of histogram we use for all compression-tracking histograms.
1383#define COMPRESSION_HISTOGRAM(name, sample) \
1384 do { \
1385 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.Compress." name, sample, \
1386 500, 1000000, 100); \
[email protected]b7996452011-10-31 19:30:561387 } while (0)
[email protected]dd29bcd72011-03-24 00:03:441388
1389void URLRequestHttpJob::RecordCompressionHistograms() {
1390 DCHECK(request_);
1391 if (!request_)
1392 return;
1393
1394 if (is_cached_content_ || // Don't record cached content
1395 !GetStatus().is_success() || // Don't record failed content
1396 !IsCompressibleContent() || // Only record compressible content
1397 !prefilter_bytes_read()) // Zero-byte responses aren't useful.
1398 return;
1399
1400 // Miniature requests aren't really compressible. Don't count them.
1401 const int kMinSize = 16;
1402 if (prefilter_bytes_read() < kMinSize)
1403 return;
1404
1405 // Only record for http or https urls.
1406 bool is_http = request_->url().SchemeIs("http");
1407 bool is_https = request_->url().SchemeIs("https");
1408 if (!is_http && !is_https)
1409 return;
1410
1411 int compressed_B = prefilter_bytes_read();
1412 int decompressed_B = postfilter_bytes_read();
1413 bool was_filtered = HasFilter();
1414
1415 // We want to record how often downloaded resources are compressed.
1416 // But, we recognize that different protocols may have different
1417 // properties. So, for each request, we'll put it into one of 3
1418 // groups:
1419 // a) SSL resources
1420 // Proxies cannot tamper with compression headers with SSL.
1421 // b) Non-SSL, loaded-via-proxy resources
1422 // In this case, we know a proxy might have interfered.
1423 // c) Non-SSL, loaded-without-proxy resources
1424 // In this case, we know there was no explicit proxy. However,
1425 // it is possible that a transparent proxy was still interfering.
1426 //
1427 // For each group, we record the same 3 histograms.
1428
1429 if (is_https) {
1430 if (was_filtered) {
1431 COMPRESSION_HISTOGRAM("SSL.BytesBeforeCompression", compressed_B);
1432 COMPRESSION_HISTOGRAM("SSL.BytesAfterCompression", decompressed_B);
1433 } else {
1434 COMPRESSION_HISTOGRAM("SSL.ShouldHaveBeenCompressed", decompressed_B);
1435 }
1436 return;
1437 }
1438
1439 if (request_->was_fetched_via_proxy()) {
1440 if (was_filtered) {
1441 COMPRESSION_HISTOGRAM("Proxy.BytesBeforeCompression", compressed_B);
1442 COMPRESSION_HISTOGRAM("Proxy.BytesAfterCompression", decompressed_B);
1443 } else {
1444 COMPRESSION_HISTOGRAM("Proxy.ShouldHaveBeenCompressed", decompressed_B);
1445 }
1446 return;
1447 }
1448
1449 if (was_filtered) {
1450 COMPRESSION_HISTOGRAM("NoProxy.BytesBeforeCompression", compressed_B);
1451 COMPRESSION_HISTOGRAM("NoProxy.BytesAfterCompression", decompressed_B);
1452 } else {
1453 COMPRESSION_HISTOGRAM("NoProxy.ShouldHaveBeenCompressed", decompressed_B);
1454 }
1455}
1456
1457bool URLRequestHttpJob::IsCompressibleContent() const {
1458 std::string mime_type;
1459 return GetMimeType(&mime_type) &&
1460 (IsSupportedJavascriptMimeType(mime_type.c_str()) ||
1461 IsSupportedNonImageMimeType(mime_type.c_str()));
1462}
1463
[email protected]bbaea8f2011-06-24 00:11:011464void URLRequestHttpJob::RecordPerfHistograms(CompletionCause reason) {
1465 if (start_time_.is_null())
1466 return;
1467
1468 base::TimeDelta total_time = base::TimeTicks::Now() - start_time_;
1469 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTime", total_time);
1470
1471 if (reason == FINISHED) {
1472 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeSuccess", total_time);
1473 } else {
1474 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCancel", total_time);
1475 }
1476
[email protected]4b4d20242012-02-23 18:27:461477 if (response_info_) {
1478 if (response_info_->was_cached) {
1479 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeCached", total_time);
1480 } else {
1481 UMA_HISTOGRAM_TIMES("Net.HttpJob.TotalTimeNotCached", total_time);
[email protected]b73656ca2011-07-22 17:42:171482 }
[email protected]bbaea8f2011-06-24 00:11:011483 }
1484
[email protected]135c126a2012-10-31 15:39:251485 static const bool use_overlapped_read_histogram =
1486 base::FieldTrialList::TrialExists("OverlappedReadImpact");
1487 if (use_overlapped_read_histogram) {
1488 UMA_HISTOGRAM_TIMES(
1489 base::FieldTrial::MakeName("Net.HttpJob.TotalTime",
1490 "OverlappedReadImpact"),
1491 total_time);
1492
1493 if (reason == FINISHED) {
1494 UMA_HISTOGRAM_TIMES(
1495 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeSuccess",
1496 "OverlappedReadImpact"),
1497 total_time);
1498 } else {
1499 UMA_HISTOGRAM_TIMES(
1500 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeCancel",
1501 "OverlappedReadImpact"),
1502 total_time);
1503 }
1504
1505 if (response_info_) {
1506 if (response_info_->was_cached) {
1507 UMA_HISTOGRAM_TIMES(
1508 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeCached",
1509 "OverlappedReadImpact"),
1510 total_time);
1511 } else {
1512 UMA_HISTOGRAM_TIMES(
1513 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeNotCached",
1514 "OverlappedReadImpact"),
1515 total_time);
1516 }
1517 }
1518 }
1519
[email protected]908dc2b02012-11-27 23:16:261520 static const bool cache_sensitivity_analysis =
1521 base::FieldTrialList::TrialExists("CacheSensitivityAnalysis");
1522 if (cache_sensitivity_analysis) {
1523 UMA_HISTOGRAM_TIMES(
1524 base::FieldTrial::MakeName("Net.HttpJob.TotalTime",
1525 "CacheSensitivityAnalysis"),
1526 total_time);
1527
1528 if (reason == FINISHED) {
1529 UMA_HISTOGRAM_TIMES(
1530 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeSuccess",
1531 "CacheSensitivityAnalysis"),
1532 total_time);
1533 } else {
1534 UMA_HISTOGRAM_TIMES(
1535 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeCancel",
1536 "CacheSensitivityAnalysis"),
1537 total_time);
1538 }
1539
1540 if (response_info_) {
1541 if (response_info_->was_cached) {
1542 UMA_HISTOGRAM_TIMES(
1543 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeCached",
1544 "CacheSensitivityAnalysis"),
1545 total_time);
1546 } else {
1547 UMA_HISTOGRAM_TIMES(
1548 base::FieldTrial::MakeName("Net.HttpJob.TotalTimeNotCached",
1549 "CacheSensitivityAnalysis"),
1550 total_time);
1551 }
1552 }
1553 }
1554
[email protected]bbaea8f2011-06-24 00:11:011555 start_time_ = base::TimeTicks();
1556}
1557
1558void URLRequestHttpJob::DoneWithRequest(CompletionCause reason) {
1559 if (done_)
1560 return;
1561 done_ = true;
[email protected]bbaea8f2011-06-24 00:11:011562 RecordPerfHistograms(reason);
[email protected]7a299a92012-10-24 23:54:501563 if (reason == FINISHED) {
1564 request_->set_received_response_content_length(prefilter_bytes_read());
[email protected]bbaea8f2011-06-24 00:11:011565 RecordCompressionHistograms();
[email protected]7a299a92012-10-24 23:54:501566 }
[email protected]bbaea8f2011-06-24 00:11:011567}
1568
[email protected]ea8141e2011-10-05 13:12:511569HttpResponseHeaders* URLRequestHttpJob::GetResponseHeaders() const {
1570 DCHECK(transaction_.get());
1571 DCHECK(transaction_->GetResponseInfo());
1572 return override_response_headers_.get() ?
1573 override_response_headers_ :
1574 transaction_->GetResponseInfo()->headers;
1575}
1576
1577void URLRequestHttpJob::NotifyURLRequestDestroyed() {
1578 awaiting_callback_ = false;
1579}
1580
[email protected]5a07c192012-07-30 20:18:221581void URLRequestHttpJob::OnDetachRequest() {
1582 http_transaction_delegate_->OnDetachRequest();
1583}
1584
[email protected]4f5656c62010-12-13 10:47:091585} // namespace net