Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / extensions / browser / updater / extension_downloader.cc
blobda4ff410bf4a2f1a6f29f5b88f3de58c4779ba47
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_.reset(
477 net::URLFetcher::Create(kManifestFetcherId,
478 manifests_queue_.active_request()->full_url(),
479 net::URLFetcher::GET,
480 this));
481 manifest_fetcher_->SetRequestContext(request_context_.get());
482 manifest_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
483 net::LOAD_DO_NOT_SAVE_COOKIES |
484 net::LOAD_DISABLE_CACHE);
485 // Update checks can be interrupted if a network change is detected; this is
486 // common for the retail mode AppPack on ChromeOS. Retrying once should be
487 // enough to recover in those cases; let the fetcher retry up to 3 times
488 // just in case. http://crosbug.com/130602
489 manifest_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
490 manifest_fetcher_->Start();
493 void ExtensionDownloader::OnURLFetchComplete(const net::URLFetcher* source) {
494 VLOG(2) << source->GetResponseCode() << " " << source->GetURL();
496 if (source == manifest_fetcher_.get()) {
497 std::string data;
498 source->GetResponseAsString(&data);
499 OnManifestFetchComplete(source->GetURL(),
500 source->GetStatus(),
501 source->GetResponseCode(),
502 source->GetBackoffDelay(),
503 data);
504 } else if (source == extension_fetcher_.get()) {
505 OnCRXFetchComplete(source,
506 source->GetURL(),
507 source->GetStatus(),
508 source->GetResponseCode(),
509 source->GetBackoffDelay());
510 } else {
511 NOTREACHED();
515 void ExtensionDownloader::OnManifestFetchComplete(
516 const GURL& url,
517 const net::URLRequestStatus& status,
518 int response_code,
519 const base::TimeDelta& backoff_delay,
520 const std::string& data) {
521 // We want to try parsing the manifest, and if it indicates updates are
522 // available, we want to fire off requests to fetch those updates.
523 if (status.status() == net::URLRequestStatus::SUCCESS &&
524 (response_code == 200 || (url.SchemeIsFile() && data.length() > 0))) {
525 RETRY_HISTOGRAM("ManifestFetchSuccess",
526 manifests_queue_.active_request_failure_count(),
527 url);
528 VLOG(2) << "beginning manifest parse for " << url;
529 scoped_refptr<SafeManifestParser> safe_parser(new SafeManifestParser(
530 data,
531 manifests_queue_.reset_active_request().release(),
532 base::Bind(&ExtensionDownloader::HandleManifestResults,
533 weak_ptr_factory_.GetWeakPtr())));
534 safe_parser->Start();
535 } else {
536 VLOG(1) << "Failed to fetch manifest '" << url.possibly_invalid_spec()
537 << "' response code:" << response_code;
538 if (ShouldRetryRequest(status, response_code) &&
539 manifests_queue_.active_request_failure_count() < kMaxRetries) {
540 manifests_queue_.RetryRequest(backoff_delay);
541 } else {
542 RETRY_HISTOGRAM("ManifestFetchFailure",
543 manifests_queue_.active_request_failure_count(),
544 url);
545 NotifyExtensionsDownloadFailed(
546 manifests_queue_.active_request()->extension_ids(),
547 manifests_queue_.active_request()->request_ids(),
548 ExtensionDownloaderDelegate::MANIFEST_FETCH_FAILED);
551 manifest_fetcher_.reset();
552 manifests_queue_.reset_active_request();
554 // If we have any pending manifest requests, fire off the next one.
555 manifests_queue_.StartNextRequest();
558 void ExtensionDownloader::HandleManifestResults(
559 const ManifestFetchData& fetch_data,
560 const UpdateManifest::Results* results) {
561 // Keep a list of extensions that will not be updated, so that the |delegate_|
562 // can be notified once we're done here.
563 std::set<std::string> not_updated(fetch_data.extension_ids());
565 if (!results) {
566 NotifyExtensionsDownloadFailed(
567 not_updated,
568 fetch_data.request_ids(),
569 ExtensionDownloaderDelegate::MANIFEST_INVALID);
570 return;
573 // Examine the parsed manifest and kick off fetches of any new crx files.
574 std::vector<int> updates;
575 DetermineUpdates(fetch_data, *results, &updates);
576 for (size_t i = 0; i < updates.size(); i++) {
577 const UpdateManifest::Result* update = &(results->list.at(updates[i]));
578 const std::string& id = update->extension_id;
579 not_updated.erase(id);
581 GURL crx_url = update->crx_url;
582 if (id != kBlacklistAppID) {
583 NotifyUpdateFound(update->extension_id, update->version);
584 } else {
585 // The URL of the blacklist file is returned by the server and we need to
586 // be sure that we continue to be able to reliably detect whether a URL
587 // references a blacklist file.
588 DCHECK(extension_urls::IsBlacklistUpdateUrl(crx_url)) << crx_url;
590 // Force https (crbug.com/129587).
591 if (!crx_url.SchemeIsSecure()) {
592 url::Replacements<char> replacements;
593 std::string scheme("https");
594 replacements.SetScheme(scheme.c_str(),
595 url::Component(0, scheme.size()));
596 crx_url = crx_url.ReplaceComponents(replacements);
599 scoped_ptr<ExtensionFetch> fetch(
600 new ExtensionFetch(update->extension_id,
601 crx_url,
602 update->package_hash,
603 update->version,
604 fetch_data.request_ids()));
605 FetchUpdatedExtension(fetch.Pass());
608 // If the manifest response included a <daystart> element, we want to save
609 // that value for any extensions which had sent a ping in the request.
610 if (fetch_data.base_url().DomainIs(kGoogleDotCom) &&
611 results->daystart_elapsed_seconds >= 0) {
612 Time day_start =
613 Time::Now() - TimeDelta::FromSeconds(results->daystart_elapsed_seconds);
615 const std::set<std::string>& extension_ids = fetch_data.extension_ids();
616 std::set<std::string>::const_iterator i;
617 for (i = extension_ids.begin(); i != extension_ids.end(); i++) {
618 const std::string& id = *i;
619 ExtensionDownloaderDelegate::PingResult& result = ping_results_[id];
620 result.did_ping = fetch_data.DidPing(id, ManifestFetchData::ROLLCALL);
621 result.day_start = day_start;
625 NotifyExtensionsDownloadFailed(
626 not_updated,
627 fetch_data.request_ids(),
628 ExtensionDownloaderDelegate::NO_UPDATE_AVAILABLE);
631 void ExtensionDownloader::DetermineUpdates(
632 const ManifestFetchData& fetch_data,
633 const UpdateManifest::Results& possible_updates,
634 std::vector<int>* result) {
635 for (size_t i = 0; i < possible_updates.list.size(); i++) {
636 const UpdateManifest::Result* update = &possible_updates.list[i];
637 const std::string& id = update->extension_id;
639 if (!fetch_data.Includes(id)) {
640 VLOG(2) << "Ignoring " << id << " from this manifest";
641 continue;
644 if (VLOG_IS_ON(2)) {
645 if (update->version.empty())
646 VLOG(2) << "manifest indicates " << id << " has no update";
647 else
648 VLOG(2) << "manifest indicates " << id << " latest version is '"
649 << update->version << "'";
652 if (!delegate_->IsExtensionPending(id)) {
653 // If we're not installing pending extension, and the update
654 // version is the same or older than what's already installed,
655 // we don't want it.
656 std::string version;
657 if (!delegate_->GetExtensionExistingVersion(id, &version)) {
658 VLOG(2) << id << " is not installed";
659 continue;
662 VLOG(2) << id << " is at '" << version << "'";
664 // We should skip the version check if update was forced.
665 if (!fetch_data.DidForceUpdate(id)) {
666 Version existing_version(version);
667 Version update_version(update->version);
668 if (!update_version.IsValid() ||
669 update_version.CompareTo(existing_version) <= 0) {
670 continue;
675 // If the update specifies a browser minimum version, do we qualify?
676 if (update->browser_min_version.length() > 0 &&
677 !ExtensionsBrowserClient::Get()->IsMinBrowserVersionSupported(
678 update->browser_min_version)) {
679 // TODO(asargent) - We may want this to show up in the extensions UI
680 // eventually. (http://crbug.com/12547).
681 LOG(WARNING) << "Updated version of extension " << id
682 << " available, but requires chrome version "
683 << update->browser_min_version;
684 continue;
686 VLOG(2) << "will try to update " << id;
687 result->push_back(i);
691 // Begins (or queues up) download of an updated extension.
692 void ExtensionDownloader::FetchUpdatedExtension(
693 scoped_ptr<ExtensionFetch> fetch_data) {
694 if (!fetch_data->url.is_valid()) {
695 // TODO(asargent): This can sometimes be invalid. See crbug.com/130881.
696 LOG(ERROR) << "Invalid URL: '" << fetch_data->url.possibly_invalid_spec()
697 << "' for extension " << fetch_data->id;
698 return;
701 for (RequestQueue<ExtensionFetch>::iterator iter = extensions_queue_.begin();
702 iter != extensions_queue_.end();
703 ++iter) {
704 if (iter->id == fetch_data->id || iter->url == fetch_data->url) {
705 iter->request_ids.insert(fetch_data->request_ids.begin(),
706 fetch_data->request_ids.end());
707 return; // already scheduled
711 if (extensions_queue_.active_request() &&
712 extensions_queue_.active_request()->url == fetch_data->url) {
713 extensions_queue_.active_request()->request_ids.insert(
714 fetch_data->request_ids.begin(), fetch_data->request_ids.end());
715 } else {
716 std::string version;
717 if (extension_cache_ &&
718 extension_cache_->GetExtension(fetch_data->id, NULL, &version) &&
719 version == fetch_data->version) {
720 base::FilePath crx_path;
721 // Now get .crx file path and mark extension as used.
722 extension_cache_->GetExtension(fetch_data->id, &crx_path, &version);
723 NotifyDelegateDownloadFinished(fetch_data.Pass(), crx_path, false);
724 } else {
725 extensions_queue_.ScheduleRequest(fetch_data.Pass());
730 void ExtensionDownloader::NotifyDelegateDownloadFinished(
731 scoped_ptr<ExtensionFetch> fetch_data,
732 const base::FilePath& crx_path,
733 bool file_ownership_passed) {
734 delegate_->OnExtensionDownloadFinished(fetch_data->id,
735 crx_path,
736 file_ownership_passed,
737 fetch_data->url,
738 fetch_data->version,
739 ping_results_[fetch_data->id],
740 fetch_data->request_ids);
741 ping_results_.erase(fetch_data->id);
744 void ExtensionDownloader::CreateExtensionFetcher() {
745 const ExtensionFetch* fetch = extensions_queue_.active_request();
746 extension_fetcher_.reset(net::URLFetcher::Create(
747 kExtensionFetcherId, fetch->url, net::URLFetcher::GET, this));
748 extension_fetcher_->SetRequestContext(request_context_.get());
749 extension_fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
751 int load_flags = net::LOAD_DISABLE_CACHE;
752 bool is_secure = fetch->url.SchemeIsSecure();
753 if (fetch->credentials != ExtensionFetch::CREDENTIALS_COOKIES || !is_secure) {
754 load_flags |= net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES;
756 extension_fetcher_->SetLoadFlags(load_flags);
758 // Download CRX files to a temp file. The blacklist is small and will be
759 // processed in memory, so it is fetched into a string.
760 if (fetch->id != kBlacklistAppID) {
761 extension_fetcher_->SaveResponseToTemporaryFile(
762 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
765 if (fetch->credentials == ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN &&
766 is_secure) {
767 if (access_token_.empty()) {
768 // We should try OAuth2, but we have no token cached. This
769 // ExtensionFetcher will be started once the token fetch is complete,
770 // in either OnTokenFetchSuccess or OnTokenFetchFailure.
771 DCHECK(identity_provider_.get());
772 OAuth2TokenService::ScopeSet webstore_scopes;
773 webstore_scopes.insert(kWebstoreOAuth2Scope);
774 access_token_request_ =
775 identity_provider_->GetTokenService()->StartRequest(
776 identity_provider_->GetActiveAccountId(), webstore_scopes, this);
777 return;
779 extension_fetcher_->AddExtraRequestHeader(
780 base::StringPrintf("%s: Bearer %s",
781 net::HttpRequestHeaders::kAuthorization,
782 access_token_.c_str()));
785 VLOG(2) << "Starting fetch of " << fetch->url << " for " << fetch->id;
786 extension_fetcher_->Start();
789 void ExtensionDownloader::OnCRXFetchComplete(
790 const net::URLFetcher* source,
791 const GURL& url,
792 const net::URLRequestStatus& status,
793 int response_code,
794 const base::TimeDelta& backoff_delay) {
795 ExtensionFetch& active_request = *extensions_queue_.active_request();
796 const std::string& id = active_request.id;
797 if (status.status() == net::URLRequestStatus::SUCCESS &&
798 (response_code == 200 || url.SchemeIsFile())) {
799 RETRY_HISTOGRAM("CrxFetchSuccess",
800 extensions_queue_.active_request_failure_count(),
801 url);
802 base::FilePath crx_path;
803 // Take ownership of the file at |crx_path|.
804 CHECK(source->GetResponseAsFilePath(true, &crx_path));
805 scoped_ptr<ExtensionFetch> fetch_data =
806 extensions_queue_.reset_active_request();
807 if (extension_cache_) {
808 const std::string& version = fetch_data->version;
809 extension_cache_->PutExtension(
811 crx_path,
812 version,
813 base::Bind(&ExtensionDownloader::NotifyDelegateDownloadFinished,
814 weak_ptr_factory_.GetWeakPtr(),
815 base::Passed(&fetch_data)));
816 } else {
817 NotifyDelegateDownloadFinished(fetch_data.Pass(), crx_path, true);
819 } else if (IterateFetchCredentialsAfterFailure(
820 &active_request, status, response_code)) {
821 extensions_queue_.RetryRequest(backoff_delay);
822 } else {
823 const std::set<int>& request_ids = active_request.request_ids;
824 const ExtensionDownloaderDelegate::PingResult& ping = ping_results_[id];
825 VLOG(1) << "Failed to fetch extension '" << url.possibly_invalid_spec()
826 << "' response code:" << response_code;
827 if (ShouldRetryRequest(status, response_code) &&
828 extensions_queue_.active_request_failure_count() < kMaxRetries) {
829 extensions_queue_.RetryRequest(backoff_delay);
830 } else {
831 RETRY_HISTOGRAM("CrxFetchFailure",
832 extensions_queue_.active_request_failure_count(),
833 url);
834 // status.error() is 0 (net::OK) or negative. (See net/base/net_errors.h)
835 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.CrxFetchError", -status.error());
836 delegate_->OnExtensionDownloadFailed(
837 id, ExtensionDownloaderDelegate::CRX_FETCH_FAILED, ping, request_ids);
839 ping_results_.erase(id);
840 extensions_queue_.reset_active_request();
843 extension_fetcher_.reset();
845 // If there are any pending downloads left, start the next one.
846 extensions_queue_.StartNextRequest();
849 void ExtensionDownloader::NotifyExtensionsDownloadFailed(
850 const std::set<std::string>& extension_ids,
851 const std::set<int>& request_ids,
852 ExtensionDownloaderDelegate::Error error) {
853 for (std::set<std::string>::const_iterator it = extension_ids.begin();
854 it != extension_ids.end();
855 ++it) {
856 const ExtensionDownloaderDelegate::PingResult& ping = ping_results_[*it];
857 delegate_->OnExtensionDownloadFailed(*it, error, ping, request_ids);
858 ping_results_.erase(*it);
862 void ExtensionDownloader::NotifyUpdateFound(const std::string& id,
863 const std::string& version) {
864 UpdateDetails updateInfo(id, Version(version));
865 content::NotificationService::current()->Notify(
866 extensions::NOTIFICATION_EXTENSION_UPDATE_FOUND,
867 content::NotificationService::AllBrowserContextsAndSources(),
868 content::Details<UpdateDetails>(&updateInfo));
871 bool ExtensionDownloader::IterateFetchCredentialsAfterFailure(
872 ExtensionFetch* fetch,
873 const net::URLRequestStatus& status,
874 int response_code) {
875 bool auth_failure = status.status() == net::URLRequestStatus::CANCELED ||
876 (status.status() == net::URLRequestStatus::SUCCESS &&
877 (response_code == net::HTTP_UNAUTHORIZED ||
878 response_code == net::HTTP_FORBIDDEN));
879 if (!auth_failure) {
880 return false;
882 // Here we decide what to do next if the server refused to authorize this
883 // fetch.
884 switch (fetch->credentials) {
885 case ExtensionFetch::CREDENTIALS_NONE:
886 if (fetch->url.DomainIs(kGoogleDotCom) && identity_provider_) {
887 fetch->credentials = ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN;
888 } else {
889 fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES;
891 return true;
892 case ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN:
893 fetch->oauth2_attempt_count++;
894 // OAuth2 may fail due to an expired access token, in which case we
895 // should invalidate the token and try again.
896 if (response_code == net::HTTP_UNAUTHORIZED &&
897 fetch->oauth2_attempt_count <= kMaxOAuth2Attempts) {
898 DCHECK(identity_provider_.get());
899 OAuth2TokenService::ScopeSet webstore_scopes;
900 webstore_scopes.insert(kWebstoreOAuth2Scope);
901 identity_provider_->GetTokenService()->InvalidateToken(
902 identity_provider_->GetActiveAccountId(),
903 webstore_scopes,
904 access_token_);
905 access_token_.clear();
906 return true;
908 // Either there is no Gaia identity available, the active identity
909 // doesn't have access to this resource, or the server keeps returning
910 // 401s and we've retried too many times. Fall back on cookies.
911 if (access_token_.empty() || response_code == net::HTTP_FORBIDDEN ||
912 fetch->oauth2_attempt_count > kMaxOAuth2Attempts) {
913 fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES;
914 return true;
916 // Something else is wrong. Time to give up.
917 return false;
918 case ExtensionFetch::CREDENTIALS_COOKIES:
919 if (response_code == net::HTTP_FORBIDDEN) {
920 // Try the next session identity, up to some maximum.
921 return IncrementAuthUserIndex(&fetch->url);
923 return false;
924 default:
925 NOTREACHED();
927 NOTREACHED();
928 return false;
931 void ExtensionDownloader::OnGetTokenSuccess(
932 const OAuth2TokenService::Request* request,
933 const std::string& access_token,
934 const base::Time& expiration_time) {
935 access_token_ = access_token;
936 extension_fetcher_->AddExtraRequestHeader(
937 base::StringPrintf("%s: Bearer %s",
938 net::HttpRequestHeaders::kAuthorization,
939 access_token_.c_str()));
940 extension_fetcher_->Start();
943 void ExtensionDownloader::OnGetTokenFailure(
944 const OAuth2TokenService::Request* request,
945 const GoogleServiceAuthError& error) {
946 // If we fail to get an access token, kick the pending fetch and let it fall
947 // back on cookies.
948 extension_fetcher_->Start();
951 ManifestFetchData* ExtensionDownloader::CreateManifestFetchData(
952 const GURL& update_url,
953 int request_id) {
954 ManifestFetchData::PingMode ping_mode = ManifestFetchData::NO_PING;
955 if (update_url.DomainIs(ping_enabled_domain_.c_str()))
956 ping_mode = ManifestFetchData::PING_WITH_ENABLED_STATE;
957 return new ManifestFetchData(
958 update_url, request_id, brand_code_, manifest_query_params_, ping_mode);
961 } // namespace extensions