1 // Copyright 2014 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 "components/component_updater/component_updater_service.h"
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/macros.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/message_loop/message_loop_proxy.h"
22 #include "base/observer_list.h"
23 #include "base/sequenced_task_runner.h"
24 #include "base/stl_util.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "base/threading/thread_checker.h"
27 #include "base/timer/timer.h"
28 #include "components/component_updater/component_patcher_operation.h"
29 #include "components/component_updater/component_unpacker.h"
30 #include "components/component_updater/component_updater_configurator.h"
31 #include "components/component_updater/component_updater_ping_manager.h"
32 #include "components/component_updater/component_updater_utils.h"
33 #include "components/component_updater/crx_downloader.h"
34 #include "components/component_updater/crx_update_item.h"
35 #include "components/component_updater/update_checker.h"
36 #include "components/component_updater/update_response.h"
39 namespace component_updater
{
41 // The component updater is designed to live until process shutdown, so
42 // base::Bind() calls are not refcounted.
46 // Returns true if the |proposed| version is newer than |current| version.
47 bool IsVersionNewer(const Version
& current
, const std::string
& proposed
) {
48 Version
proposed_ver(proposed
);
49 return proposed_ver
.IsValid() && current
.CompareTo(proposed_ver
) < 0;
52 // Returns true if a differential update is available, it has not failed yet,
53 // and the configuration allows it.
54 bool CanTryDiffUpdate(const CrxUpdateItem
* update_item
,
55 const Configurator
& config
) {
56 return HasDiffUpdate(update_item
) && !update_item
->diff_update_failed
&&
57 config
.DeltasEnabled();
60 void AppendDownloadMetrics(
61 const std::vector
<CrxDownloader::DownloadMetrics
>& source
,
62 std::vector
<CrxDownloader::DownloadMetrics
>* destination
) {
63 destination
->insert(destination
->end(), source
.begin(), source
.end());
68 CrxUpdateItem::CrxUpdateItem()
71 diff_update_failed(false),
75 diff_error_category(0),
80 CrxUpdateItem::~CrxUpdateItem() {
83 CrxComponent::CrxComponent()
84 : installer(NULL
), allow_background_download(true) {
87 CrxComponent::~CrxComponent() {
90 //////////////////////////////////////////////////////////////////////////////
91 // The one and only implementation of the ComponentUpdateService interface. In
92 // charge of running the show. The main method is ProcessPendingItems() which
93 // is called periodically to do the upgrades/installs or the update checks.
94 // An important consideration here is to be as "low impact" as we can to the
95 // rest of the browser, so even if we have many components registered and
96 // eligible for update, we only do one thing at a time with pauses in between
97 // the tasks. Also when we do network requests there is only one |url_fetcher_|
98 // in flight at a time.
99 // There are no locks in this code, the main structure |work_items_| is mutated
100 // only from the main thread. The unpack and installation is done in a blocking
101 // pool thread. The network requests are done in the IO thread or in the file
103 class CrxUpdateService
: public ComponentUpdateService
, public OnDemandUpdater
{
105 explicit CrxUpdateService(Configurator
* config
);
106 ~CrxUpdateService() override
;
108 // Overrides for ComponentUpdateService.
109 void AddObserver(Observer
* observer
) override
;
110 void RemoveObserver(Observer
* observer
) override
;
111 Status
Start() override
;
112 Status
Stop() override
;
113 Status
RegisterComponent(const CrxComponent
& component
) override
;
114 std::vector
<std::string
> GetComponentIDs() const override
;
115 OnDemandUpdater
& GetOnDemandUpdater() override
;
116 void MaybeThrottle(const std::string
& crx_id
,
117 const base::Closure
& callback
) override
;
118 scoped_refptr
<base::SequencedTaskRunner
> GetSequencedTaskRunner() override
;
120 // Context for a crx download url request.
122 ComponentInstaller
* installer
;
123 std::vector
<uint8_t> pk_hash
;
125 std::string fingerprint
;
126 CRXContext() : installer(NULL
) {}
137 enum StepDelayInterval
{
143 // Overrides for ComponentUpdateService.
144 bool GetComponentDetails(const std::string
& component_id
,
145 CrxUpdateItem
* item
) const override
;
147 // Overrides for OnDemandUpdater.
148 Status
OnDemandUpdate(const std::string
& component_id
) override
;
150 void UpdateCheckComplete(const GURL
& original_url
,
152 const std::string
& error_message
,
153 const UpdateResponse::Results
& results
);
154 void OnUpdateCheckSucceeded(const UpdateResponse::Results
& results
);
155 void OnUpdateCheckFailed(int error
, const std::string
& error_message
);
157 void DownloadProgress(const std::string
& component_id
,
158 const CrxDownloader::Result
& download_result
);
160 void DownloadComplete(scoped_ptr
<CRXContext
> crx_context
,
161 const CrxDownloader::Result
& download_result
);
163 Status
OnDemandUpdateInternal(CrxUpdateItem
* item
);
164 Status
OnDemandUpdateWithCooldown(CrxUpdateItem
* item
);
166 void ProcessPendingItems();
168 // Find a component that is ready to update.
169 CrxUpdateItem
* FindReadyComponent() const;
171 // Prepares the components for an update check and initiates the request.
172 // Returns true if an update check request has been made. Returns false if
173 // no update check was needed or an error occured.
174 bool CheckForUpdates();
176 void UpdateComponent(CrxUpdateItem
* workitem
);
178 void ScheduleNextRun(StepDelayInterval step_delay
);
180 void ParseResponse(const std::string
& xml
);
182 void Install(scoped_ptr
<CRXContext
> context
, const base::FilePath
& crx_path
);
184 void EndUnpacking(const std::string
& component_id
,
185 const base::FilePath
& crx_path
,
186 ComponentUnpacker::Error error
,
189 void DoneInstalling(const std::string
& component_id
,
190 ComponentUnpacker::Error error
,
193 void ChangeItemState(CrxUpdateItem
* item
, CrxUpdateItem::Status to
);
195 size_t ChangeItemStatus(CrxUpdateItem::Status from
, CrxUpdateItem::Status to
);
197 CrxUpdateItem
* FindUpdateItemById(const std::string
& id
) const;
199 void NotifyObservers(Observer::Events event
, const std::string
& id
);
201 bool HasOnDemandItems() const;
203 Status
GetServiceStatus(const CrxUpdateItem::Status status
);
205 scoped_ptr
<Configurator
> config_
;
207 scoped_ptr
<UpdateChecker
> update_checker_
;
209 scoped_ptr
<PingManager
> ping_manager_
;
211 scoped_refptr
<ComponentUnpacker
> unpacker_
;
213 scoped_ptr
<CrxDownloader
> crx_downloader_
;
215 // A collection of every work item.
216 typedef std::vector
<CrxUpdateItem
*> UpdateItems
;
217 UpdateItems work_items_
;
219 base::OneShotTimer
<CrxUpdateService
> timer_
;
221 base::ThreadChecker thread_checker_
;
223 // Used to post responses back to the main thread.
224 scoped_refptr
<base::SingleThreadTaskRunner
> main_task_runner_
;
226 scoped_refptr
<base::SequencedTaskRunner
> blocking_task_runner_
;
230 ObserverList
<Observer
> observer_list_
;
232 DISALLOW_COPY_AND_ASSIGN(CrxUpdateService
);
235 //////////////////////////////////////////////////////////////////////////////
237 CrxUpdateService::CrxUpdateService(Configurator
* config
)
239 ping_manager_(new PingManager(*config
)),
240 main_task_runner_(base::MessageLoopProxy::current()),
241 blocking_task_runner_(config
->GetSequencedTaskRunner()),
245 CrxUpdateService::~CrxUpdateService() {
246 // Because we are a singleton, at this point only the main thread should be
247 // alive, this simplifies the management of the work that could be in
248 // flight in other threads.
250 STLDeleteElements(&work_items_
);
253 void CrxUpdateService::AddObserver(Observer
* observer
) {
254 DCHECK(thread_checker_
.CalledOnValidThread());
255 observer_list_
.AddObserver(observer
);
258 void CrxUpdateService::RemoveObserver(Observer
* observer
) {
259 DCHECK(thread_checker_
.CalledOnValidThread());
260 observer_list_
.RemoveObserver(observer
);
263 ComponentUpdateService::Status
CrxUpdateService::Start() {
264 // Note that RegisterComponent will call Start() when the first
265 // component is registered, so it can be called twice. This way
266 // we avoid scheduling the timer if there is no work to do.
267 VLOG(1) << "CrxUpdateService starting up";
269 if (work_items_
.empty())
272 NotifyObservers(Observer::COMPONENT_UPDATER_STARTED
, "");
274 VLOG(1) << "First update attempt will take place in "
275 << config_
->InitialDelay() << " seconds";
276 timer_
.Start(FROM_HERE
,
277 base::TimeDelta::FromSeconds(config_
->InitialDelay()),
279 &CrxUpdateService::ProcessPendingItems
);
283 // Stop the main check + update loop. In flight operations will be
285 ComponentUpdateService::Status
CrxUpdateService::Stop() {
286 VLOG(1) << "CrxUpdateService stopping";
292 bool CrxUpdateService::HasOnDemandItems() const {
295 static bool IsOnDemand(CrxUpdateItem
* item
) { return item
->on_demand
; }
297 return std::find_if(work_items_
.begin(),
299 Helper::IsOnDemand
) != work_items_
.end();
302 // This function sets the timer which will call ProcessPendingItems() or
303 // ProcessRequestedItem() if there is an on_demand item. There
304 // are three kinds of waits:
305 // - a short delay, when there is immediate work to be done.
306 // - a medium delay, when there are updates to be applied within the current
307 // update cycle, or there are components that are still unchecked.
308 // - a long delay when a full check/update cycle has completed for all
310 void CrxUpdateService::ScheduleNextRun(StepDelayInterval step_delay
) {
311 DCHECK(thread_checker_
.CalledOnValidThread());
312 DCHECK(!update_checker_
);
313 CHECK(!timer_
.IsRunning());
314 // It could be the case that Stop() had been called while a url request
315 // or unpacking was in flight, if so we arrive here but |running_| is
316 // false. In that case do not loop again.
320 // Keep the delay short if in the middle of an update (step_delay),
321 // or there are new requested_work_items_ that have not been processed yet.
322 int64_t delay_seconds
= 0;
323 if (!HasOnDemandItems()) {
324 switch (step_delay
) {
325 case kStepDelayShort
:
326 delay_seconds
= config_
->StepDelay();
328 case kStepDelayMedium
:
329 delay_seconds
= config_
->StepDelayMedium();
332 delay_seconds
= config_
->NextCheckDelay();
336 delay_seconds
= config_
->StepDelay();
339 if (step_delay
!= kStepDelayShort
) {
340 NotifyObservers(Observer::COMPONENT_UPDATER_SLEEPING
, "");
342 // Zero is only used for unit tests.
343 if (0 == delay_seconds
)
347 VLOG(1) << "Scheduling next run to occur in " << delay_seconds
<< " seconds";
348 timer_
.Start(FROM_HERE
,
349 base::TimeDelta::FromSeconds(delay_seconds
),
351 &CrxUpdateService::ProcessPendingItems
);
354 // Given a extension-like component id, find the associated component.
355 CrxUpdateItem
* CrxUpdateService::FindUpdateItemById(
356 const std::string
& id
) const {
357 DCHECK(thread_checker_
.CalledOnValidThread());
358 CrxUpdateItem::FindById
finder(id
);
359 UpdateItems::const_iterator it
=
360 std::find_if(work_items_
.begin(), work_items_
.end(), finder
);
361 return it
!= work_items_
.end() ? *it
: NULL
;
364 // Changes a component's status, clearing on_demand and firing notifications as
365 // necessary. By convention, this is the only function that can change a
366 // CrxUpdateItem's |status|.
367 // TODO(waffles): Do we want to add DCHECKS for valid state transitions here?
368 void CrxUpdateService::ChangeItemState(CrxUpdateItem
* item
,
369 CrxUpdateItem::Status to
) {
370 DCHECK(thread_checker_
.CalledOnValidThread());
371 if (to
== CrxUpdateItem::kNoUpdate
|| to
== CrxUpdateItem::kUpdated
||
372 to
== CrxUpdateItem::kUpToDate
) {
373 item
->on_demand
= false;
379 case CrxUpdateItem::kCanUpdate
:
380 NotifyObservers(Observer::COMPONENT_UPDATE_FOUND
, item
->id
);
382 case CrxUpdateItem::kUpdatingDiff
:
383 case CrxUpdateItem::kUpdating
:
384 NotifyObservers(Observer::COMPONENT_UPDATE_READY
, item
->id
);
386 case CrxUpdateItem::kUpdated
:
387 NotifyObservers(Observer::COMPONENT_UPDATED
, item
->id
);
389 case CrxUpdateItem::kUpToDate
:
390 case CrxUpdateItem::kNoUpdate
:
391 NotifyObservers(Observer::COMPONENT_NOT_UPDATED
, item
->id
);
393 case CrxUpdateItem::kNew
:
394 case CrxUpdateItem::kChecking
:
395 case CrxUpdateItem::kDownloading
:
396 case CrxUpdateItem::kDownloadingDiff
:
397 case CrxUpdateItem::kLastStatus
:
398 // No notification for these states.
402 // Free possible pending network requests.
403 if ((to
== CrxUpdateItem::kUpdated
) || (to
== CrxUpdateItem::kUpToDate
) ||
404 (to
== CrxUpdateItem::kNoUpdate
)) {
405 for (std::vector
<base::Closure
>::iterator it
=
406 item
->ready_callbacks
.begin();
407 it
!= item
->ready_callbacks
.end();
411 item
->ready_callbacks
.clear();
415 // Changes all the components in |work_items_| that have |from| status to
416 // |to| status and returns how many have been changed.
417 size_t CrxUpdateService::ChangeItemStatus(CrxUpdateItem::Status from
,
418 CrxUpdateItem::Status to
) {
419 DCHECK(thread_checker_
.CalledOnValidThread());
421 for (UpdateItems::iterator it
= work_items_
.begin();
422 it
!= work_items_
.end();
424 CrxUpdateItem
* item
= *it
;
425 if (item
->status
== from
) {
426 ChangeItemState(item
, to
);
433 // Adds a component to be checked for upgrades. If the component exists it
434 // it will be replaced and the return code is kReplaced.
435 ComponentUpdateService::Status
CrxUpdateService::RegisterComponent(
436 const CrxComponent
& component
) {
437 DCHECK(thread_checker_
.CalledOnValidThread());
438 if (component
.pk_hash
.empty() || !component
.version
.IsValid() ||
439 !component
.installer
)
442 std::string
id(GetCrxComponentID(component
));
443 CrxUpdateItem
* uit
= FindUpdateItemById(id
);
445 uit
->component
= component
;
449 uit
= new CrxUpdateItem
;
451 uit
->component
= component
;
453 work_items_
.push_back(uit
);
455 // If this is the first component registered we call Start to
456 // schedule the first timer. Otherwise, reset the timer to trigger another
457 // pass over the work items, if the component updater is sleeping, fact
458 // indicated by a running timer. If the timer is not running, it means that
459 // the service is busy updating something, and in that case, this component
460 // will be picked up at the next pass.
462 if (work_items_
.size() == 1) {
464 } else if (timer_
.IsRunning()) {
465 timer_
.Start(FROM_HERE
,
466 base::TimeDelta::FromSeconds(config_
->InitialDelay()),
468 &CrxUpdateService::ProcessPendingItems
);
475 std::vector
<std::string
> CrxUpdateService::GetComponentIDs() const {
476 DCHECK(thread_checker_
.CalledOnValidThread());
477 std::vector
<std::string
> component_ids
;
478 for (UpdateItems::const_iterator it
= work_items_
.begin();
479 it
!= work_items_
.end();
481 const CrxUpdateItem
* item
= *it
;
482 component_ids
.push_back(item
->id
);
484 return component_ids
;
487 OnDemandUpdater
& CrxUpdateService::GetOnDemandUpdater() {
491 void CrxUpdateService::MaybeThrottle(const std::string
& crx_id
,
492 const base::Closure
& callback
) {
493 DCHECK(thread_checker_
.CalledOnValidThread());
494 // Check if we can on-demand update, else unblock the request anyway.
495 CrxUpdateItem
* item
= FindUpdateItemById(crx_id
);
496 Status status
= OnDemandUpdateWithCooldown(item
);
497 if (status
== kOk
|| status
== kInProgress
) {
498 item
->ready_callbacks
.push_back(callback
);
504 scoped_refptr
<base::SequencedTaskRunner
>
505 CrxUpdateService::GetSequencedTaskRunner() {
506 return config_
->GetSequencedTaskRunner();
509 bool CrxUpdateService::GetComponentDetails(const std::string
& component_id
,
510 CrxUpdateItem
* item
) const {
511 DCHECK(thread_checker_
.CalledOnValidThread());
512 const CrxUpdateItem
* crx_update_item(FindUpdateItemById(component_id
));
514 *item
= *crx_update_item
;
515 return crx_update_item
!= NULL
;
518 // Start the process of checking for an update, for a particular component
519 // that was previously registered.
520 // |component_id| is a value returned from GetCrxComponentID().
521 ComponentUpdateService::Status
CrxUpdateService::OnDemandUpdate(
522 const std::string
& component_id
) {
523 return OnDemandUpdateInternal(FindUpdateItemById(component_id
));
526 // This is the main loop of the component updater. It updates one component
527 // at a time if updates are available. Otherwise, it does an update check or
528 // takes a long sleep until the loop runs again.
529 void CrxUpdateService::ProcessPendingItems() {
530 DCHECK(thread_checker_
.CalledOnValidThread());
532 CrxUpdateItem
* ready_upgrade
= FindReadyComponent();
534 UpdateComponent(ready_upgrade
);
538 if (!CheckForUpdates())
539 ScheduleNextRun(kStepDelayLong
);
542 CrxUpdateItem
* CrxUpdateService::FindReadyComponent() const {
545 static bool IsReadyOnDemand(CrxUpdateItem
* item
) {
546 return item
->on_demand
&& IsReady(item
);
548 static bool IsReady(CrxUpdateItem
* item
) {
549 return item
->status
== CrxUpdateItem::kCanUpdate
;
553 std::vector
<CrxUpdateItem
*>::const_iterator it
= std::find_if(
554 work_items_
.begin(), work_items_
.end(), Helper::IsReadyOnDemand
);
555 if (it
!= work_items_
.end())
557 it
= std::find_if(work_items_
.begin(), work_items_
.end(), Helper::IsReady
);
558 if (it
!= work_items_
.end())
563 // Prepares the components for an update check and initiates the request.
564 // On demand components are always included in the update check request.
565 // Otherwise, only include components that have not been checked recently.
566 bool CrxUpdateService::CheckForUpdates() {
567 const base::TimeDelta minimum_recheck_wait_time
=
568 base::TimeDelta::FromSeconds(config_
->MinimumReCheckWait());
569 const base::Time
now(base::Time::Now());
571 std::vector
<CrxUpdateItem
*> items_to_check
;
572 for (size_t i
= 0; i
!= work_items_
.size(); ++i
) {
573 CrxUpdateItem
* item
= work_items_
[i
];
574 DCHECK(item
->status
== CrxUpdateItem::kNew
||
575 item
->status
== CrxUpdateItem::kNoUpdate
||
576 item
->status
== CrxUpdateItem::kUpToDate
||
577 item
->status
== CrxUpdateItem::kUpdated
);
579 const base::TimeDelta
time_since_last_checked(now
- item
->last_check
);
581 if (!item
->on_demand
&&
582 time_since_last_checked
< minimum_recheck_wait_time
) {
583 VLOG(1) << "Skipping check for component update: id=" << item
->id
584 << ", time_since_last_checked="
585 << time_since_last_checked
.InSeconds()
586 << " seconds: too soon to check for an update";
590 VLOG(1) << "Scheduling update check for component id=" << item
->id
591 << ", time_since_last_checked="
592 << time_since_last_checked
.InSeconds() << " seconds";
594 item
->last_check
= now
;
595 item
->crx_urls
.clear();
596 item
->crx_diffurls
.clear();
597 item
->previous_version
= item
->component
.version
;
598 item
->next_version
= Version();
599 item
->previous_fp
= item
->component
.fingerprint
;
600 item
->next_fp
.clear();
601 item
->diff_update_failed
= false;
602 item
->error_category
= 0;
603 item
->error_code
= 0;
604 item
->extra_code1
= 0;
605 item
->diff_error_category
= 0;
606 item
->diff_error_code
= 0;
607 item
->diff_extra_code1
= 0;
608 item
->download_metrics
.clear();
610 items_to_check
.push_back(item
);
612 ChangeItemState(item
, CrxUpdateItem::kChecking
);
615 if (items_to_check
.empty())
618 update_checker_
= UpdateChecker::Create(*config_
).Pass();
619 return update_checker_
->CheckForUpdates(
621 config_
->ExtraRequestParams(),
622 base::Bind(&CrxUpdateService::UpdateCheckComplete
,
623 base::Unretained(this)));
626 void CrxUpdateService::UpdateComponent(CrxUpdateItem
* workitem
) {
627 scoped_ptr
<CRXContext
> crx_context(new CRXContext
);
628 crx_context
->pk_hash
= workitem
->component
.pk_hash
;
629 crx_context
->id
= workitem
->id
;
630 crx_context
->installer
= workitem
->component
.installer
;
631 crx_context
->fingerprint
= workitem
->next_fp
;
632 const std::vector
<GURL
>* urls
= NULL
;
633 bool allow_background_download
= false;
634 if (CanTryDiffUpdate(workitem
, *config_
)) {
635 urls
= &workitem
->crx_diffurls
;
636 ChangeItemState(workitem
, CrxUpdateItem::kDownloadingDiff
);
638 // Background downloads are enabled only for selected components and
639 // only for full downloads (see issue 340448).
640 allow_background_download
= workitem
->component
.allow_background_download
;
641 urls
= &workitem
->crx_urls
;
642 ChangeItemState(workitem
, CrxUpdateItem::kDownloading
);
645 // On demand component updates are always downloaded in foreground.
646 const bool is_background_download
= !workitem
->on_demand
&&
647 allow_background_download
&&
648 config_
->UseBackgroundDownloader();
650 crx_downloader_
.reset(
651 CrxDownloader::Create(is_background_download
,
652 config_
->RequestContext(),
653 blocking_task_runner_
,
654 config_
->GetSingleThreadTaskRunner()));
655 crx_downloader_
->set_progress_callback(
656 base::Bind(&CrxUpdateService::DownloadProgress
,
657 base::Unretained(this),
659 crx_downloader_
->StartDownload(*urls
,
660 base::Bind(&CrxUpdateService::DownloadComplete
,
661 base::Unretained(this),
662 base::Passed(&crx_context
)));
665 void CrxUpdateService::UpdateCheckComplete(
666 const GURL
& original_url
,
668 const std::string
& error_message
,
669 const UpdateResponse::Results
& results
) {
670 DCHECK(thread_checker_
.CalledOnValidThread());
671 VLOG(1) << "Update check completed from: " << original_url
.spec();
672 update_checker_
.reset();
674 OnUpdateCheckSucceeded(results
);
676 OnUpdateCheckFailed(error
, error_message
);
679 // Handles a valid Omaha update check response by matching the results with
680 // the registered components which were checked for updates.
681 // If updates are found, prepare the components for the actual version upgrade.
682 // One of these components will be drafted for the upgrade next time
683 // ProcessPendingItems is called.
684 void CrxUpdateService::OnUpdateCheckSucceeded(
685 const UpdateResponse::Results
& results
) {
686 size_t num_updates_pending
= 0;
687 DCHECK(thread_checker_
.CalledOnValidThread());
688 VLOG(1) << "Update check succeeded.";
689 std::vector
<UpdateResponse::Result
>::const_iterator it
;
690 for (it
= results
.list
.begin(); it
!= results
.list
.end(); ++it
) {
691 CrxUpdateItem
* crx
= FindUpdateItemById(it
->extension_id
);
695 if (crx
->status
!= CrxUpdateItem::kChecking
) {
697 continue; // Not updating this component now.
700 if (it
->manifest
.version
.empty()) {
701 // No version means no update available.
702 ChangeItemState(crx
, CrxUpdateItem::kNoUpdate
);
703 VLOG(1) << "No update available for component: " << crx
->id
;
707 if (!IsVersionNewer(crx
->component
.version
, it
->manifest
.version
)) {
708 // The component is up to date.
709 ChangeItemState(crx
, CrxUpdateItem::kUpToDate
);
710 VLOG(1) << "Component already up-to-date: " << crx
->id
;
714 if (!it
->manifest
.browser_min_version
.empty()) {
715 if (IsVersionNewer(config_
->GetBrowserVersion(),
716 it
->manifest
.browser_min_version
)) {
717 // The component is not compatible with this Chrome version.
718 VLOG(1) << "Ignoring incompatible component: " << crx
->id
;
719 ChangeItemState(crx
, CrxUpdateItem::kNoUpdate
);
724 if (it
->manifest
.packages
.size() != 1) {
725 // Assume one and only one package per component.
726 VLOG(1) << "Ignoring multiple packages for component: " << crx
->id
;
727 ChangeItemState(crx
, CrxUpdateItem::kNoUpdate
);
731 // Parse the members of the result and queue an upgrade for this component.
732 crx
->next_version
= Version(it
->manifest
.version
);
734 VLOG(1) << "Update found for component: " << crx
->id
;
736 typedef UpdateResponse::Result::Manifest::Package Package
;
737 const Package
& package(it
->manifest
.packages
[0]);
738 crx
->next_fp
= package
.fingerprint
;
740 // Resolve the urls by combining the base urls with the package names.
741 for (size_t i
= 0; i
!= it
->crx_urls
.size(); ++i
) {
742 const GURL
url(it
->crx_urls
[i
].Resolve(package
.name
));
744 crx
->crx_urls
.push_back(url
);
746 for (size_t i
= 0; i
!= it
->crx_diffurls
.size(); ++i
) {
747 const GURL
url(it
->crx_diffurls
[i
].Resolve(package
.namediff
));
749 crx
->crx_diffurls
.push_back(url
);
752 ChangeItemState(crx
, CrxUpdateItem::kCanUpdate
);
753 ++num_updates_pending
;
756 // All components that are not included in the update response are
757 // considered up to date.
758 ChangeItemStatus(CrxUpdateItem::kChecking
, CrxUpdateItem::kUpToDate
);
760 // If there are updates pending we do a short wait, otherwise we take
761 // a longer delay until we check the components again.
762 ScheduleNextRun(num_updates_pending
> 0 ? kStepDelayShort
: kStepDelayLong
);
765 void CrxUpdateService::OnUpdateCheckFailed(int error
,
766 const std::string
& error_message
) {
767 DCHECK(thread_checker_
.CalledOnValidThread());
770 ChangeItemStatus(CrxUpdateItem::kChecking
, CrxUpdateItem::kNoUpdate
);
771 DCHECK_GT(count
, 0ul);
772 VLOG(1) << "Update check failed.";
773 ScheduleNextRun(kStepDelayLong
);
776 // Called when progress is being made downloading a CRX. The progress may
777 // not monotonically increase due to how the CRX downloader switches between
778 // different downloaders and fallback urls.
779 void CrxUpdateService::DownloadProgress(
780 const std::string
& component_id
,
781 const CrxDownloader::Result
& download_result
) {
782 DCHECK(thread_checker_
.CalledOnValidThread());
783 NotifyObservers(Observer::COMPONENT_UPDATE_DOWNLOADING
, component_id
);
786 // Called when the CRX package has been downloaded to a temporary location.
787 // Here we fire the notifications and schedule the component-specific installer
788 // to be called in the file thread.
789 void CrxUpdateService::DownloadComplete(
790 scoped_ptr
<CRXContext
> crx_context
,
791 const CrxDownloader::Result
& download_result
) {
792 DCHECK(thread_checker_
.CalledOnValidThread());
794 CrxUpdateItem
* crx
= FindUpdateItemById(crx_context
->id
);
795 DCHECK(crx
->status
== CrxUpdateItem::kDownloadingDiff
||
796 crx
->status
== CrxUpdateItem::kDownloading
);
798 AppendDownloadMetrics(crx_downloader_
->download_metrics(),
799 &crx
->download_metrics
);
801 crx_downloader_
.reset();
803 if (download_result
.error
) {
804 if (crx
->status
== CrxUpdateItem::kDownloadingDiff
) {
805 crx
->diff_error_category
= kNetworkError
;
806 crx
->diff_error_code
= download_result
.error
;
807 crx
->diff_update_failed
= true;
808 size_t count
= ChangeItemStatus(CrxUpdateItem::kDownloadingDiff
,
809 CrxUpdateItem::kCanUpdate
);
810 DCHECK_EQ(count
, 1ul);
812 ScheduleNextRun(kStepDelayShort
);
815 crx
->error_category
= kNetworkError
;
816 crx
->error_code
= download_result
.error
;
818 ChangeItemStatus(CrxUpdateItem::kDownloading
, CrxUpdateItem::kNoUpdate
);
819 DCHECK_EQ(count
, 1ul);
821 // At this point, since both the differential and the full downloads failed,
822 // the update for this component has finished with an error.
823 ping_manager_
->OnUpdateComplete(crx
);
825 // Move on to the next update, if there is one available.
826 ScheduleNextRun(kStepDelayMedium
);
829 if (crx
->status
== CrxUpdateItem::kDownloadingDiff
) {
830 count
= ChangeItemStatus(CrxUpdateItem::kDownloadingDiff
,
831 CrxUpdateItem::kUpdatingDiff
);
833 count
= ChangeItemStatus(CrxUpdateItem::kDownloading
,
834 CrxUpdateItem::kUpdating
);
836 DCHECK_EQ(count
, 1ul);
838 // Why unretained? See comment at top of file.
839 blocking_task_runner_
->PostDelayedTask(
841 base::Bind(&CrxUpdateService::Install
,
842 base::Unretained(this),
843 base::Passed(&crx_context
),
844 download_result
.response
),
845 base::TimeDelta::FromMilliseconds(config_
->StepDelay()));
849 // Install consists of digital signature verification, unpacking and then
850 // calling the component specific installer. All that is handled by the
851 // |unpacker_|. If there is an error this function is in charge of deleting
852 // the files created.
853 void CrxUpdateService::Install(scoped_ptr
<CRXContext
> context
,
854 const base::FilePath
& crx_path
) {
855 // This function owns the file at |crx_path| and the |context| object.
856 unpacker_
= new ComponentUnpacker(context
->pk_hash
,
858 context
->fingerprint
,
860 config_
->CreateOutOfProcessPatcher(),
861 blocking_task_runner_
);
862 unpacker_
->Unpack(base::Bind(&CrxUpdateService::EndUnpacking
,
863 base::Unretained(this),
868 void CrxUpdateService::EndUnpacking(const std::string
& component_id
,
869 const base::FilePath
& crx_path
,
870 ComponentUnpacker::Error error
,
871 int extended_error
) {
872 if (!DeleteFileAndEmptyParentDirectory(crx_path
))
873 NOTREACHED() << crx_path
.value();
874 main_task_runner_
->PostDelayedTask(
876 base::Bind(&CrxUpdateService::DoneInstalling
,
877 base::Unretained(this),
881 base::TimeDelta::FromMilliseconds(config_
->StepDelay()));
882 // Reset the unpacker last, otherwise we free our own arguments.
886 // Installation has been completed. Adjust the component status and
887 // schedule the next check. Schedule a short delay before trying the full
888 // update when the differential update failed.
889 void CrxUpdateService::DoneInstalling(const std::string
& component_id
,
890 ComponentUnpacker::Error error
,
892 DCHECK(thread_checker_
.CalledOnValidThread());
894 ErrorCategory error_category
= kErrorNone
;
896 case ComponentUnpacker::kNone
:
898 case ComponentUnpacker::kInstallerError
:
899 error_category
= kInstallError
;
902 error_category
= kUnpackError
;
906 const bool is_success
= error
== ComponentUnpacker::kNone
;
908 CrxUpdateItem
* item
= FindUpdateItemById(component_id
);
909 if (item
->status
== CrxUpdateItem::kUpdatingDiff
&& !is_success
) {
910 item
->diff_error_category
= error_category
;
911 item
->diff_error_code
= error
;
912 item
->diff_extra_code1
= extra_code
;
913 item
->diff_update_failed
= true;
914 size_t count
= ChangeItemStatus(CrxUpdateItem::kUpdatingDiff
,
915 CrxUpdateItem::kCanUpdate
);
916 DCHECK_EQ(count
, 1ul);
917 ScheduleNextRun(kStepDelayShort
);
922 item
->component
.version
= item
->next_version
;
923 item
->component
.fingerprint
= item
->next_fp
;
924 ChangeItemState(item
, CrxUpdateItem::kUpdated
);
926 item
->error_category
= error_category
;
927 item
->error_code
= error
;
928 item
->extra_code1
= extra_code
;
929 ChangeItemState(item
, CrxUpdateItem::kNoUpdate
);
932 ping_manager_
->OnUpdateComplete(item
);
934 // Move on to the next update, if there is one available.
935 ScheduleNextRun(kStepDelayMedium
);
938 void CrxUpdateService::NotifyObservers(Observer::Events event
,
939 const std::string
& id
) {
940 DCHECK(thread_checker_
.CalledOnValidThread());
941 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnEvent(event
, id
));
944 ComponentUpdateService::Status
CrxUpdateService::OnDemandUpdateWithCooldown(
945 CrxUpdateItem
* uit
) {
949 // Check if the request is too soon.
950 base::TimeDelta delta
= base::Time::Now() - uit
->last_check
;
951 if (delta
< base::TimeDelta::FromSeconds(config_
->OnDemandDelay()))
954 return OnDemandUpdateInternal(uit
);
957 ComponentUpdateService::Status
CrxUpdateService::OnDemandUpdateInternal(
958 CrxUpdateItem
* uit
) {
962 uit
->on_demand
= true;
964 // If there is an update available for this item, then continue processing
965 // the update. This is an artifact of how update checks are done: in addition
966 // to the on-demand item, the update check may include other items as well.
967 if (uit
->status
!= CrxUpdateItem::kCanUpdate
) {
968 Status service_status
= GetServiceStatus(uit
->status
);
969 // If the item is already in the process of being updated, there is
970 // no point in this call, so return kInProgress.
971 if (service_status
== kInProgress
)
972 return service_status
;
974 // Otherwise the item was already checked a while back (or it is new),
975 // set its status to kNew to give it a slightly higher priority.
976 ChangeItemState(uit
, CrxUpdateItem::kNew
);
979 // In case the current delay is long, set the timer to a shorter value
980 // to get the ball rolling.
981 if (timer_
.IsRunning()) {
983 timer_
.Start(FROM_HERE
,
984 base::TimeDelta::FromSeconds(config_
->StepDelay()),
986 &CrxUpdateService::ProcessPendingItems
);
992 ComponentUpdateService::Status
CrxUpdateService::GetServiceStatus(
993 CrxUpdateItem::Status status
) {
995 case CrxUpdateItem::kChecking
:
996 case CrxUpdateItem::kCanUpdate
:
997 case CrxUpdateItem::kDownloadingDiff
:
998 case CrxUpdateItem::kDownloading
:
999 case CrxUpdateItem::kUpdatingDiff
:
1000 case CrxUpdateItem::kUpdating
:
1002 case CrxUpdateItem::kNew
:
1003 case CrxUpdateItem::kUpdated
:
1004 case CrxUpdateItem::kUpToDate
:
1005 case CrxUpdateItem::kNoUpdate
:
1007 case CrxUpdateItem::kLastStatus
:
1008 NOTREACHED() << status
;
1013 ///////////////////////////////////////////////////////////////////////////////
1015 // The component update factory. Using the component updater as a singleton
1016 // is the job of the browser process.
1017 ComponentUpdateService
* ComponentUpdateServiceFactory(Configurator
* config
) {
1019 return new CrxUpdateService(config
);
1022 } // namespace component_updater