Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / component_updater / component_updater_service.cc
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.
4
5 #include "chrome/browser/component_updater/component_updater_service.h"
6
7 #include <algorithm>
8 #include <set>
9 #include <vector>
10
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"
36 #include "url/gurl.h"
37
38 using content::BrowserThread;
39
40 namespace component_updater {
41
42 // The component updater is designed to live until process shutdown, so
43 // base::Bind() calls are not refcounted.
44
45 namespace {
46
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;
51 }
52
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();
59 }
60
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());
65 }
66
67 }  // namespace
68
69 CrxUpdateItem::CrxUpdateItem()
70     : status(kNew),
71       on_demand(false),
72       diff_update_failed(false),
73       error_category(0),
74       error_code(0),
75       extra_code1(0),
76       diff_error_category(0),
77       diff_error_code(0),
78       diff_extra_code1(0) {
79 }
80
81 CrxUpdateItem::~CrxUpdateItem() {
82 }
83
84 CrxComponent::CrxComponent()
85     : installer(NULL), allow_background_download(true) {
86 }
87
88 CrxComponent::~CrxComponent() {
89 }
90
91 CrxComponentInfo::CrxComponentInfo() {
92 }
93
94 CrxComponentInfo::~CrxComponentInfo() {
95 }
96
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> {
106  public:
107   explicit CUResourceThrottle(const net::URLRequest* request);
108   virtual ~CUResourceThrottle();
109
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;
114
115   // Component updater calls this function via PostTask to unblock the request.
116   void Unblock();
117
118   typedef std::vector<base::WeakPtr<CUResourceThrottle> > WeakPtrVector;
119
120  private:
121   enum State { NEW, BLOCKED, UNBLOCKED };
122
123   State state_;
124 };
125
126 void UnblockResourceThrottle(base::WeakPtr<CUResourceThrottle> rt) {
127   BrowserThread::PostTask(BrowserThread::IO,
128                           FROM_HERE,
129                           base::Bind(&CUResourceThrottle::Unblock, rt));
130 }
131
132 void UnblockandReapAllThrottles(CUResourceThrottle::WeakPtrVector* throttles) {
133   CUResourceThrottle::WeakPtrVector::iterator it;
134   for (it = throttles->begin(); it != throttles->end(); ++it)
135     UnblockResourceThrottle(*it);
136   throttles->clear();
137 }
138
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
151 // thread.
152 class CrxUpdateService : public ComponentUpdateService {
153  public:
154   explicit CrxUpdateService(ComponentUpdateService::Configurator* config);
155   virtual ~CrxUpdateService();
156
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;
169
170   // Context for a crx download url request.
171   struct CRXContext {
172     ComponentInstaller* installer;
173     std::vector<uint8> pk_hash;
174     std::string id;
175     std::string fingerprint;
176     CRXContext() : installer(NULL) {}
177   };
178
179  private:
180   enum ErrorCategory {
181     kErrorNone = 0,
182     kNetworkError,
183     kUnpackError,
184     kInstallError,
185   };
186
187   enum StepDelayInterval {
188     kStepDelayShort = 0,
189     kStepDelayMedium,
190     kStepDelayLong,
191   };
192
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);
198
199   void DownloadProgress(const std::string& component_id,
200                         const CrxDownloader::Result& download_result);
201
202   void DownloadComplete(scoped_ptr<CRXContext> crx_context,
203                         const CrxDownloader::Result& download_result);
204
205   Status OnDemandUpdateInternal(CrxUpdateItem* item);
206
207   void ProcessPendingItems();
208
209   // Find a component that is ready to update.
210   CrxUpdateItem* FindReadyComponent() const;
211
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();
216
217   void UpdateComponent(CrxUpdateItem* workitem);
218
219   void ScheduleNextRun(StepDelayInterval step_delay);
220
221   void ParseResponse(const std::string& xml);
222
223   void Install(scoped_ptr<CRXContext> context, const base::FilePath& crx_path);
224
225   void EndUnpacking(const std::string& component_id,
226                     const base::FilePath& crx_path,
227                     ComponentUnpacker::Error error,
228                     int extended_error);
229
230   void DoneInstalling(const std::string& component_id,
231                       ComponentUnpacker::Error error,
232                       int extended_error);
233
234   void ChangeItemState(CrxUpdateItem* item, CrxUpdateItem::Status to);
235
236   size_t ChangeItemStatus(CrxUpdateItem::Status from, CrxUpdateItem::Status to);
237
238   CrxUpdateItem* FindUpdateItemById(const std::string& id);
239
240   void NotifyObservers(Observer::Events event, const std::string& id);
241
242   bool HasOnDemandItems() const;
243
244   void OnNewResourceThrottle(base::WeakPtr<CUResourceThrottle> rt,
245                              const std::string& crx_id);
246
247   scoped_ptr<ComponentUpdateService::Configurator> config_;
248
249   scoped_ptr<UpdateChecker> update_checker_;
250
251   scoped_ptr<PingManager> ping_manager_;
252
253   scoped_refptr<ComponentUnpacker> unpacker_;
254
255   scoped_ptr<CrxDownloader> crx_downloader_;
256
257   // A collection of every work item.
258   typedef std::vector<CrxUpdateItem*> UpdateItems;
259   UpdateItems work_items_;
260
261   base::OneShotTimer<CrxUpdateService> timer_;
262
263   scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
264
265   const Version chrome_version_;
266
267   bool running_;
268
269   ObserverList<Observer> observer_list_;
270
271   DISALLOW_COPY_AND_ASSIGN(CrxUpdateService);
272 };
273
274 //////////////////////////////////////////////////////////////////////////////
275
276 CrxUpdateService::CrxUpdateService(ComponentUpdateService::Configurator* config)
277     : config_(config),
278       ping_manager_(
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()),
286       running_(false) {
287 }
288
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.
293   Stop();
294   STLDeleteElements(&work_items_);
295 }
296
297 void CrxUpdateService::AddObserver(Observer* observer) {
298   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
299   observer_list_.AddObserver(observer);
300 }
301
302 void CrxUpdateService::RemoveObserver(Observer* observer) {
303   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
304   observer_list_.RemoveObserver(observer);
305 }
306
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";
312   running_ = true;
313   if (work_items_.empty())
314     return kOk;
315
316   NotifyObservers(Observer::COMPONENT_UPDATER_STARTED, "");
317
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()),
322                this,
323                &CrxUpdateService::ProcessPendingItems);
324   return kOk;
325 }
326
327 // Stop the main check + update loop. In flight operations will be
328 // completed.
329 ComponentUpdateService::Status CrxUpdateService::Stop() {
330   VLOG(1) << "CrxUpdateService stopping";
331   running_ = false;
332   timer_.Stop();
333   return kOk;
334 }
335
336 bool CrxUpdateService::HasOnDemandItems() const {
337   class Helper {
338    public:
339     static bool IsOnDemand(CrxUpdateItem* item) { return item->on_demand; }
340   };
341   return std::find_if(work_items_.begin(),
342                       work_items_.end(),
343                       Helper::IsOnDemand) != work_items_.end();
344 }
345
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
353 //    components.
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.
361   if (!running_)
362     return;
363
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();
371         break;
372       case kStepDelayMedium:
373         delay_seconds = config_->StepDelayMedium();
374         break;
375       case kStepDelayLong:
376         delay_seconds = config_->NextCheckDelay();
377         break;
378     }
379   } else {
380     delay_seconds = config_->StepDelay();
381   }
382
383   if (step_delay != kStepDelayShort) {
384     NotifyObservers(Observer::COMPONENT_UPDATER_SLEEPING, "");
385
386     // Zero is only used for unit tests.
387     if (0 == delay_seconds)
388       return;
389   }
390
391   VLOG(1) << "Scheduling next run to occur in " << delay_seconds << " seconds";
392   timer_.Start(FROM_HERE,
393                base::TimeDelta::FromSeconds(delay_seconds),
394                this,
395                &CrxUpdateService::ProcessPendingItems);
396 }
397
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;
405 }
406
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;
417   }
418
419   item->status = to;
420
421   switch (to) {
422     case CrxUpdateItem::kCanUpdate:
423       NotifyObservers(Observer::COMPONENT_UPDATE_FOUND, item->id);
424       break;
425     case CrxUpdateItem::kUpdatingDiff:
426     case CrxUpdateItem::kUpdating:
427       NotifyObservers(Observer::COMPONENT_UPDATE_READY, item->id);
428       break;
429     case CrxUpdateItem::kUpdated:
430       NotifyObservers(Observer::COMPONENT_UPDATED, item->id);
431       break;
432     case CrxUpdateItem::kUpToDate:
433     case CrxUpdateItem::kNoUpdate:
434       NotifyObservers(Observer::COMPONENT_NOT_UPDATED, item->id);
435       break;
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.
442       break;
443   }
444
445   // Free possible pending network requests.
446   if ((to == CrxUpdateItem::kUpdated) || (to == CrxUpdateItem::kUpToDate) ||
447       (to == CrxUpdateItem::kNoUpdate)) {
448     UnblockandReapAllThrottles(&item->throttles);
449   }
450 }
451
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));
457   size_t count = 0;
458   for (UpdateItems::iterator it = work_items_.begin();
459        it != work_items_.end();
460        ++it) {
461     CrxUpdateItem* item = *it;
462     if (item->status == from) {
463       ChangeItemState(item, to);
464       ++count;
465     }
466   }
467   return count;
468 }
469
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)
477     return kError;
478
479   std::string id(GetCrxComponentID(component));
480   CrxUpdateItem* uit = FindUpdateItemById(id);
481   if (uit) {
482     uit->component = component;
483     return kReplaced;
484   }
485
486   uit = new CrxUpdateItem;
487   uit->id.swap(id);
488   uit->component = component;
489
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))
494     Start();
495
496   return kOk;
497 }
498
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));
505 }
506
507 ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateInternal(
508     CrxUpdateItem* uit) {
509   if (!uit)
510     return kError;
511
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()))
515     return kError;
516
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:
526       return kInProgress;
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;
535       break;
536     case CrxUpdateItem::kLastStatus:
537       NOTREACHED() << uit->status;
538   }
539
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()) {
543     timer_.Stop();
544     timer_.Start(FROM_HERE,
545                  base::TimeDelta::FromSeconds(config_->StepDelay()),
546                  this,
547                  &CrxUpdateService::ProcessPendingItems);
548   }
549
550   return kOk;
551 }
552
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();
558        ++it) {
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);
565   }
566 }
567
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));
573
574   CrxUpdateItem* ready_upgrade = FindReadyComponent();
575   if (ready_upgrade) {
576     UpdateComponent(ready_upgrade);
577     return;
578   }
579
580   if (!CheckForUpdates())
581     ScheduleNextRun(kStepDelayLong);
582 }
583
584 CrxUpdateItem* CrxUpdateService::FindReadyComponent() const {
585   class Helper {
586    public:
587     static bool IsReadyOnDemand(CrxUpdateItem* item) {
588       return item->on_demand && IsReady(item);
589     }
590     static bool IsReady(CrxUpdateItem* item) {
591       return item->status == CrxUpdateItem::kCanUpdate;
592     }
593   };
594
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())
598     return *it;
599   it = std::find_if(work_items_.begin(), work_items_.end(), Helper::IsReady);
600   if (it != work_items_.end())
601     return *it;
602   return NULL;
603 }
604
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());
612
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);
620
621     const base::TimeDelta time_since_last_checked(now - item->last_check);
622
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";
629       continue;
630     }
631
632     VLOG(1) << "Scheduling update check for component id=" << item->id
633             << ", time_since_last_checked="
634             << time_since_last_checked.InSeconds() << " seconds";
635
636     ChangeItemState(item, CrxUpdateItem::kChecking);
637
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();
653
654     items_to_check.push_back(item);
655   }
656
657   if (items_to_check.empty())
658     return false;
659
660   update_checker_ =
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());
667 }
668
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);
680   } else {
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);
686   }
687
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();
692
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),
699                  crx_context->id));
700   crx_downloader_->StartDownload(*urls,
701                                  base::Bind(&CrxUpdateService::DownloadComplete,
702                                             base::Unretained(this),
703                                             base::Passed(&crx_context)));
704 }
705
706 void CrxUpdateService::UpdateCheckComplete(
707     int error,
708     const std::string& error_message,
709     const UpdateResponse::Results& results) {
710   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
711   update_checker_.reset();
712   if (!error)
713     OnUpdateCheckSucceeded(results);
714   else
715     OnUpdateCheckFailed(error, error_message);
716 }
717
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);
731     if (!crx)
732       continue;
733
734     if (crx->status != CrxUpdateItem::kChecking) {
735       NOTREACHED();
736       continue;  // Not updating this component now.
737     }
738
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;
743       continue;
744     }
745
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;
750       continue;
751     }
752
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);
758         continue;
759       }
760     }
761
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);
766       continue;
767     }
768
769     // Parse the members of the result and queue an upgrade for this component.
770     crx->next_version = Version(it->manifest.version);
771
772     VLOG(1) << "Update found for component: " << crx->id;
773
774     typedef UpdateResponse::Result::Manifest::Package Package;
775     const Package& package(it->manifest.packages[0]);
776     crx->next_fp = package.fingerprint;
777
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));
781       if (url.is_valid())
782         crx->crx_urls.push_back(url);
783     }
784     for (size_t i = 0; i != it->crx_diffurls.size(); ++i) {
785       const GURL url(it->crx_diffurls[i].Resolve(package.namediff));
786       if (url.is_valid())
787         crx->crx_diffurls.push_back(url);
788     }
789
790     ChangeItemState(crx, CrxUpdateItem::kCanUpdate);
791     ++num_updates_pending;
792   }
793
794   // All components that are not included in the update response are
795   // considered up to date.
796   ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate);
797
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);
801 }
802
803 void CrxUpdateService::OnUpdateCheckFailed(int error,
804                                            const std::string& error_message) {
805   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
806   DCHECK(error);
807   size_t count =
808       ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kNoUpdate);
809   DCHECK_GT(count, 0ul);
810   VLOG(1) << "Update check failed.";
811   ScheduleNextRun(kStepDelayLong);
812 }
813
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);
822 }
823
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));
831
832   CrxUpdateItem* crx = FindUpdateItemById(crx_context->id);
833   DCHECK(crx->status == CrxUpdateItem::kDownloadingDiff ||
834          crx->status == CrxUpdateItem::kDownloading);
835
836   AppendDownloadMetrics(crx_downloader_->download_metrics(),
837                         &crx->download_metrics);
838
839   crx_downloader_.reset();
840
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);
849
850       ScheduleNextRun(kStepDelayShort);
851       return;
852     }
853     crx->error_category = kNetworkError;
854     crx->error_code = download_result.error;
855     size_t count =
856         ChangeItemStatus(CrxUpdateItem::kDownloading, CrxUpdateItem::kNoUpdate);
857     DCHECK_EQ(count, 1ul);
858
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);
862
863     // Move on to the next update, if there is one available.
864     ScheduleNextRun(kStepDelayMedium);
865   } else {
866     size_t count = 0;
867     if (crx->status == CrxUpdateItem::kDownloadingDiff) {
868       count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff,
869                                CrxUpdateItem::kUpdatingDiff);
870     } else {
871       count = ChangeItemStatus(CrxUpdateItem::kDownloading,
872                                CrxUpdateItem::kUpdating);
873     }
874     DCHECK_EQ(count, 1ul);
875
876     // Why unretained? See comment at top of file.
877     blocking_task_runner_->PostDelayedTask(
878         FROM_HERE,
879         base::Bind(&CrxUpdateService::Install,
880                    base::Unretained(this),
881                    base::Passed(&crx_context),
882                    download_result.response),
883         base::TimeDelta::FromMilliseconds(config_->StepDelay()));
884   }
885 }
886
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,
895                                     crx_path,
896                                     context->fingerprint,
897                                     context->installer,
898                                     config_->InProcess(),
899                                     blocking_task_runner_);
900   unpacker_->Unpack(base::Bind(&CrxUpdateService::EndUnpacking,
901                                base::Unretained(this),
902                                context->id,
903                                crx_path));
904 }
905
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(
913       BrowserThread::UI,
914       FROM_HERE,
915       base::Bind(&CrxUpdateService::DoneInstalling,
916                  base::Unretained(this),
917                  component_id,
918                  error,
919                  extended_error),
920       base::TimeDelta::FromMilliseconds(config_->StepDelay()));
921   // Reset the unpacker last, otherwise we free our own arguments.
922   unpacker_ = NULL;
923 }
924
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,
930                                       int extra_code) {
931   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
932
933   ErrorCategory error_category = kErrorNone;
934   switch (error) {
935     case ComponentUnpacker::kNone:
936       break;
937     case ComponentUnpacker::kInstallerError:
938       error_category = kInstallError;
939       break;
940     default:
941       error_category = kUnpackError;
942       break;
943   }
944
945   const bool is_success = error == ComponentUnpacker::kNone;
946
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);
957     return;
958   }
959
960   if (is_success) {
961     ChangeItemState(item, CrxUpdateItem::kUpdated);
962     item->component.version = item->next_version;
963     item->component.fingerprint = item->next_fp;
964   } else {
965     ChangeItemState(item, CrxUpdateItem::kNoUpdate);
966     item->error_category = error_category;
967     item->error_code = error;
968     item->extra_code1 = extra_code;
969   }
970
971   ping_manager_->OnUpdateComplete(item);
972
973   // Move on to the next update, if there is one available.
974   ScheduleNextRun(kStepDelayMedium);
975 }
976
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));
981 }
982
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,
991                           FROM_HERE,
992                           base::Bind(&CrxUpdateService::OnNewResourceThrottle,
993                                      base::Unretained(this),
994                                      rt->AsWeakPtr(),
995                                      crx_id));
996   return rt;
997 }
998
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);
1008     return;
1009   }
1010   UnblockResourceThrottle(rt);
1011 }
1012
1013 ///////////////////////////////////////////////////////////////////////////////
1014
1015 CUResourceThrottle::CUResourceThrottle(const net::URLRequest* request)
1016     : state_(NEW) {
1017   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1018 }
1019
1020 CUResourceThrottle::~CUResourceThrottle() {
1021   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1022 }
1023
1024 void CUResourceThrottle::WillStartRequest(bool* defer) {
1025   if (state_ != UNBLOCKED) {
1026     state_ = BLOCKED;
1027     *defer = true;
1028   } else {
1029     *defer = false;
1030   }
1031 }
1032
1033 void CUResourceThrottle::WillRedirectRequest(const GURL& new_url, bool* defer) {
1034   WillStartRequest(defer);
1035 }
1036
1037 const char* CUResourceThrottle::GetNameForLogging() const {
1038   return "ComponentUpdateResourceThrottle";
1039 }
1040
1041 void CUResourceThrottle::Unblock() {
1042   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1043   if (state_ == BLOCKED)
1044     controller()->Resume();
1045   state_ = UNBLOCKED;
1046 }
1047
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) {
1052   DCHECK(config);
1053   return new CrxUpdateService(config);
1054 }
1055
1056 }  // namespace component_updater