Material throbber: use in tabstrip
[chromium-blink-merge.git] / extensions / browser / updater / extension_downloader.cc
blob87958ae4a64d84051a1e130bdc5f22abdd243da7
1 // Copyright (c) 2012 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.
5 #include "extensions/browser/updater/extension_downloader.h"
7 #include <utility>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/time/time.h"
21 #include "base/version.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "content/public/browser/notification_details.h"
24 #include "content/public/browser/notification_service.h"
25 #include "extensions/browser/extensions_browser_client.h"
26 #include "extensions/browser/notification_types.h"
27 #include "extensions/browser/updater/extension_cache.h"
28 #include "extensions/browser/updater/request_queue_impl.h"
29 #include "extensions/browser/updater/safe_manifest_parser.h"
30 #include "extensions/common/extension_urls.h"
31 #include "extensions/common/manifest_url_handlers.h"
32 #include "google_apis/gaia/identity_provider.h"
33 #include "net/base/backoff_entry.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/net_errors.h"
36 #include "net/http/http_request_headers.h"
37 #include "net/http/http_status_code.h"
38 #include "net/url_request/url_fetcher.h"
39 #include "net/url_request/url_request_context_getter.h"
40 #include "net/url_request/url_request_status.h"
42 using base::Time;
43 using base::TimeDelta;
44 using content::BrowserThread;
46 namespace extensions {
48 const char ExtensionDownloader::kBlacklistAppID[] = "com.google.crx.blacklist";
50 namespace {
52 const net::BackoffEntry::Policy kDefaultBackoffPolicy = {
53 // Number of initial errors (in sequence) to ignore before applying
54 // exponential back-off rules.
57 // Initial delay for exponential back-off in ms.
58 2000,
60 // Factor by which the waiting time will be multiplied.
63 // Fuzzing percentage. ex: 10% will spread requests randomly
64 // between 90%-100% of the calculated time.
65 0.1,
67 // Maximum amount of time we are willing to delay our request in ms.
68 -1,
70 // Time to keep an entry from being discarded even when it
71 // has no significant state, -1 to never discard.
72 -1,
74 // Don't use initial delay unless the last request was an error.
75 false,
78 const char kAuthUserQueryKey[] = "authuser";
80 const int kMaxAuthUserValue = 10;
81 const int kMaxOAuth2Attempts = 3;
83 const char kNotFromWebstoreInstallSource[] = "notfromwebstore";
84 const char kDefaultInstallSource[] = "";
86 const char kGoogleDotCom[] = "google.com";
87 const char kTokenServiceConsumerId[] = "extension_downloader";
88 const char kWebstoreOAuth2Scope[] =
89 "https://www.googleapis.com/auth/chromewebstore.readonly";
91 #define RETRY_HISTOGRAM(name, retry_count, url) \
92 if ((url).DomainIs(kGoogleDotCom)) { \
93 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions." name "RetryCountGoogleUrl", \
94 retry_count, \
95 1, \
96 kMaxRetries, \
97 kMaxRetries + 1); \
98 } else { \
99 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions." name "RetryCountOtherUrl", \
100 retry_count, \
101 1, \
102 kMaxRetries, \
103 kMaxRetries + 1); \
106 bool ShouldRetryRequest(const net::URLRequestStatus& status,
107 int response_code) {
108 // Retry if the response code is a server error, or the request failed because
109 // of network errors as opposed to file errors.
110 return ((response_code >= 500 && status.is_success()) ||
111 status.status() == net::URLRequestStatus::FAILED);
114 // This parses and updates a URL query such that the value of the |authuser|
115 // query parameter is incremented by 1. If parameter was not present in the URL,
116 // it will be added with a value of 1. All other query keys and values are
117 // preserved as-is. Returns |false| if the user index exceeds a hard-coded
118 // maximum.
119 bool IncrementAuthUserIndex(GURL* url) {
120 int user_index = 0;
121 std::string old_query = url->query();
122 std::vector<std::string> new_query_parts;
123 url::Component query(0, old_query.length());
124 url::Component key, value;
125 while (url::ExtractQueryKeyValue(old_query.c_str(), &query, &key, &value)) {
126 std::string key_string = old_query.substr(key.begin, key.len);
127 std::string value_string = old_query.substr(value.begin, value.len);
128 if (key_string == kAuthUserQueryKey) {
129 base::StringToInt(value_string, &user_index);
130 } else {
131 new_query_parts.push_back(base::StringPrintf(
132 "%s=%s", key_string.c_str(), value_string.c_str()));
135 if (user_index >= kMaxAuthUserValue)
136 return false;
137 new_query_parts.push_back(
138 base::StringPrintf("%s=%d", kAuthUserQueryKey, user_index + 1));
139 std::string new_query_string = JoinString(new_query_parts, '&');
140 url::Component new_query(0, new_query_string.size());
141 url::Replacements<char> replacements;
142 replacements.SetQuery(new_query_string.c_str(), new_query);
143 *url = url->ReplaceComponents(replacements);
144 return true;
147 } // namespace
149 UpdateDetails::UpdateDetails(const std::string& id, const Version& version)
150 : id(id), version(version) {
153 UpdateDetails::~UpdateDetails() {
156 ExtensionDownloader::ExtensionFetch::ExtensionFetch()
157 : url(), credentials(CREDENTIALS_NONE) {
160 ExtensionDownloader::ExtensionFetch::ExtensionFetch(
161 const std::string& id,
162 const GURL& url,
163 const std::string& package_hash,
164 const std::string& version,
165 const std::set<int>& request_ids)
166 : id(id),
167 url(url),
168 package_hash(package_hash),
169 version(version),
170 request_ids(request_ids),
171 credentials(CREDENTIALS_NONE),
172 oauth2_attempt_count(0) {
175 ExtensionDownloader::ExtensionFetch::~ExtensionFetch() {
178 ExtensionDownloader::ExtensionDownloader(
179 ExtensionDownloaderDelegate* delegate,
180 net::URLRequestContextGetter* request_context)
181 : OAuth2TokenService::Consumer(kTokenServiceConsumerId),
182 delegate_(delegate),
183 request_context_(request_context),
184 manifests_queue_(&kDefaultBackoffPolicy,
185 base::Bind(&ExtensionDownloader::CreateManifestFetcher,
186 base::Unretained(this))),
187 extensions_queue_(&kDefaultBackoffPolicy,
188 base::Bind(&ExtensionDownloader::CreateExtensionFetcher,
189 base::Unretained(this))),
190 extension_cache_(NULL),
191 enable_extra_update_metrics_(false),
192 weak_ptr_factory_(this) {
193 DCHECK(delegate_);
194 DCHECK(request_context_.get());
197 ExtensionDownloader::~ExtensionDownloader() {
200 bool ExtensionDownloader::AddExtension(const Extension& extension,
201 int request_id) {
202 // Skip extensions with empty update URLs converted from user
203 // scripts.
204 if (extension.converted_from_user_script() &&
205 ManifestURL::GetUpdateURL(&extension).is_empty()) {
206 return false;
209 // If the extension updates itself from the gallery, ignore any update URL
210 // data. At the moment there is no extra data that an extension can
211 // communicate to the the gallery update servers.
212 std::string update_url_data;
213 if (!ManifestURL::UpdatesFromGallery(&extension))
214 update_url_data = delegate_->GetUpdateUrlData(extension.id());
216 std::string install_source;
217 bool force_update =
218 delegate_->ShouldForceUpdate(extension.id(), &install_source);
219 return AddExtensionData(extension.id(),
220 *extension.version(),
221 extension.GetType(),
222 ManifestURL::GetUpdateURL(&extension),
223 update_url_data,
224 request_id,
225 force_update,
226 install_source);
229 bool ExtensionDownloader::AddPendingExtension(const std::string& id,
230 const GURL& update_url,
231 int request_id) {
232 // Use a zero version to ensure that a pending extension will always
233 // be updated, and thus installed (assuming all extensions have
234 // non-zero versions).
235 Version version("0.0.0.0");
236 DCHECK(version.IsValid());
238 return AddExtensionData(id,
239 version,
240 Manifest::TYPE_UNKNOWN,
241 update_url,
242 std::string(),
243 request_id,
244 false,
245 std::string());
248 void ExtensionDownloader::StartAllPending(ExtensionCache* cache) {
249 if (cache) {
250 extension_cache_ = cache;
251 extension_cache_->Start(base::Bind(&ExtensionDownloader::DoStartAllPending,
252 weak_ptr_factory_.GetWeakPtr()));
253 } else {
254 DoStartAllPending();
258 void ExtensionDownloader::DoStartAllPending() {
259 ReportStats();
260 url_stats_ = URLStats();
262 for (FetchMap::iterator it = fetches_preparing_.begin();
263 it != fetches_preparing_.end();
264 ++it) {
265 std::vector<linked_ptr<ManifestFetchData>>& list = it->second;
266 for (size_t i = 0; i < list.size(); ++i) {
267 StartUpdateCheck(scoped_ptr<ManifestFetchData>(list[i].release()));
270 fetches_preparing_.clear();
273 void ExtensionDownloader::StartBlacklistUpdate(
274 const std::string& version,
275 const ManifestFetchData::PingData& ping_data,
276 int request_id) {
277 // Note: it is very important that we use the https version of the update
278 // url here to avoid DNS hijacking of the blacklist, which is not validated
279 // by a public key signature like .crx files are.
280 scoped_ptr<ManifestFetchData> blacklist_fetch(CreateManifestFetchData(
281 extension_urls::GetWebstoreUpdateUrl(), request_id));
282 DCHECK(blacklist_fetch->base_url().SchemeIsSecure());
283 blacklist_fetch->AddExtension(kBlacklistAppID,
284 version,
285 &ping_data,
286 std::string(),
287 kDefaultInstallSource,
288 false);
289 StartUpdateCheck(blacklist_fetch.Pass());
292 void ExtensionDownloader::SetWebstoreIdentityProvider(
293 scoped_ptr<IdentityProvider> identity_provider) {
294 identity_provider_.swap(identity_provider);
297 bool ExtensionDownloader::AddExtensionData(
298 const std::string& id,
299 const Version& version,
300 Manifest::Type extension_type,
301 const GURL& extension_update_url,
302 const std::string& update_url_data,
303 int request_id,
304 bool force_update,
305 const std::string& install_source_override) {
306 GURL update_url(extension_update_url);
307 // Skip extensions with non-empty invalid update URLs.
308 if (!update_url.is_empty() && !update_url.is_valid()) {
309 LOG(WARNING) << "Extension " << id << " has invalid update url "
310 << update_url;
311 return false;
314 // Make sure we use SSL for store-hosted extensions.
315 if (extension_urls::IsWebstoreUpdateUrl(update_url) &&
316 !update_url.SchemeIsSecure())
317 update_url = extension_urls::GetWebstoreUpdateUrl();
319 // Skip extensions with empty IDs.
320 if (id.empty()) {
321 LOG(WARNING) << "Found extension with empty ID";
322 return false;
325 if (update_url.DomainIs(kGoogleDotCom)) {
326 url_stats_.google_url_count++;
327 } else if (update_url.is_empty()) {
328 url_stats_.no_url_count++;
329 // Fill in default update URL.
330 update_url = extension_urls::GetWebstoreUpdateUrl();
331 } else {
332 url_stats_.other_url_count++;
335 switch (extension_type) {
336 case Manifest::TYPE_THEME:
337 ++url_stats_.theme_count;
338 break;
339 case Manifest::TYPE_EXTENSION:
340 case Manifest::TYPE_USER_SCRIPT:
341 ++url_stats_.extension_count;
342 break;
343 case Manifest::TYPE_HOSTED_APP:
344 case Manifest::TYPE_LEGACY_PACKAGED_APP:
345 ++url_stats_.app_count;
346 break;
347 case Manifest::TYPE_PLATFORM_APP:
348 ++url_stats_.platform_app_count;
349 break;
350 case Manifest::TYPE_UNKNOWN:
351 default:
352 ++url_stats_.pending_count;
353 break;
356 std::vector<GURL> update_urls;
357 update_urls.push_back(update_url);
358 // If metrics are enabled, also add to ManifestFetchData for the
359 // webstore update URL.
360 if (!extension_urls::IsWebstoreUpdateUrl(update_url) &&
361 enable_extra_update_metrics_) {
362 update_urls.push_back(extension_urls::GetWebstoreUpdateUrl());
365 for (size_t i = 0; i < update_urls.size(); ++i) {
366 DCHECK(!update_urls[i].is_empty());
367 DCHECK(update_urls[i].is_valid());
369 std::string install_source =
370 i == 0 ? kDefaultInstallSource : kNotFromWebstoreInstallSource;
371 if (!install_source_override.empty()) {
372 install_source = install_source_override;
375 ManifestFetchData::PingData ping_data;
376 ManifestFetchData::PingData* optional_ping_data = NULL;
377 if (delegate_->GetPingDataForExtension(id, &ping_data))
378 optional_ping_data = &ping_data;
380 // Find or create a ManifestFetchData to add this extension to.
381 bool added = false;
382 FetchMap::iterator existing_iter =
383 fetches_preparing_.find(std::make_pair(request_id, update_urls[i]));
384 if (existing_iter != fetches_preparing_.end() &&
385 !existing_iter->second.empty()) {
386 // Try to add to the ManifestFetchData at the end of the list.
387 ManifestFetchData* existing_fetch = existing_iter->second.back().get();
388 if (existing_fetch->AddExtension(id,
389 version.GetString(),
390 optional_ping_data,
391 update_url_data,
392 install_source,
393 force_update)) {
394 added = true;
397 if (!added) {
398 // Otherwise add a new element to the list, if the list doesn't exist or
399 // if its last element is already full.
400 linked_ptr<ManifestFetchData> fetch(
401 CreateManifestFetchData(update_urls[i], request_id));
402 fetches_preparing_[std::make_pair(request_id, update_urls[i])].push_back(
403 fetch);
404 added = fetch->AddExtension(id,
405 version.GetString(),
406 optional_ping_data,
407 update_url_data,
408 install_source,
409 force_update);
410 DCHECK(added);
414 return true;
417 void ExtensionDownloader::ReportStats() const {
418 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckExtension",
419 url_stats_.extension_count);
420 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckTheme",
421 url_stats_.theme_count);
422 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckApp", url_stats_.app_count);
423 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckPackagedApp",
424 url_stats_.platform_app_count);
425 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckPending",
426 url_stats_.pending_count);
427 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckGoogleUrl",
428 url_stats_.google_url_count);
429 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckOtherUrl",
430 url_stats_.other_url_count);
431 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckNoUrl",
432 url_stats_.no_url_count);
435 void ExtensionDownloader::StartUpdateCheck(
436 scoped_ptr<ManifestFetchData> fetch_data) {
437 const std::set<std::string>& id_set(fetch_data->extension_ids());
439 if (!ExtensionsBrowserClient::Get()->IsBackgroundUpdateAllowed()) {
440 NotifyExtensionsDownloadFailed(id_set,
441 fetch_data->request_ids(),
442 ExtensionDownloaderDelegate::DISABLED);
445 RequestQueue<ManifestFetchData>::iterator i;
446 for (i = manifests_queue_.begin(); i != manifests_queue_.end(); ++i) {
447 if (fetch_data->full_url() == i->full_url()) {
448 // This url is already scheduled to be fetched.
449 i->Merge(*fetch_data);
450 return;
454 if (manifests_queue_.active_request() &&
455 manifests_queue_.active_request()->full_url() == fetch_data->full_url()) {
456 manifests_queue_.active_request()->Merge(*fetch_data);
457 } else {
458 UMA_HISTOGRAM_COUNTS(
459 "Extensions.UpdateCheckUrlLength",
460 fetch_data->full_url().possibly_invalid_spec().length());
462 manifests_queue_.ScheduleRequest(fetch_data.Pass());
466 void ExtensionDownloader::CreateManifestFetcher() {
467 if (VLOG_IS_ON(2)) {
468 std::vector<std::string> id_vector(
469 manifests_queue_.active_request()->extension_ids().begin(),
470 manifests_queue_.active_request()->extension_ids().end());
471 std::string id_list = JoinString(id_vector, ',');
472 VLOG(2) << "Fetching " << manifests_queue_.active_request()->full_url()
473 << " for " << id_list;
476 manifest_fetcher_ = net::URLFetcher::Create(
477 kManifestFetcherId, manifests_queue_.active_request()->full_url(),
478 net::URLFetcher::GET, this);
479 manifest_fetcher_->SetRequestContext(request_context_.get());
480 manifest_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
481 net::LOAD_DO_NOT_SAVE_COOKIES |
482 net::LOAD_DISABLE_CACHE);
483 // Update checks can be interrupted if a network change is detected; this is
484 // common for the retail mode AppPack on ChromeOS. Retrying once should be
485 // enough to recover in those cases; let the fetcher retry up to 3 times
486 // just in case. http://crosbug.com/130602
487 manifest_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
488 manifest_fetcher_->Start();
491 void ExtensionDownloader::OnURLFetchComplete(const net::URLFetcher* source) {
492 VLOG(2) << source->GetResponseCode() << " " << source->GetURL();
494 if (source == manifest_fetcher_.get()) {
495 std::string data;
496 source->GetResponseAsString(&data);
497 OnManifestFetchComplete(source->GetURL(),
498 source->GetStatus(),
499 source->GetResponseCode(),
500 source->GetBackoffDelay(),
501 data);
502 } else if (source == extension_fetcher_.get()) {
503 OnCRXFetchComplete(source,
504 source->GetURL(),
505 source->GetStatus(),
506 source->GetResponseCode(),
507 source->GetBackoffDelay());
508 } else {
509 NOTREACHED();
513 void ExtensionDownloader::OnManifestFetchComplete(
514 const GURL& url,
515 const net::URLRequestStatus& status,
516 int response_code,
517 const base::TimeDelta& backoff_delay,
518 const std::string& data) {
519 // We want to try parsing the manifest, and if it indicates updates are
520 // available, we want to fire off requests to fetch those updates.
521 if (status.status() == net::URLRequestStatus::SUCCESS &&
522 (response_code == 200 || (url.SchemeIsFile() && data.length() > 0))) {
523 RETRY_HISTOGRAM("ManifestFetchSuccess",
524 manifests_queue_.active_request_failure_count(),
525 url);
526 VLOG(2) << "beginning manifest parse for " << url;
527 scoped_refptr<SafeManifestParser> safe_parser(new SafeManifestParser(
528 data,
529 base::Bind(
530 &ExtensionDownloader::HandleManifestResults,
531 weak_ptr_factory_.GetWeakPtr(),
532 base::Owned(manifests_queue_.reset_active_request().release()))));
533 safe_parser->Start();
534 } else {
535 VLOG(1) << "Failed to fetch manifest '" << url.possibly_invalid_spec()
536 << "' response code:" << response_code;
537 if (ShouldRetryRequest(status, response_code) &&
538 manifests_queue_.active_request_failure_count() < kMaxRetries) {
539 manifests_queue_.RetryRequest(backoff_delay);
540 } else {
541 RETRY_HISTOGRAM("ManifestFetchFailure",
542 manifests_queue_.active_request_failure_count(),
543 url);
544 NotifyExtensionsDownloadFailed(
545 manifests_queue_.active_request()->extension_ids(),
546 manifests_queue_.active_request()->request_ids(),
547 ExtensionDownloaderDelegate::MANIFEST_FETCH_FAILED);
550 manifest_fetcher_.reset();
551 manifests_queue_.reset_active_request();
553 // If we have any pending manifest requests, fire off the next one.
554 manifests_queue_.StartNextRequest();
557 void ExtensionDownloader::HandleManifestResults(
558 const ManifestFetchData* fetch_data,
559 const UpdateManifest::Results* results) {
560 // Keep a list of extensions that will not be updated, so that the |delegate_|
561 // can be notified once we're done here.
562 std::set<std::string> not_updated(fetch_data->extension_ids());
564 if (!results) {
565 VLOG(2) << "parsing manifest failed (" << fetch_data->full_url() << ")";
566 NotifyExtensionsDownloadFailed(
567 not_updated, fetch_data->request_ids(),
568 ExtensionDownloaderDelegate::MANIFEST_INVALID);
569 return;
570 } else {
571 VLOG(2) << "parsing manifest succeeded (" << fetch_data->full_url() << ")";
574 // Examine the parsed manifest and kick off fetches of any new crx files.
575 std::vector<int> updates;
576 DetermineUpdates(*fetch_data, *results, &updates);
577 for (size_t i = 0; i < updates.size(); i++) {
578 const UpdateManifest::Result* update = &(results->list.at(updates[i]));
579 const std::string& id = update->extension_id;
580 not_updated.erase(id);
582 GURL crx_url = update->crx_url;
583 if (id != kBlacklistAppID) {
584 NotifyUpdateFound(update->extension_id, update->version);
585 } else {
586 // The URL of the blacklist file is returned by the server and we need to
587 // be sure that we continue to be able to reliably detect whether a URL
588 // references a blacklist file.
589 DCHECK(extension_urls::IsBlacklistUpdateUrl(crx_url)) << crx_url;
591 // Force https (crbug.com/129587).
592 if (!crx_url.SchemeIsSecure()) {
593 url::Replacements<char> replacements;
594 std::string scheme("https");
595 replacements.SetScheme(scheme.c_str(),
596 url::Component(0, scheme.size()));
597 crx_url = crx_url.ReplaceComponents(replacements);
600 scoped_ptr<ExtensionFetch> fetch(
601 new ExtensionFetch(update->extension_id, crx_url, update->package_hash,
602 update->version, fetch_data->request_ids()));
603 FetchUpdatedExtension(fetch.Pass());
606 // If the manifest response included a <daystart> element, we want to save
607 // that value for any extensions which had sent a ping in the request.
608 if (fetch_data->base_url().DomainIs(kGoogleDotCom) &&
609 results->daystart_elapsed_seconds >= 0) {
610 Time day_start =
611 Time::Now() - TimeDelta::FromSeconds(results->daystart_elapsed_seconds);
613 const std::set<std::string>& extension_ids = fetch_data->extension_ids();
614 std::set<std::string>::const_iterator i;
615 for (i = extension_ids.begin(); i != extension_ids.end(); i++) {
616 const std::string& id = *i;
617 ExtensionDownloaderDelegate::PingResult& result = ping_results_[id];
618 result.did_ping = fetch_data->DidPing(id, ManifestFetchData::ROLLCALL);
619 result.day_start = day_start;
623 NotifyExtensionsDownloadFailed(
624 not_updated, fetch_data->request_ids(),
625 ExtensionDownloaderDelegate::NO_UPDATE_AVAILABLE);
628 void ExtensionDownloader::DetermineUpdates(
629 const ManifestFetchData& fetch_data,
630 const UpdateManifest::Results& possible_updates,
631 std::vector<int>* result) {
632 for (size_t i = 0; i < possible_updates.list.size(); i++) {
633 const UpdateManifest::Result* update = &possible_updates.list[i];
634 const std::string& id = update->extension_id;
636 if (!fetch_data.Includes(id)) {
637 VLOG(2) << "Ignoring " << id << " from this manifest";
638 continue;
641 if (VLOG_IS_ON(2)) {
642 if (update->version.empty())
643 VLOG(2) << "manifest indicates " << id << " has no update";
644 else
645 VLOG(2) << "manifest indicates " << id << " latest version is '"
646 << update->version << "'";
649 if (!delegate_->IsExtensionPending(id)) {
650 // If we're not installing pending extension, and the update
651 // version is the same or older than what's already installed,
652 // we don't want it.
653 std::string version;
654 if (!delegate_->GetExtensionExistingVersion(id, &version)) {
655 VLOG(2) << id << " is not installed";
656 continue;
659 VLOG(2) << id << " is at '" << version << "'";
661 // We should skip the version check if update was forced.
662 if (!fetch_data.DidForceUpdate(id)) {
663 Version existing_version(version);
664 Version update_version(update->version);
665 if (!update_version.IsValid() ||
666 update_version.CompareTo(existing_version) <= 0) {
667 continue;
672 // If the update specifies a browser minimum version, do we qualify?
673 if (update->browser_min_version.length() > 0 &&
674 !ExtensionsBrowserClient::Get()->IsMinBrowserVersionSupported(
675 update->browser_min_version)) {
676 // TODO(asargent) - We may want this to show up in the extensions UI
677 // eventually. (http://crbug.com/12547).
678 LOG(WARNING) << "Updated version of extension " << id
679 << " available, but requires chrome version "
680 << update->browser_min_version;
681 continue;
683 VLOG(2) << "will try to update " << id;
684 result->push_back(i);
688 // Begins (or queues up) download of an updated extension.
689 void ExtensionDownloader::FetchUpdatedExtension(
690 scoped_ptr<ExtensionFetch> fetch_data) {
691 if (!fetch_data->url.is_valid()) {
692 // TODO(asargent): This can sometimes be invalid. See crbug.com/130881.
693 LOG(ERROR) << "Invalid URL: '" << fetch_data->url.possibly_invalid_spec()
694 << "' for extension " << fetch_data->id;
695 return;
698 for (RequestQueue<ExtensionFetch>::iterator iter = extensions_queue_.begin();
699 iter != extensions_queue_.end();
700 ++iter) {
701 if (iter->id == fetch_data->id || iter->url == fetch_data->url) {
702 iter->request_ids.insert(fetch_data->request_ids.begin(),
703 fetch_data->request_ids.end());
704 return; // already scheduled
708 if (extensions_queue_.active_request() &&
709 extensions_queue_.active_request()->url == fetch_data->url) {
710 extensions_queue_.active_request()->request_ids.insert(
711 fetch_data->request_ids.begin(), fetch_data->request_ids.end());
712 } else {
713 std::string version;
714 if (extension_cache_ &&
715 extension_cache_->GetExtension(fetch_data->id, fetch_data->package_hash,
716 NULL, &version) &&
717 version == fetch_data->version) {
718 base::FilePath crx_path;
719 // Now get .crx file path and mark extension as used.
720 extension_cache_->GetExtension(fetch_data->id, fetch_data->package_hash,
721 &crx_path, &version);
722 NotifyDelegateDownloadFinished(fetch_data.Pass(), true, crx_path, false);
723 } else {
724 extensions_queue_.ScheduleRequest(fetch_data.Pass());
729 void ExtensionDownloader::NotifyDelegateDownloadFinished(
730 scoped_ptr<ExtensionFetch> fetch_data,
731 bool from_cache,
732 const base::FilePath& crx_path,
733 bool file_ownership_passed) {
734 // Dereference required params before passing a scoped_ptr.
735 const std::string& id = fetch_data->id;
736 const std::string& package_hash = fetch_data->package_hash;
737 const GURL& url = fetch_data->url;
738 const std::string& version = fetch_data->version;
739 const std::set<int>& request_ids = fetch_data->request_ids;
740 delegate_->OnExtensionDownloadFinished(
741 CRXFileInfo(id, crx_path, package_hash), file_ownership_passed, url,
742 version, ping_results_[id], request_ids,
743 from_cache ? base::Bind(&ExtensionDownloader::CacheInstallDone,
744 weak_ptr_factory_.GetWeakPtr(),
745 base::Passed(&fetch_data))
746 : ExtensionDownloaderDelegate::InstallCallback());
747 if (!from_cache)
748 ping_results_.erase(id);
751 void ExtensionDownloader::CacheInstallDone(
752 scoped_ptr<ExtensionFetch> fetch_data,
753 bool should_download) {
754 ping_results_.erase(fetch_data->id);
755 if (should_download) {
756 // Resume download from cached manifest data.
757 extensions_queue_.ScheduleRequest(fetch_data.Pass());
761 void ExtensionDownloader::CreateExtensionFetcher() {
762 const ExtensionFetch* fetch = extensions_queue_.active_request();
763 extension_fetcher_ = net::URLFetcher::Create(kExtensionFetcherId, fetch->url,
764 net::URLFetcher::GET, this);
765 extension_fetcher_->SetRequestContext(request_context_.get());
766 extension_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
768 int load_flags = net::LOAD_DISABLE_CACHE;
769 bool is_secure = fetch->url.SchemeIsSecure();
770 if (fetch->credentials != ExtensionFetch::CREDENTIALS_COOKIES || !is_secure) {
771 load_flags |= net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES;
773 extension_fetcher_->SetLoadFlags(load_flags);
775 // Download CRX files to a temp file. The blacklist is small and will be
776 // processed in memory, so it is fetched into a string.
777 if (fetch->id != kBlacklistAppID) {
778 extension_fetcher_->SaveResponseToTemporaryFile(
779 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
782 if (fetch->credentials == ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN &&
783 is_secure) {
784 if (access_token_.empty()) {
785 // We should try OAuth2, but we have no token cached. This
786 // ExtensionFetcher will be started once the token fetch is complete,
787 // in either OnTokenFetchSuccess or OnTokenFetchFailure.
788 DCHECK(identity_provider_.get());
789 OAuth2TokenService::ScopeSet webstore_scopes;
790 webstore_scopes.insert(kWebstoreOAuth2Scope);
791 access_token_request_ =
792 identity_provider_->GetTokenService()->StartRequest(
793 identity_provider_->GetActiveAccountId(), webstore_scopes, this);
794 return;
796 extension_fetcher_->AddExtraRequestHeader(
797 base::StringPrintf("%s: Bearer %s",
798 net::HttpRequestHeaders::kAuthorization,
799 access_token_.c_str()));
802 VLOG(2) << "Starting fetch of " << fetch->url << " for " << fetch->id;
803 extension_fetcher_->Start();
806 void ExtensionDownloader::OnCRXFetchComplete(
807 const net::URLFetcher* source,
808 const GURL& url,
809 const net::URLRequestStatus& status,
810 int response_code,
811 const base::TimeDelta& backoff_delay) {
812 ExtensionFetch& active_request = *extensions_queue_.active_request();
813 const std::string& id = active_request.id;
814 if (status.status() == net::URLRequestStatus::SUCCESS &&
815 (response_code == 200 || url.SchemeIsFile())) {
816 RETRY_HISTOGRAM("CrxFetchSuccess",
817 extensions_queue_.active_request_failure_count(),
818 url);
819 base::FilePath crx_path;
820 // Take ownership of the file at |crx_path|.
821 CHECK(source->GetResponseAsFilePath(true, &crx_path));
822 scoped_ptr<ExtensionFetch> fetch_data =
823 extensions_queue_.reset_active_request();
824 if (extension_cache_) {
825 const std::string& version = fetch_data->version;
826 const std::string& expected_hash = fetch_data->package_hash;
827 extension_cache_->PutExtension(
828 id, expected_hash, crx_path, version,
829 base::Bind(&ExtensionDownloader::NotifyDelegateDownloadFinished,
830 weak_ptr_factory_.GetWeakPtr(), base::Passed(&fetch_data),
831 false));
832 } else {
833 NotifyDelegateDownloadFinished(fetch_data.Pass(), false, crx_path, true);
835 } else if (IterateFetchCredentialsAfterFailure(
836 &active_request, status, response_code)) {
837 extensions_queue_.RetryRequest(backoff_delay);
838 } else {
839 const std::set<int>& request_ids = active_request.request_ids;
840 const ExtensionDownloaderDelegate::PingResult& ping = ping_results_[id];
841 VLOG(1) << "Failed to fetch extension '" << url.possibly_invalid_spec()
842 << "' response code:" << response_code;
843 if (ShouldRetryRequest(status, response_code) &&
844 extensions_queue_.active_request_failure_count() < kMaxRetries) {
845 extensions_queue_.RetryRequest(backoff_delay);
846 } else {
847 RETRY_HISTOGRAM("CrxFetchFailure",
848 extensions_queue_.active_request_failure_count(),
849 url);
850 // status.error() is 0 (net::OK) or negative. (See net/base/net_errors.h)
851 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.CrxFetchError", -status.error());
852 delegate_->OnExtensionDownloadFailed(
853 id, ExtensionDownloaderDelegate::CRX_FETCH_FAILED, ping, request_ids);
855 ping_results_.erase(id);
856 extensions_queue_.reset_active_request();
859 extension_fetcher_.reset();
861 // If there are any pending downloads left, start the next one.
862 extensions_queue_.StartNextRequest();
865 void ExtensionDownloader::NotifyExtensionsDownloadFailed(
866 const std::set<std::string>& extension_ids,
867 const std::set<int>& request_ids,
868 ExtensionDownloaderDelegate::Error error) {
869 for (std::set<std::string>::const_iterator it = extension_ids.begin();
870 it != extension_ids.end();
871 ++it) {
872 const ExtensionDownloaderDelegate::PingResult& ping = ping_results_[*it];
873 delegate_->OnExtensionDownloadFailed(*it, error, ping, request_ids);
874 ping_results_.erase(*it);
878 void ExtensionDownloader::NotifyUpdateFound(const std::string& id,
879 const std::string& version) {
880 UpdateDetails updateInfo(id, Version(version));
881 content::NotificationService::current()->Notify(
882 extensions::NOTIFICATION_EXTENSION_UPDATE_FOUND,
883 content::NotificationService::AllBrowserContextsAndSources(),
884 content::Details<UpdateDetails>(&updateInfo));
887 bool ExtensionDownloader::IterateFetchCredentialsAfterFailure(
888 ExtensionFetch* fetch,
889 const net::URLRequestStatus& status,
890 int response_code) {
891 bool auth_failure = status.status() == net::URLRequestStatus::CANCELED ||
892 (status.status() == net::URLRequestStatus::SUCCESS &&
893 (response_code == net::HTTP_UNAUTHORIZED ||
894 response_code == net::HTTP_FORBIDDEN));
895 if (!auth_failure) {
896 return false;
898 // Here we decide what to do next if the server refused to authorize this
899 // fetch.
900 switch (fetch->credentials) {
901 case ExtensionFetch::CREDENTIALS_NONE:
902 if (fetch->url.DomainIs(kGoogleDotCom) && identity_provider_) {
903 fetch->credentials = ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN;
904 } else {
905 fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES;
907 return true;
908 case ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN:
909 fetch->oauth2_attempt_count++;
910 // OAuth2 may fail due to an expired access token, in which case we
911 // should invalidate the token and try again.
912 if (response_code == net::HTTP_UNAUTHORIZED &&
913 fetch->oauth2_attempt_count <= kMaxOAuth2Attempts) {
914 DCHECK(identity_provider_.get());
915 OAuth2TokenService::ScopeSet webstore_scopes;
916 webstore_scopes.insert(kWebstoreOAuth2Scope);
917 identity_provider_->GetTokenService()->InvalidateToken(
918 identity_provider_->GetActiveAccountId(),
919 webstore_scopes,
920 access_token_);
921 access_token_.clear();
922 return true;
924 // Either there is no Gaia identity available, the active identity
925 // doesn't have access to this resource, or the server keeps returning
926 // 401s and we've retried too many times. Fall back on cookies.
927 if (access_token_.empty() || response_code == net::HTTP_FORBIDDEN ||
928 fetch->oauth2_attempt_count > kMaxOAuth2Attempts) {
929 fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES;
930 return true;
932 // Something else is wrong. Time to give up.
933 return false;
934 case ExtensionFetch::CREDENTIALS_COOKIES:
935 if (response_code == net::HTTP_FORBIDDEN) {
936 // Try the next session identity, up to some maximum.
937 return IncrementAuthUserIndex(&fetch->url);
939 return false;
940 default:
941 NOTREACHED();
943 NOTREACHED();
944 return false;
947 void ExtensionDownloader::OnGetTokenSuccess(
948 const OAuth2TokenService::Request* request,
949 const std::string& access_token,
950 const base::Time& expiration_time) {
951 access_token_ = access_token;
952 extension_fetcher_->AddExtraRequestHeader(
953 base::StringPrintf("%s: Bearer %s",
954 net::HttpRequestHeaders::kAuthorization,
955 access_token_.c_str()));
956 extension_fetcher_->Start();
959 void ExtensionDownloader::OnGetTokenFailure(
960 const OAuth2TokenService::Request* request,
961 const GoogleServiceAuthError& error) {
962 // If we fail to get an access token, kick the pending fetch and let it fall
963 // back on cookies.
964 extension_fetcher_->Start();
967 ManifestFetchData* ExtensionDownloader::CreateManifestFetchData(
968 const GURL& update_url,
969 int request_id) {
970 ManifestFetchData::PingMode ping_mode = ManifestFetchData::NO_PING;
971 if (update_url.DomainIs(ping_enabled_domain_.c_str()))
972 ping_mode = ManifestFetchData::PING_WITH_ENABLED_STATE;
973 return new ManifestFetchData(
974 update_url, request_id, brand_code_, manifest_query_params_, ping_mode);
977 } // namespace extensions