1 // Copyright 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 "chrome/browser/component_updater/component_updater_service.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/compiler_specific.h"
14 #include "base/file_util.h"
15 #include "base/files/file_path.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/sequenced_task_runner.h"
21 #include "base/stl_util.h"
22 #include "base/threading/sequenced_worker_pool.h"
23 #include "base/timer/timer.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/component_updater/component_unpacker.h"
26 #include "chrome/browser/component_updater/component_updater_ping_manager.h"
27 #include "chrome/browser/component_updater/component_updater_utils.h"
28 #include "chrome/browser/component_updater/crx_downloader.h"
29 #include "chrome/browser/component_updater/crx_update_item.h"
30 #include "chrome/browser/component_updater/update_checker.h"
31 #include "chrome/browser/component_updater/update_response.h"
32 #include "chrome/common/chrome_version_info.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "content/public/browser/resource_controller.h"
35 #include "content/public/browser/resource_throttle.h"
38 using content::BrowserThread;
40 namespace component_updater {
42 // The component updater is designed to live until process shutdown, so
43 // base::Bind() calls are not refcounted.
47 // Returns true if the |proposed| version is newer than |current| version.
48 bool IsVersionNewer(const Version& current, const std::string& proposed) {
49 Version proposed_ver(proposed);
50 return proposed_ver.IsValid() && current.CompareTo(proposed_ver) < 0;
53 // Returns true if a differential update is available, it has not failed yet,
54 // and the configuration allows it.
55 bool CanTryDiffUpdate(const CrxUpdateItem* update_item,
56 const ComponentUpdateService::Configurator& config) {
57 return HasDiffUpdate(update_item) && !update_item->diff_update_failed &&
58 config.DeltasEnabled();
61 void AppendDownloadMetrics(
62 const std::vector<CrxDownloader::DownloadMetrics>& source,
63 std::vector<CrxDownloader::DownloadMetrics>* destination) {
64 destination->insert(destination->end(), source.begin(), source.end());
69 CrxUpdateItem::CrxUpdateItem()
72 diff_update_failed(false),
76 diff_error_category(0),
81 CrxUpdateItem::~CrxUpdateItem() {
84 CrxComponent::CrxComponent()
85 : installer(NULL), allow_background_download(true) {
88 CrxComponent::~CrxComponent() {
91 CrxComponentInfo::CrxComponentInfo() {
94 CrxComponentInfo::~CrxComponentInfo() {
97 ///////////////////////////////////////////////////////////////////////////////
98 // In charge of blocking url requests until the |crx_id| component has been
99 // updated. This class is touched solely from the IO thread. The UI thread
100 // can post tasks to it via weak pointers. By default the request is blocked
101 // unless the CrxUpdateService calls Unblock().
102 // The lifetime is controlled by Chrome's resource loader so the component
103 // updater cannot touch objects from this class except via weak pointers.
104 class CUResourceThrottle : public content::ResourceThrottle,
105 public base::SupportsWeakPtr<CUResourceThrottle> {
107 explicit CUResourceThrottle(const net::URLRequest* request);
108 virtual ~CUResourceThrottle();
110 // Overriden from ResourceThrottle.
111 virtual void WillStartRequest(bool* defer) OVERRIDE;
112 virtual void WillRedirectRequest(const GURL& new_url, bool* defer) OVERRIDE;
113 virtual const char* GetNameForLogging() const OVERRIDE;
115 // Component updater calls this function via PostTask to unblock the request.
118 typedef std::vector<base::WeakPtr<CUResourceThrottle> > WeakPtrVector;
121 enum State { NEW, BLOCKED, UNBLOCKED };
126 void UnblockResourceThrottle(base::WeakPtr<CUResourceThrottle> rt) {
127 BrowserThread::PostTask(BrowserThread::IO,
129 base::Bind(&CUResourceThrottle::Unblock, rt));
132 void UnblockandReapAllThrottles(CUResourceThrottle::WeakPtrVector* throttles) {
133 CUResourceThrottle::WeakPtrVector::iterator it;
134 for (it = throttles->begin(); it != throttles->end(); ++it)
135 UnblockResourceThrottle(*it);
139 //////////////////////////////////////////////////////////////////////////////
140 // The one and only implementation of the ComponentUpdateService interface. In
141 // charge of running the show. The main method is ProcessPendingItems() which
142 // is called periodically to do the upgrades/installs or the update checks.
143 // An important consideration here is to be as "low impact" as we can to the
144 // rest of the browser, so even if we have many components registered and
145 // eligible for update, we only do one thing at a time with pauses in between
146 // the tasks. Also when we do network requests there is only one |url_fetcher_|
147 // in flight at a time.
148 // There are no locks in this code, the main structure |work_items_| is mutated
149 // only from the UI thread. The unpack and installation is done in a blocking
150 // pool thread. The network requests are done in the IO thread or in the file
152 class CrxUpdateService : public ComponentUpdateService {
154 explicit CrxUpdateService(ComponentUpdateService::Configurator* config);
155 virtual ~CrxUpdateService();
157 // Overrides for ComponentUpdateService.
158 virtual void AddObserver(Observer* observer) OVERRIDE;
159 virtual void RemoveObserver(Observer* observer) OVERRIDE;
160 virtual Status Start() OVERRIDE;
161 virtual Status Stop() OVERRIDE;
162 virtual Status RegisterComponent(const CrxComponent& component) OVERRIDE;
163 virtual Status OnDemandUpdate(const std::string& component_id) OVERRIDE;
164 virtual void GetComponents(
165 std::vector<CrxComponentInfo>* components) OVERRIDE;
166 virtual content::ResourceThrottle* GetOnDemandResourceThrottle(
167 net::URLRequest* request,
168 const std::string& crx_id) OVERRIDE;
170 // Context for a crx download url request.
172 ComponentInstaller* installer;
173 std::vector<uint8> pk_hash;
175 std::string fingerprint;
176 CRXContext() : installer(NULL) {}
187 enum StepDelayInterval {
193 void UpdateCheckComplete(int error,
194 const std::string& error_message,
195 const UpdateResponse::Results& results);
196 void OnUpdateCheckSucceeded(const UpdateResponse::Results& results);
197 void OnUpdateCheckFailed(int error, const std::string& error_message);
199 void DownloadProgress(const std::string& component_id,
200 const CrxDownloader::Result& download_result);
202 void DownloadComplete(scoped_ptr<CRXContext> crx_context,
203 const CrxDownloader::Result& download_result);
205 Status OnDemandUpdateInternal(CrxUpdateItem* item);
207 void ProcessPendingItems();
209 // Find a component that is ready to update.
210 CrxUpdateItem* FindReadyComponent() const;
212 // Prepares the components for an update check and initiates the request.
213 // Returns true if an update check request has been made. Returns false if
214 // no update check was needed or an error occured.
215 bool CheckForUpdates();
217 void UpdateComponent(CrxUpdateItem* workitem);
219 void ScheduleNextRun(StepDelayInterval step_delay);
221 void ParseResponse(const std::string& xml);
223 void Install(scoped_ptr<CRXContext> context, const base::FilePath& crx_path);
225 void EndUnpacking(const std::string& component_id,
226 const base::FilePath& crx_path,
227 ComponentUnpacker::Error error,
230 void DoneInstalling(const std::string& component_id,
231 ComponentUnpacker::Error error,
234 void ChangeItemState(CrxUpdateItem* item, CrxUpdateItem::Status to);
236 size_t ChangeItemStatus(CrxUpdateItem::Status from, CrxUpdateItem::Status to);
238 CrxUpdateItem* FindUpdateItemById(const std::string& id);
240 void NotifyObservers(Observer::Events event, const std::string& id);
242 bool HasOnDemandItems() const;
244 void OnNewResourceThrottle(base::WeakPtr<CUResourceThrottle> rt,
245 const std::string& crx_id);
247 scoped_ptr<ComponentUpdateService::Configurator> config_;
249 scoped_ptr<UpdateChecker> update_checker_;
251 scoped_ptr<PingManager> ping_manager_;
253 scoped_refptr<ComponentUnpacker> unpacker_;
255 scoped_ptr<CrxDownloader> crx_downloader_;
257 // A collection of every work item.
258 typedef std::vector<CrxUpdateItem*> UpdateItems;
259 UpdateItems work_items_;
261 base::OneShotTimer<CrxUpdateService> timer_;
263 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
265 const Version chrome_version_;
269 ObserverList<Observer> observer_list_;
271 DISALLOW_COPY_AND_ASSIGN(CrxUpdateService);
274 //////////////////////////////////////////////////////////////////////////////
276 CrxUpdateService::CrxUpdateService(ComponentUpdateService::Configurator* config)
279 new PingManager(config->PingUrl(), config->RequestContext())),
280 blocking_task_runner_(
281 BrowserThread::GetBlockingPool()->
282 GetSequencedTaskRunnerWithShutdownBehavior(
283 BrowserThread::GetBlockingPool()->GetSequenceToken(),
284 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)),
285 chrome_version_(chrome::VersionInfo().Version()),
289 CrxUpdateService::~CrxUpdateService() {
290 // Because we are a singleton, at this point only the UI thread should be
291 // alive, this simplifies the management of the work that could be in
292 // flight in other threads.
294 STLDeleteElements(&work_items_);
297 void CrxUpdateService::AddObserver(Observer* observer) {
298 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
299 observer_list_.AddObserver(observer);
302 void CrxUpdateService::RemoveObserver(Observer* observer) {
303 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
304 observer_list_.RemoveObserver(observer);
307 ComponentUpdateService::Status CrxUpdateService::Start() {
308 // Note that RegisterComponent will call Start() when the first
309 // component is registered, so it can be called twice. This way
310 // we avoid scheduling the timer if there is no work to do.
311 VLOG(1) << "CrxUpdateService starting up";
313 if (work_items_.empty())
316 NotifyObservers(Observer::COMPONENT_UPDATER_STARTED, "");
318 VLOG(1) << "First update attempt will take place in "
319 << config_->InitialDelay() << " seconds";
320 timer_.Start(FROM_HERE,
321 base::TimeDelta::FromSeconds(config_->InitialDelay()),
323 &CrxUpdateService::ProcessPendingItems);
327 // Stop the main check + update loop. In flight operations will be
329 ComponentUpdateService::Status CrxUpdateService::Stop() {
330 VLOG(1) << "CrxUpdateService stopping";
336 bool CrxUpdateService::HasOnDemandItems() const {
339 static bool IsOnDemand(CrxUpdateItem* item) { return item->on_demand; }
341 return std::find_if(work_items_.begin(),
343 Helper::IsOnDemand) != work_items_.end();
346 // This function sets the timer which will call ProcessPendingItems() or
347 // ProcessRequestedItem() if there is an on_demand item. There
348 // are three kinds of waits:
349 // - a short delay, when there is immediate work to be done.
350 // - a medium delay, when there are updates to be applied within the current
351 // update cycle, or there are components that are still unchecked.
352 // - a long delay when a full check/update cycle has completed for all
354 void CrxUpdateService::ScheduleNextRun(StepDelayInterval step_delay) {
355 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
356 DCHECK(!update_checker_);
357 CHECK(!timer_.IsRunning());
358 // It could be the case that Stop() had been called while a url request
359 // or unpacking was in flight, if so we arrive here but |running_| is
360 // false. In that case do not loop again.
364 // Keep the delay short if in the middle of an update (step_delay),
365 // or there are new requested_work_items_ that have not been processed yet.
366 int64 delay_seconds = 0;
367 if (!HasOnDemandItems()) {
368 switch (step_delay) {
369 case kStepDelayShort:
370 delay_seconds = config_->StepDelay();
372 case kStepDelayMedium:
373 delay_seconds = config_->StepDelayMedium();
376 delay_seconds = config_->NextCheckDelay();
380 delay_seconds = config_->StepDelay();
383 if (step_delay != kStepDelayShort) {
384 NotifyObservers(Observer::COMPONENT_UPDATER_SLEEPING, "");
386 // Zero is only used for unit tests.
387 if (0 == delay_seconds)
391 VLOG(1) << "Scheduling next run to occur in " << delay_seconds << " seconds";
392 timer_.Start(FROM_HERE,
393 base::TimeDelta::FromSeconds(delay_seconds),
395 &CrxUpdateService::ProcessPendingItems);
398 // Given a extension-like component id, find the associated component.
399 CrxUpdateItem* CrxUpdateService::FindUpdateItemById(const std::string& id) {
400 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
401 CrxUpdateItem::FindById finder(id);
402 UpdateItems::iterator it =
403 std::find_if(work_items_.begin(), work_items_.end(), finder);
404 return it != work_items_.end() ? *it : NULL;
407 // Changes a component's status, clearing on_demand and firing notifications as
408 // necessary. By convention, this is the only function that can change a
409 // CrxUpdateItem's |status|.
410 // TODO(waffles): Do we want to add DCHECKS for valid state transitions here?
411 void CrxUpdateService::ChangeItemState(CrxUpdateItem* item,
412 CrxUpdateItem::Status to) {
413 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
414 if (to == CrxUpdateItem::kNoUpdate || to == CrxUpdateItem::kUpdated ||
415 to == CrxUpdateItem::kUpToDate) {
416 item->on_demand = false;
422 case CrxUpdateItem::kCanUpdate:
423 NotifyObservers(Observer::COMPONENT_UPDATE_FOUND, item->id);
425 case CrxUpdateItem::kUpdatingDiff:
426 case CrxUpdateItem::kUpdating:
427 NotifyObservers(Observer::COMPONENT_UPDATE_READY, item->id);
429 case CrxUpdateItem::kUpdated:
430 NotifyObservers(Observer::COMPONENT_UPDATED, item->id);
432 case CrxUpdateItem::kUpToDate:
433 case CrxUpdateItem::kNoUpdate:
434 NotifyObservers(Observer::COMPONENT_NOT_UPDATED, item->id);
436 case CrxUpdateItem::kNew:
437 case CrxUpdateItem::kChecking:
438 case CrxUpdateItem::kDownloading:
439 case CrxUpdateItem::kDownloadingDiff:
440 case CrxUpdateItem::kLastStatus:
441 // No notification for these states.
445 // Free possible pending network requests.
446 if ((to == CrxUpdateItem::kUpdated) || (to == CrxUpdateItem::kUpToDate) ||
447 (to == CrxUpdateItem::kNoUpdate)) {
448 UnblockandReapAllThrottles(&item->throttles);
452 // Changes all the components in |work_items_| that have |from| status to
453 // |to| status and returns how many have been changed.
454 size_t CrxUpdateService::ChangeItemStatus(CrxUpdateItem::Status from,
455 CrxUpdateItem::Status to) {
456 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
458 for (UpdateItems::iterator it = work_items_.begin();
459 it != work_items_.end();
461 CrxUpdateItem* item = *it;
462 if (item->status == from) {
463 ChangeItemState(item, to);
470 // Adds a component to be checked for upgrades. If the component exists it
471 // it will be replaced and the return code is kReplaced.
472 ComponentUpdateService::Status CrxUpdateService::RegisterComponent(
473 const CrxComponent& component) {
474 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
475 if (component.pk_hash.empty() || !component.version.IsValid() ||
476 !component.installer)
479 std::string id(GetCrxComponentID(component));
480 CrxUpdateItem* uit = FindUpdateItemById(id);
482 uit->component = component;
486 uit = new CrxUpdateItem;
488 uit->component = component;
490 work_items_.push_back(uit);
491 // If this is the first component registered we call Start to
492 // schedule the first timer.
493 if (running_ && (work_items_.size() == 1))
499 // Start the process of checking for an update, for a particular component
500 // that was previously registered.
501 // |component_id| is a value returned from GetCrxComponentID().
502 ComponentUpdateService::Status CrxUpdateService::OnDemandUpdate(
503 const std::string& component_id) {
504 return OnDemandUpdateInternal(FindUpdateItemById(component_id));
507 ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateInternal(
508 CrxUpdateItem* uit) {
512 // Check if the request is too soon.
513 base::TimeDelta delta = base::Time::Now() - uit->last_check;
514 if (delta < base::TimeDelta::FromSeconds(config_->OnDemandDelay()))
517 switch (uit->status) {
518 // If the item is already in the process of being updated, there is
519 // no point in this call, so return kInProgress.
520 case CrxUpdateItem::kChecking:
521 case CrxUpdateItem::kCanUpdate:
522 case CrxUpdateItem::kDownloadingDiff:
523 case CrxUpdateItem::kDownloading:
524 case CrxUpdateItem::kUpdatingDiff:
525 case CrxUpdateItem::kUpdating:
527 // Otherwise the item was already checked a while back (or it is new),
528 // set its status to kNew to give it a slightly higher priority.
529 case CrxUpdateItem::kNew:
530 case CrxUpdateItem::kUpdated:
531 case CrxUpdateItem::kUpToDate:
532 case CrxUpdateItem::kNoUpdate:
533 ChangeItemState(uit, CrxUpdateItem::kNew);
534 uit->on_demand = true;
536 case CrxUpdateItem::kLastStatus:
537 NOTREACHED() << uit->status;
540 // In case the current delay is long, set the timer to a shorter value
541 // to get the ball rolling.
542 if (timer_.IsRunning()) {
544 timer_.Start(FROM_HERE,
545 base::TimeDelta::FromSeconds(config_->StepDelay()),
547 &CrxUpdateService::ProcessPendingItems);
553 void CrxUpdateService::GetComponents(
554 std::vector<CrxComponentInfo>* components) {
555 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
556 for (UpdateItems::const_iterator it = work_items_.begin();
557 it != work_items_.end();
559 const CrxUpdateItem* item = *it;
560 CrxComponentInfo info;
561 info.id = GetCrxComponentID(item->component);
562 info.version = item->component.version.GetString();
563 info.name = item->component.name;
564 components->push_back(info);
568 // This is the main loop of the component updater. It updates one component
569 // at a time if updates are available. Otherwise, it does an update check or
570 // takes a long sleep until the loop runs again.
571 void CrxUpdateService::ProcessPendingItems() {
572 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
574 CrxUpdateItem* ready_upgrade = FindReadyComponent();
576 UpdateComponent(ready_upgrade);
580 if (!CheckForUpdates())
581 ScheduleNextRun(kStepDelayLong);
584 CrxUpdateItem* CrxUpdateService::FindReadyComponent() const {
587 static bool IsReadyOnDemand(CrxUpdateItem* item) {
588 return item->on_demand && IsReady(item);
590 static bool IsReady(CrxUpdateItem* item) {
591 return item->status == CrxUpdateItem::kCanUpdate;
595 std::vector<CrxUpdateItem*>::const_iterator it = std::find_if(
596 work_items_.begin(), work_items_.end(), Helper::IsReadyOnDemand);
597 if (it != work_items_.end())
599 it = std::find_if(work_items_.begin(), work_items_.end(), Helper::IsReady);
600 if (it != work_items_.end())
605 // Prepares the components for an update check and initiates the request.
606 // On demand components are always included in the update check request.
607 // Otherwise, only include components that have not been checked recently.
608 bool CrxUpdateService::CheckForUpdates() {
609 const base::TimeDelta minimum_recheck_wait_time =
610 base::TimeDelta::FromSeconds(config_->MinimumReCheckWait());
611 const base::Time now(base::Time::Now());
613 std::vector<CrxUpdateItem*> items_to_check;
614 for (size_t i = 0; i != work_items_.size(); ++i) {
615 CrxUpdateItem* item = work_items_[i];
616 DCHECK(item->status == CrxUpdateItem::kNew ||
617 item->status == CrxUpdateItem::kNoUpdate ||
618 item->status == CrxUpdateItem::kUpToDate ||
619 item->status == CrxUpdateItem::kUpdated);
621 const base::TimeDelta time_since_last_checked(now - item->last_check);
623 if (!item->on_demand &&
624 time_since_last_checked < minimum_recheck_wait_time) {
625 VLOG(1) << "Skipping check for component update: id=" << item->id
626 << ", time_since_last_checked="
627 << time_since_last_checked.InSeconds()
628 << " seconds: too soon to check for an update";
632 VLOG(1) << "Scheduling update check for component id=" << item->id
633 << ", time_since_last_checked="
634 << time_since_last_checked.InSeconds() << " seconds";
636 ChangeItemState(item, CrxUpdateItem::kChecking);
638 item->last_check = now;
639 item->crx_urls.clear();
640 item->crx_diffurls.clear();
641 item->previous_version = item->component.version;
642 item->next_version = Version();
643 item->previous_fp = item->component.fingerprint;
644 item->next_fp.clear();
645 item->diff_update_failed = false;
646 item->error_category = 0;
647 item->error_code = 0;
648 item->extra_code1 = 0;
649 item->diff_error_category = 0;
650 item->diff_error_code = 0;
651 item->diff_extra_code1 = 0;
652 item->download_metrics.clear();
654 items_to_check.push_back(item);
657 if (items_to_check.empty())
661 UpdateChecker::Create(config_->UpdateUrl(),
662 config_->RequestContext(),
663 base::Bind(&CrxUpdateService::UpdateCheckComplete,
664 base::Unretained(this))).Pass();
665 return update_checker_->CheckForUpdates(items_to_check,
666 config_->ExtraRequestParams());
669 void CrxUpdateService::UpdateComponent(CrxUpdateItem* workitem) {
670 scoped_ptr<CRXContext> crx_context(new CRXContext);
671 crx_context->pk_hash = workitem->component.pk_hash;
672 crx_context->id = workitem->id;
673 crx_context->installer = workitem->component.installer;
674 crx_context->fingerprint = workitem->next_fp;
675 const std::vector<GURL>* urls = NULL;
676 bool allow_background_download = false;
677 if (CanTryDiffUpdate(workitem, *config_)) {
678 urls = &workitem->crx_diffurls;
679 ChangeItemState(workitem, CrxUpdateItem::kDownloadingDiff);
681 // Background downloads are enabled only for selected components and
682 // only for full downloads (see issue 340448).
683 allow_background_download = workitem->component.allow_background_download;
684 urls = &workitem->crx_urls;
685 ChangeItemState(workitem, CrxUpdateItem::kDownloading);
688 // On demand component updates are always downloaded in foreground.
689 const bool is_background_download = !workitem->on_demand &&
690 allow_background_download &&
691 config_->UseBackgroundDownloader();
693 crx_downloader_.reset(CrxDownloader::Create(is_background_download,
694 config_->RequestContext(),
695 blocking_task_runner_));
696 crx_downloader_->set_progress_callback(
697 base::Bind(&CrxUpdateService::DownloadProgress,
698 base::Unretained(this),
700 crx_downloader_->StartDownload(*urls,
701 base::Bind(&CrxUpdateService::DownloadComplete,
702 base::Unretained(this),
703 base::Passed(&crx_context)));
706 void CrxUpdateService::UpdateCheckComplete(
708 const std::string& error_message,
709 const UpdateResponse::Results& results) {
710 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
711 update_checker_.reset();
713 OnUpdateCheckSucceeded(results);
715 OnUpdateCheckFailed(error, error_message);
718 // Handles a valid Omaha update check response by matching the results with
719 // the registered components which were checked for updates.
720 // If updates are found, prepare the components for the actual version upgrade.
721 // One of these components will be drafted for the upgrade next time
722 // ProcessPendingItems is called.
723 void CrxUpdateService::OnUpdateCheckSucceeded(
724 const UpdateResponse::Results& results) {
725 size_t num_updates_pending = 0;
726 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
727 VLOG(1) << "Update check succeeded.";
728 std::vector<UpdateResponse::Result>::const_iterator it;
729 for (it = results.list.begin(); it != results.list.end(); ++it) {
730 CrxUpdateItem* crx = FindUpdateItemById(it->extension_id);
734 if (crx->status != CrxUpdateItem::kChecking) {
736 continue; // Not updating this component now.
739 if (it->manifest.version.empty()) {
740 // No version means no update available.
741 ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
742 VLOG(1) << "No update available for component: " << crx->id;
746 if (!IsVersionNewer(crx->component.version, it->manifest.version)) {
747 // The component is up to date.
748 ChangeItemState(crx, CrxUpdateItem::kUpToDate);
749 VLOG(1) << "Component already up-to-date: " << crx->id;
753 if (!it->manifest.browser_min_version.empty()) {
754 if (IsVersionNewer(chrome_version_, it->manifest.browser_min_version)) {
755 // The component is not compatible with this Chrome version.
756 VLOG(1) << "Ignoring incompatible component: " << crx->id;
757 ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
762 if (it->manifest.packages.size() != 1) {
763 // Assume one and only one package per component.
764 VLOG(1) << "Ignoring multiple packages for component: " << crx->id;
765 ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
769 // Parse the members of the result and queue an upgrade for this component.
770 crx->next_version = Version(it->manifest.version);
772 VLOG(1) << "Update found for component: " << crx->id;
774 typedef UpdateResponse::Result::Manifest::Package Package;
775 const Package& package(it->manifest.packages[0]);
776 crx->next_fp = package.fingerprint;
778 // Resolve the urls by combining the base urls with the package names.
779 for (size_t i = 0; i != it->crx_urls.size(); ++i) {
780 const GURL url(it->crx_urls[i].Resolve(package.name));
782 crx->crx_urls.push_back(url);
784 for (size_t i = 0; i != it->crx_diffurls.size(); ++i) {
785 const GURL url(it->crx_diffurls[i].Resolve(package.namediff));
787 crx->crx_diffurls.push_back(url);
790 ChangeItemState(crx, CrxUpdateItem::kCanUpdate);
791 ++num_updates_pending;
794 // All components that are not included in the update response are
795 // considered up to date.
796 ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate);
798 // If there are updates pending we do a short wait, otherwise we take
799 // a longer delay until we check the components again.
800 ScheduleNextRun(num_updates_pending > 0 ? kStepDelayShort : kStepDelayLong);
803 void CrxUpdateService::OnUpdateCheckFailed(int error,
804 const std::string& error_message) {
805 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
808 ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kNoUpdate);
809 DCHECK_GT(count, 0ul);
810 VLOG(1) << "Update check failed.";
811 ScheduleNextRun(kStepDelayLong);
814 // Called when progress is being made downloading a CRX. The progress may
815 // not monotonically increase due to how the CRX downloader switches between
816 // different downloaders and fallback urls.
817 void CrxUpdateService::DownloadProgress(
818 const std::string& component_id,
819 const CrxDownloader::Result& download_result) {
820 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
821 NotifyObservers(Observer::COMPONENT_UPDATE_DOWNLOADING, component_id);
824 // Called when the CRX package has been downloaded to a temporary location.
825 // Here we fire the notifications and schedule the component-specific installer
826 // to be called in the file thread.
827 void CrxUpdateService::DownloadComplete(
828 scoped_ptr<CRXContext> crx_context,
829 const CrxDownloader::Result& download_result) {
830 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
832 CrxUpdateItem* crx = FindUpdateItemById(crx_context->id);
833 DCHECK(crx->status == CrxUpdateItem::kDownloadingDiff ||
834 crx->status == CrxUpdateItem::kDownloading);
836 AppendDownloadMetrics(crx_downloader_->download_metrics(),
837 &crx->download_metrics);
839 crx_downloader_.reset();
841 if (download_result.error) {
842 if (crx->status == CrxUpdateItem::kDownloadingDiff) {
843 crx->diff_error_category = kNetworkError;
844 crx->diff_error_code = download_result.error;
845 crx->diff_update_failed = true;
846 size_t count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff,
847 CrxUpdateItem::kCanUpdate);
848 DCHECK_EQ(count, 1ul);
850 ScheduleNextRun(kStepDelayShort);
853 crx->error_category = kNetworkError;
854 crx->error_code = download_result.error;
856 ChangeItemStatus(CrxUpdateItem::kDownloading, CrxUpdateItem::kNoUpdate);
857 DCHECK_EQ(count, 1ul);
859 // At this point, since both the differential and the full downloads failed,
860 // the update for this component has finished with an error.
861 ping_manager_->OnUpdateComplete(crx);
863 // Move on to the next update, if there is one available.
864 ScheduleNextRun(kStepDelayMedium);
867 if (crx->status == CrxUpdateItem::kDownloadingDiff) {
868 count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff,
869 CrxUpdateItem::kUpdatingDiff);
871 count = ChangeItemStatus(CrxUpdateItem::kDownloading,
872 CrxUpdateItem::kUpdating);
874 DCHECK_EQ(count, 1ul);
876 // Why unretained? See comment at top of file.
877 blocking_task_runner_->PostDelayedTask(
879 base::Bind(&CrxUpdateService::Install,
880 base::Unretained(this),
881 base::Passed(&crx_context),
882 download_result.response),
883 base::TimeDelta::FromMilliseconds(config_->StepDelay()));
887 // Install consists of digital signature verification, unpacking and then
888 // calling the component specific installer. All that is handled by the
889 // |unpacker_|. If there is an error this function is in charge of deleting
890 // the files created.
891 void CrxUpdateService::Install(scoped_ptr<CRXContext> context,
892 const base::FilePath& crx_path) {
893 // This function owns the file at |crx_path| and the |context| object.
894 unpacker_ = new ComponentUnpacker(context->pk_hash,
896 context->fingerprint,
898 config_->InProcess(),
899 blocking_task_runner_);
900 unpacker_->Unpack(base::Bind(&CrxUpdateService::EndUnpacking,
901 base::Unretained(this),
906 void CrxUpdateService::EndUnpacking(const std::string& component_id,
907 const base::FilePath& crx_path,
908 ComponentUnpacker::Error error,
909 int extended_error) {
910 if (!DeleteFileAndEmptyParentDirectory(crx_path))
911 NOTREACHED() << crx_path.value();
912 BrowserThread::PostDelayedTask(
915 base::Bind(&CrxUpdateService::DoneInstalling,
916 base::Unretained(this),
920 base::TimeDelta::FromMilliseconds(config_->StepDelay()));
921 // Reset the unpacker last, otherwise we free our own arguments.
925 // Installation has been completed. Adjust the component status and
926 // schedule the next check. Schedule a short delay before trying the full
927 // update when the differential update failed.
928 void CrxUpdateService::DoneInstalling(const std::string& component_id,
929 ComponentUnpacker::Error error,
931 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
933 ErrorCategory error_category = kErrorNone;
935 case ComponentUnpacker::kNone:
937 case ComponentUnpacker::kInstallerError:
938 error_category = kInstallError;
941 error_category = kUnpackError;
945 const bool is_success = error == ComponentUnpacker::kNone;
947 CrxUpdateItem* item = FindUpdateItemById(component_id);
948 if (item->status == CrxUpdateItem::kUpdatingDiff && !is_success) {
949 item->diff_error_category = error_category;
950 item->diff_error_code = error;
951 item->diff_extra_code1 = extra_code;
952 item->diff_update_failed = true;
953 size_t count = ChangeItemStatus(CrxUpdateItem::kUpdatingDiff,
954 CrxUpdateItem::kCanUpdate);
955 DCHECK_EQ(count, 1ul);
956 ScheduleNextRun(kStepDelayShort);
961 ChangeItemState(item, CrxUpdateItem::kUpdated);
962 item->component.version = item->next_version;
963 item->component.fingerprint = item->next_fp;
965 ChangeItemState(item, CrxUpdateItem::kNoUpdate);
966 item->error_category = error_category;
967 item->error_code = error;
968 item->extra_code1 = extra_code;
971 ping_manager_->OnUpdateComplete(item);
973 // Move on to the next update, if there is one available.
974 ScheduleNextRun(kStepDelayMedium);
977 void CrxUpdateService::NotifyObservers(Observer::Events event,
978 const std::string& id) {
979 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
980 FOR_EACH_OBSERVER(Observer, observer_list_, OnEvent(event, id));
983 content::ResourceThrottle* CrxUpdateService::GetOnDemandResourceThrottle(
984 net::URLRequest* request,
985 const std::string& crx_id) {
986 // We give the raw pointer to the caller, who will delete it at will
987 // and we keep for ourselves a weak pointer to it so we can post tasks
988 // from the UI thread without having to track lifetime directly.
989 CUResourceThrottle* rt = new CUResourceThrottle(request);
990 BrowserThread::PostTask(BrowserThread::UI,
992 base::Bind(&CrxUpdateService::OnNewResourceThrottle,
993 base::Unretained(this),
999 void CrxUpdateService::OnNewResourceThrottle(
1000 base::WeakPtr<CUResourceThrottle> rt,
1001 const std::string& crx_id) {
1002 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1003 // Check if we can on-demand update, else unblock the request anyway.
1004 CrxUpdateItem* item = FindUpdateItemById(crx_id);
1005 Status status = OnDemandUpdateInternal(item);
1006 if (status == kOk || status == kInProgress) {
1007 item->throttles.push_back(rt);
1010 UnblockResourceThrottle(rt);
1013 ///////////////////////////////////////////////////////////////////////////////
1015 CUResourceThrottle::CUResourceThrottle(const net::URLRequest* request)
1017 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1020 CUResourceThrottle::~CUResourceThrottle() {
1021 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1024 void CUResourceThrottle::WillStartRequest(bool* defer) {
1025 if (state_ != UNBLOCKED) {
1033 void CUResourceThrottle::WillRedirectRequest(const GURL& new_url, bool* defer) {
1034 WillStartRequest(defer);
1037 const char* CUResourceThrottle::GetNameForLogging() const {
1038 return "ComponentUpdateResourceThrottle";
1041 void CUResourceThrottle::Unblock() {
1042 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1043 if (state_ == BLOCKED)
1044 controller()->Resume();
1048 // The component update factory. Using the component updater as a singleton
1049 // is the job of the browser process.
1050 ComponentUpdateService* ComponentUpdateServiceFactory(
1051 ComponentUpdateService::Configurator* config) {
1053 return new CrxUpdateService(config);
1056 } // namespace component_updater