-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
-#include "base/memory/weak_ptr.h"
+#include "base/observer_list.h"
+#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/timer/timer.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/component_updater/component_patcher.h"
#include "chrome/browser/component_updater/component_unpacker.h"
#include "chrome/browser/component_updater/component_updater_ping_manager.h"
+#include "chrome/browser/component_updater/component_updater_utils.h"
+#include "chrome/browser/component_updater/crx_downloader.h"
#include "chrome/browser/component_updater/crx_update_item.h"
-#include "chrome/common/chrome_utility_messages.h"
+#include "chrome/browser/component_updater/update_checker.h"
+#include "chrome/browser/component_updater/update_response.h"
#include "chrome/common/chrome_version_info.h"
-#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_controller.h"
#include "content/public/browser/resource_throttle.h"
-#include "content/public/browser/utility_process_host.h"
-#include "content/public/browser/utility_process_host_client.h"
-#include "net/base/escape.h"
-#include "net/base/load_flags.h"
-#include "net/base/net_errors.h"
-#include "net/url_request/url_fetcher.h"
-#include "net/url_request/url_fetcher_delegate.h"
-#include "net/url_request/url_request.h"
-#include "net/url_request/url_request_status.h"
#include "url/gurl.h"
using content::BrowserThread;
-using content::UtilityProcessHost;
-using content::UtilityProcessHostClient;
-using extensions::Extension;
+
+namespace component_updater {
// The component updater is designed to live until process shutdown, so
// base::Bind() calls are not refcounted.
namespace {
-// Extends an omaha compatible update check url |query| string. Does
-// not mutate the string if it would be longer than |limit| chars.
-bool AddQueryString(const std::string& id,
- const std::string& version,
- const std::string& fingerprint,
- bool ondemand,
- size_t limit,
- std::string* query) {
- std::string additional =
- base::StringPrintf("id=%s&v=%s&fp=%s&uc%s",
- id.c_str(),
- version.c_str(),
- fingerprint.c_str(),
- ondemand ? "&installsource=ondemand" : "");
- additional = "x=" + net::EscapeQueryParamValue(additional, true);
- if ((additional.size() + query->size() + 1) > limit)
- return false;
- if (!query->empty())
- query->append(1, '&');
- query->append(additional);
- return true;
-}
-
-// Create the final omaha compatible query. The |extra| is optional and can
-// be null. It should contain top level (non-escaped) parameters.
-std::string MakeFinalQuery(const std::string& host,
- const std::string& query,
- const char* extra) {
- std::string request(host);
- request.append(1, '?');
- if (extra) {
- request.append(extra);
- request.append(1, '&');
- }
- request.append(query);
- return request;
-}
-
-// Produces an extension-like friendly |id|. This might be removed in the
-// future if we roll our on packing tools.
-static std::string HexStringToID(const std::string& hexstr) {
- std::string id;
- for (size_t i = 0; i < hexstr.size(); ++i) {
- int val;
- if (base::HexStringToInt(base::StringPiece(hexstr.begin() + i,
- hexstr.begin() + i + 1),
- &val)) {
- id.append(1, val + 'a');
- } else {
- id.append(1, 'a');
- }
- }
- DCHECK(Extension::IdIsValid(id));
- return id;
-}
-
-// Helper to do version check for components.
+// Returns true if the |proposed| version is newer than |current| version.
bool IsVersionNewer(const Version& current, const std::string& proposed) {
Version proposed_ver(proposed);
- if (!proposed_ver.IsValid())
- return false;
- return (current.CompareTo(proposed_ver) < 0);
-}
-
-// Helper template class that allows our main class to have separate
-// OnURLFetchComplete() callbacks for different types of url requests
-// they are differentiated by the |Ctx| type.
-template <typename Del, typename Ctx>
-class DelegateWithContext : public net::URLFetcherDelegate {
- public:
- DelegateWithContext(Del* delegate, Ctx* context)
- : delegate_(delegate), context_(context) {}
-
- virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE {
- delegate_->OnURLFetchComplete(source, context_);
- delete this;
- }
-
- private:
- ~DelegateWithContext() {}
-
- Del* delegate_;
- Ctx* context_;
-};
-// This function creates the right DelegateWithContext using template inference.
-template <typename Del, typename Ctx>
-net::URLFetcherDelegate* MakeContextDelegate(Del* delegate, Ctx* context) {
- return new DelegateWithContext<Del, Ctx>(delegate, context);
-}
-
-// Helper to start a url request using |fetcher| with the common flags.
-void StartFetch(net::URLFetcher* fetcher,
- net::URLRequestContextGetter* context_getter,
- bool save_to_file,
- scoped_refptr<base::SequencedTaskRunner> task_runner) {
- fetcher->SetRequestContext(context_getter);
- fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
- net::LOAD_DO_NOT_SAVE_COOKIES |
- net::LOAD_DISABLE_CACHE);
- // TODO(cpu): Define our retry and backoff policy.
- fetcher->SetAutomaticallyRetryOn5xx(false);
- if (save_to_file) {
- fetcher->SaveResponseToTemporaryFile(task_runner);
- }
- fetcher->Start();
-}
-
-// Returns true if the url request of |fetcher| was succesful.
-bool FetchSuccess(const net::URLFetcher& fetcher) {
- return (fetcher.GetStatus().status() == net::URLRequestStatus::SUCCESS) &&
- (fetcher.GetResponseCode() == 200);
-}
-
-// Returns the error code which occured during the fetch.The function returns 0
-// if the fetch was successful. If errors happen, the function could return a
-// network error, an http response code, or the status of the fetch, if the
-// fetch is pending or canceled.
-int GetFetchError(const net::URLFetcher& fetcher) {
- if (FetchSuccess(fetcher))
- return 0;
-
- const net::URLRequestStatus::Status status(fetcher.GetStatus().status());
- if (status == net::URLRequestStatus::FAILED)
- return fetcher.GetStatus().error();
-
- if (status == net::URLRequestStatus::IO_PENDING ||
- status == net::URLRequestStatus::CANCELED)
- return status;
-
- const int response_code(fetcher.GetResponseCode());
- if (status == net::URLRequestStatus::SUCCESS && response_code != 200)
- return response_code;
-
- return -1;
- }
-
-// Returns true if a differential update is available for the update item.
-bool IsDiffUpdateAvailable(const CrxUpdateItem* update_item) {
- return update_item->diff_crx_url.is_valid();
+ return proposed_ver.IsValid() && current.CompareTo(proposed_ver) < 0;
}
// Returns true if a differential update is available, it has not failed yet,
// and the configuration allows it.
bool CanTryDiffUpdate(const CrxUpdateItem* update_item,
const ComponentUpdateService::Configurator& config) {
- return IsDiffUpdateAvailable(update_item) &&
- !update_item->diff_update_failed &&
+ return HasDiffUpdate(update_item) && !update_item->diff_update_failed &&
config.DeltasEnabled();
}
+void AppendDownloadMetrics(
+ const std::vector<CrxDownloader::DownloadMetrics>& source,
+ std::vector<CrxDownloader::DownloadMetrics>* destination) {
+ destination->insert(destination->end(), source.begin(), source.end());
+}
+
} // namespace
CrxUpdateItem::CrxUpdateItem()
}
CrxComponent::CrxComponent()
- : installer(NULL),
- observer(NULL) {
+ : installer(NULL), allow_background_download(true) {
}
CrxComponent::~CrxComponent() {
}
-std::string GetCrxComponentID(const CrxComponent& component) {
- return HexStringToID(StringToLowerASCII(base::HexEncode(&component.pk_hash[0],
- component.pk_hash.size()/2)));
-}
-
-CrxComponentInfo::CrxComponentInfo() {
-}
-
-CrxComponentInfo::~CrxComponentInfo() {
-}
-
///////////////////////////////////////////////////////////////////////////////
// In charge of blocking url requests until the |crx_id| component has been
// updated. This class is touched solely from the IO thread. The UI thread
// unless the CrxUpdateService calls Unblock().
// The lifetime is controlled by Chrome's resource loader so the component
// updater cannot touch objects from this class except via weak pointers.
-class CUResourceThrottle
- : public content::ResourceThrottle,
- public base::SupportsWeakPtr<CUResourceThrottle> {
+class CUResourceThrottle : public content::ResourceThrottle,
+ public base::SupportsWeakPtr<CUResourceThrottle> {
public:
explicit CUResourceThrottle(const net::URLRequest* request);
virtual ~CUResourceThrottle();
+
// Overriden from ResourceThrottle.
virtual void WillStartRequest(bool* defer) OVERRIDE;
virtual void WillRedirectRequest(const GURL& new_url, bool* defer) OVERRIDE;
+ virtual const char* GetNameForLogging() const OVERRIDE;
// Component updater calls this function via PostTask to unblock the request.
void Unblock();
typedef std::vector<base::WeakPtr<CUResourceThrottle> > WeakPtrVector;
private:
- enum State {
- NEW,
- BLOCKED,
- UNBLOCKED
- };
+ enum State { NEW, BLOCKED, UNBLOCKED };
- State state_;
+ State state_;
};
void UnblockResourceThrottle(base::WeakPtr<CUResourceThrottle> rt) {
- BrowserThread::PostTask(
- BrowserThread::IO,
- FROM_HERE,
- base::Bind(&CUResourceThrottle::Unblock, rt));
+ BrowserThread::PostTask(BrowserThread::IO,
+ FROM_HERE,
+ base::Bind(&CUResourceThrottle::Unblock, rt));
}
void UnblockandReapAllThrottles(CUResourceThrottle::WeakPtrVector* throttles) {
// the tasks. Also when we do network requests there is only one |url_fetcher_|
// in flight at a time.
// There are no locks in this code, the main structure |work_items_| is mutated
-// only from the UI thread. The unpack and installation is done in the file
-// thread and the network requests are done in the IO thread and in the file
+// only from the UI thread. The unpack and installation is done in a blocking
+// pool thread. The network requests are done in the IO thread or in the file
// thread.
-class CrxUpdateService : public ComponentUpdateService {
+class CrxUpdateService : public ComponentUpdateService, public OnDemandUpdater {
public:
explicit CrxUpdateService(ComponentUpdateService::Configurator* config);
-
virtual ~CrxUpdateService();
// Overrides for ComponentUpdateService.
+ virtual void AddObserver(Observer* observer) OVERRIDE;
+ virtual void RemoveObserver(Observer* observer) OVERRIDE;
virtual Status Start() OVERRIDE;
virtual Status Stop() OVERRIDE;
virtual Status RegisterComponent(const CrxComponent& component) OVERRIDE;
- virtual Status OnDemandUpdate(const std::string& component_id) OVERRIDE;
- virtual void GetComponents(
- std::vector<CrxComponentInfo>* components) OVERRIDE;
- virtual content::ResourceThrottle* GetOnDemandResourceThrottle(
- net::URLRequest* request, const std::string& crx_id) OVERRIDE;
-
- // The only purpose of this class is to forward the
- // UtilityProcessHostClient callbacks so CrxUpdateService does
- // not have to derive from it because that is refcounted.
- class ManifestParserBridge : public UtilityProcessHostClient {
- public:
- explicit ManifestParserBridge(CrxUpdateService* service)
- : service_(service) {}
-
- virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
- bool handled = true;
- IPC_BEGIN_MESSAGE_MAP(ManifestParserBridge, message)
- IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded,
- OnParseUpdateManifestSucceeded)
- IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Failed,
- OnParseUpdateManifestFailed)
- IPC_MESSAGE_UNHANDLED(handled = false)
- IPC_END_MESSAGE_MAP()
- return handled;
- }
-
- private:
- virtual ~ManifestParserBridge() {}
+ virtual std::vector<std::string> GetComponentIDs() const OVERRIDE;
+ virtual bool GetComponentDetails(const std::string& component_id,
+ CrxUpdateItem* item) const OVERRIDE;
+ virtual OnDemandUpdater& GetOnDemandUpdater() OVERRIDE;
- // Omaha update response XML was successfully parsed.
- void OnParseUpdateManifestSucceeded(const UpdateManifest::Results& r) {
- service_->OnParseUpdateManifestSucceeded(r);
- }
- // Omaha update response XML could not be parsed.
- void OnParseUpdateManifestFailed(const std::string& e) {
- service_->OnParseUpdateManifestFailed(e);
- }
-
- CrxUpdateService* service_;
- DISALLOW_COPY_AND_ASSIGN(ManifestParserBridge);
- };
-
- // Context for a update check url request. See DelegateWithContext above.
- struct UpdateContext {
- base::Time start;
- UpdateContext() : start(base::Time::Now()) {}
- };
+ // Overrides for OnDemandUpdater.
+ virtual content::ResourceThrottle* GetOnDemandResourceThrottle(
+ net::URLRequest* request,
+ const std::string& crx_id) OVERRIDE;
+ virtual Status OnDemandUpdate(const std::string& component_id) OVERRIDE;
- // Context for a crx download url request. See DelegateWithContext above.
+ // Context for a crx download url request.
struct CRXContext {
ComponentInstaller* installer;
std::vector<uint8> pk_hash;
CRXContext() : installer(NULL) {}
};
- void OnURLFetchComplete(const net::URLFetcher* source,
- UpdateContext* context);
-
- void OnURLFetchComplete(const net::URLFetcher* source,
- CRXContext* context);
-
private:
enum ErrorCategory {
kErrorNone = 0,
kStepDelayLong,
};
- // See ManifestParserBridge.
- void OnParseUpdateManifestSucceeded(const UpdateManifest::Results& results);
+ void UpdateCheckComplete(int error,
+ const std::string& error_message,
+ const UpdateResponse::Results& results);
+ void OnUpdateCheckSucceeded(const UpdateResponse::Results& results);
+ void OnUpdateCheckFailed(int error, const std::string& error_message);
- // See ManifestParserBridge.
- void OnParseUpdateManifestFailed(const std::string& error_message);
+ void DownloadProgress(const std::string& component_id,
+ const CrxDownloader::Result& download_result);
- bool AddItemToUpdateCheck(CrxUpdateItem* item, std::string* query);
+ void DownloadComplete(scoped_ptr<CRXContext> crx_context,
+ const CrxDownloader::Result& download_result);
Status OnDemandUpdateInternal(CrxUpdateItem* item);
+ Status OnDemandUpdateWithCooldown(CrxUpdateItem* item);
void ProcessPendingItems();
- CrxUpdateItem* FindReadyComponent();
-
- void UpdateComponent(CrxUpdateItem* workitem);
+ // Find a component that is ready to update.
+ CrxUpdateItem* FindReadyComponent() const;
- void AddUpdateCheckItems(std::string* query);
+ // Prepares the components for an update check and initiates the request.
+ // Returns true if an update check request has been made. Returns false if
+ // no update check was needed or an error occured.
+ bool CheckForUpdates();
- void DoUpdateCheck(const std::string& query);
+ void UpdateComponent(CrxUpdateItem* workitem);
void ScheduleNextRun(StepDelayInterval step_delay);
- void ParseManifest(const std::string& xml);
+ void ParseResponse(const std::string& xml);
- void Install(const CRXContext* context, const base::FilePath& crx_path);
+ void Install(scoped_ptr<CRXContext> context, const base::FilePath& crx_path);
+
+ void EndUnpacking(const std::string& component_id,
+ const base::FilePath& crx_path,
+ ComponentUnpacker::Error error,
+ int extended_error);
void DoneInstalling(const std::string& component_id,
ComponentUnpacker::Error error,
void ChangeItemState(CrxUpdateItem* item, CrxUpdateItem::Status to);
- size_t ChangeItemStatus(CrxUpdateItem::Status from,
- CrxUpdateItem::Status to);
+ size_t ChangeItemStatus(CrxUpdateItem::Status from, CrxUpdateItem::Status to);
- CrxUpdateItem* FindUpdateItemById(const std::string& id);
+ CrxUpdateItem* FindUpdateItemById(const std::string& id) const;
- void NotifyComponentObservers(ComponentObserver::Events event,
- int extra) const;
+ void NotifyObservers(Observer::Events event, const std::string& id);
bool HasOnDemandItems() const;
void OnNewResourceThrottle(base::WeakPtr<CUResourceThrottle> rt,
const std::string& crx_id);
+ Status GetServiceStatus(const CrxUpdateItem::Status status);
+
scoped_ptr<ComponentUpdateService::Configurator> config_;
- scoped_ptr<ComponentPatcher> component_patcher_;
+ scoped_ptr<UpdateChecker> update_checker_;
+
+ scoped_ptr<PingManager> ping_manager_;
- scoped_ptr<net::URLFetcher> url_fetcher_;
+ scoped_refptr<ComponentUnpacker> unpacker_;
- scoped_ptr<component_updater::PingManager> ping_manager_;
+ scoped_ptr<CrxDownloader> crx_downloader_;
// A collection of every work item.
typedef std::vector<CrxUpdateItem*> UpdateItems;
bool running_;
+ ObserverList<Observer> observer_list_;
+
DISALLOW_COPY_AND_ASSIGN(CrxUpdateService);
};
CrxUpdateService::CrxUpdateService(ComponentUpdateService::Configurator* config)
: config_(config),
- component_patcher_(config->CreateComponentPatcher()),
- ping_manager_(new component_updater::PingManager(
- config->PingUrl(),
- config->RequestContext())),
- blocking_task_runner_(BrowserThread::GetBlockingPool()->
- GetSequencedTaskRunnerWithShutdownBehavior(
- BrowserThread::GetBlockingPool()->GetSequenceToken(),
- base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)),
+ ping_manager_(
+ new PingManager(config->PingUrl(), config->RequestContext())),
+ blocking_task_runner_(
+ BrowserThread::GetBlockingPool()->
+ GetSequencedTaskRunnerWithShutdownBehavior(
+ BrowserThread::GetBlockingPool()->GetSequenceToken(),
+ base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)),
chrome_version_(chrome::VersionInfo().Version()),
running_(false) {
}
STLDeleteElements(&work_items_);
}
+void CrxUpdateService::AddObserver(Observer* observer) {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ observer_list_.AddObserver(observer);
+}
+
+void CrxUpdateService::RemoveObserver(Observer* observer) {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ observer_list_.RemoveObserver(observer);
+}
+
ComponentUpdateService::Status CrxUpdateService::Start() {
// Note that RegisterComponent will call Start() when the first
// component is registered, so it can be called twice. This way
// we avoid scheduling the timer if there is no work to do.
+ VLOG(1) << "CrxUpdateService starting up";
running_ = true;
if (work_items_.empty())
return kOk;
- NotifyComponentObservers(ComponentObserver::COMPONENT_UPDATER_STARTED, 0);
+ NotifyObservers(Observer::COMPONENT_UPDATER_STARTED, "");
- timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->InitialDelay()),
- this, &CrxUpdateService::ProcessPendingItems);
+ VLOG(1) << "First update attempt will take place in "
+ << config_->InitialDelay() << " seconds";
+ timer_.Start(FROM_HERE,
+ base::TimeDelta::FromSeconds(config_->InitialDelay()),
+ this,
+ &CrxUpdateService::ProcessPendingItems);
return kOk;
}
// Stop the main check + update loop. In flight operations will be
// completed.
ComponentUpdateService::Status CrxUpdateService::Stop() {
+ VLOG(1) << "CrxUpdateService stopping";
running_ = false;
timer_.Stop();
return kOk;
bool CrxUpdateService::HasOnDemandItems() const {
class Helper {
public:
- static bool IsOnDemand(CrxUpdateItem* item) {
- return item->on_demand;
- }
+ static bool IsOnDemand(CrxUpdateItem* item) { return item->on_demand; }
};
return std::find_if(work_items_.begin(),
work_items_.end(),
// components.
void CrxUpdateService::ScheduleNextRun(StepDelayInterval step_delay) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- DCHECK(url_fetcher_.get() == NULL);
+ DCHECK(!update_checker_);
CHECK(!timer_.IsRunning());
// It could be the case that Stop() had been called while a url request
// or unpacking was in flight, if so we arrive here but |running_| is
}
if (step_delay != kStepDelayShort) {
- NotifyComponentObservers(ComponentObserver::COMPONENT_UPDATER_SLEEPING, 0);
+ NotifyObservers(Observer::COMPONENT_UPDATER_SLEEPING, "");
// Zero is only used for unit tests.
if (0 == delay_seconds)
return;
}
- timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(delay_seconds),
- this, &CrxUpdateService::ProcessPendingItems);
+ VLOG(1) << "Scheduling next run to occur in " << delay_seconds << " seconds";
+ timer_.Start(FROM_HERE,
+ base::TimeDelta::FromSeconds(delay_seconds),
+ this,
+ &CrxUpdateService::ProcessPendingItems);
}
// Given a extension-like component id, find the associated component.
-CrxUpdateItem* CrxUpdateService::FindUpdateItemById(const std::string& id) {
+CrxUpdateItem* CrxUpdateService::FindUpdateItemById(
+ const std::string& id) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CrxUpdateItem::FindById finder(id);
- UpdateItems::iterator it = std::find_if(work_items_.begin(),
- work_items_.end(),
- finder);
- if (it == work_items_.end())
- return NULL;
- return (*it);
+ UpdateItems::const_iterator it =
+ std::find_if(work_items_.begin(), work_items_.end(), finder);
+ return it != work_items_.end() ? *it : NULL;
}
// Changes a component's status, clearing on_demand and firing notifications as
void CrxUpdateService::ChangeItemState(CrxUpdateItem* item,
CrxUpdateItem::Status to) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- if (to == CrxUpdateItem::kNoUpdate ||
- to == CrxUpdateItem::kUpdated ||
+ if (to == CrxUpdateItem::kNoUpdate || to == CrxUpdateItem::kUpdated ||
to == CrxUpdateItem::kUpToDate) {
item->on_demand = false;
}
item->status = to;
- ComponentObserver* observer = item->component.observer;
- if (observer) {
- switch (to) {
- case CrxUpdateItem::kCanUpdate:
- observer->OnEvent(ComponentObserver::COMPONENT_UPDATE_FOUND, 0);
- break;
- case CrxUpdateItem::kUpdatingDiff:
- case CrxUpdateItem::kUpdating:
- observer->OnEvent(ComponentObserver::COMPONENT_UPDATE_READY, 0);
- break;
- case CrxUpdateItem::kUpdated:
- observer->OnEvent(ComponentObserver::COMPONENT_UPDATED, 0);
- break;
- case CrxUpdateItem::kUpToDate:
- case CrxUpdateItem::kNoUpdate:
- observer->OnEvent(ComponentObserver::COMPONENT_NOT_UPDATED, 0);
- break;
- case CrxUpdateItem::kNew:
- case CrxUpdateItem::kChecking:
- case CrxUpdateItem::kDownloading:
- case CrxUpdateItem::kDownloadingDiff:
- case CrxUpdateItem::kLastStatus:
- // No notification for these states.
- break;
- }
+ switch (to) {
+ case CrxUpdateItem::kCanUpdate:
+ NotifyObservers(Observer::COMPONENT_UPDATE_FOUND, item->id);
+ break;
+ case CrxUpdateItem::kUpdatingDiff:
+ case CrxUpdateItem::kUpdating:
+ NotifyObservers(Observer::COMPONENT_UPDATE_READY, item->id);
+ break;
+ case CrxUpdateItem::kUpdated:
+ NotifyObservers(Observer::COMPONENT_UPDATED, item->id);
+ break;
+ case CrxUpdateItem::kUpToDate:
+ case CrxUpdateItem::kNoUpdate:
+ NotifyObservers(Observer::COMPONENT_NOT_UPDATED, item->id);
+ break;
+ case CrxUpdateItem::kNew:
+ case CrxUpdateItem::kChecking:
+ case CrxUpdateItem::kDownloading:
+ case CrxUpdateItem::kDownloadingDiff:
+ case CrxUpdateItem::kLastStatus:
+ // No notification for these states.
+ break;
}
// Free possible pending network requests.
- if ((to == CrxUpdateItem::kUpdated) ||
- (to == CrxUpdateItem::kUpToDate) ||
+ if ((to == CrxUpdateItem::kUpdated) || (to == CrxUpdateItem::kUpToDate) ||
(to == CrxUpdateItem::kNoUpdate)) {
UnblockandReapAllThrottles(&item->throttles);
}
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
size_t count = 0;
for (UpdateItems::iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
+ it != work_items_.end();
+ ++it) {
CrxUpdateItem* item = *it;
- if (item->status != from)
- continue;
- ChangeItemState(item, to);
- ++count;
+ if (item->status == from) {
+ ChangeItemState(item, to);
+ ++count;
+ }
}
return count;
}
// Adds a component to be checked for upgrades. If the component exists it
// it will be replaced and the return code is kReplaced.
-//
-// TODO(cpu): Evaluate if we want to support un-registration.
ComponentUpdateService::Status CrxUpdateService::RegisterComponent(
const CrxComponent& component) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- if (component.pk_hash.empty() ||
- !component.version.IsValid() ||
+ if (component.pk_hash.empty() || !component.version.IsValid() ||
!component.installer)
return kError;
- std::string id =
- HexStringToID(StringToLowerASCII(base::HexEncode(&component.pk_hash[0],
- component.pk_hash.size()/2)));
- CrxUpdateItem* uit;
- uit = FindUpdateItemById(id);
+ std::string id(GetCrxComponentID(component));
+ CrxUpdateItem* uit = FindUpdateItemById(id);
if (uit) {
uit->component = component;
return kReplaced;
uit->component = component;
work_items_.push_back(uit);
- // If this is the first component registered we call Start to
- // schedule the first timer.
- if (running_ && (work_items_.size() == 1))
- Start();
-
- return kOk;
-}
-
-// Sets a component to be checked for updates.
-// The component to add is |item| and the |query| string is modified with the
-// required omaha compatible query. Returns false when the query string is
-// longer than specified by UrlSizeLimit().
-bool CrxUpdateService::AddItemToUpdateCheck(CrxUpdateItem* item,
- std::string* query) {
- if (!AddQueryString(item->id,
- item->component.version.GetString(),
- item->component.fingerprint,
- item->on_demand,
- config_->UrlSizeLimit(),
- query))
- return false;
-
- ChangeItemState(item, CrxUpdateItem::kChecking);
- item->last_check = base::Time::Now();
- item->previous_version = item->component.version;
- item->next_version = Version();
- item->previous_fp = item->component.fingerprint;
- item->next_fp.clear();
- item->diff_update_failed = false;
- item->error_category = 0;
- item->error_code = 0;
- item->extra_code1 = 0;
- item->diff_error_category = 0;
- item->diff_error_code = 0;
- item->diff_extra_code1 = 0;
- return true;
-}
-
-// Start the process of checking for an update, for a particular component
-// that was previously registered.
-// |component_id| is a value returned from GetCrxComponentID().
-ComponentUpdateService::Status CrxUpdateService::OnDemandUpdate(
- const std::string& component_id) {
- return OnDemandUpdateInternal(FindUpdateItemById(component_id));
-}
-ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateInternal(
- CrxUpdateItem* uit) {
- if (!uit)
- return kError;
- // Check if the request is too soon.
- base::TimeDelta delta = base::Time::Now() - uit->last_check;
- if (delta < base::TimeDelta::FromSeconds(config_->OnDemandDelay()))
- return kError;
-
- switch (uit->status) {
- // If the item is already in the process of being updated, there is
- // no point in this call, so return kInProgress.
- case CrxUpdateItem::kChecking:
- case CrxUpdateItem::kCanUpdate:
- case CrxUpdateItem::kDownloadingDiff:
- case CrxUpdateItem::kDownloading:
- case CrxUpdateItem::kUpdatingDiff:
- case CrxUpdateItem::kUpdating:
- return kInProgress;
- // Otherwise the item was already checked a while back (or it is new),
- // set its status to kNew to give it a slightly higher priority.
- case CrxUpdateItem::kNew:
- case CrxUpdateItem::kUpdated:
- case CrxUpdateItem::kUpToDate:
- case CrxUpdateItem::kNoUpdate:
- ChangeItemState(uit, CrxUpdateItem::kNew);
- uit->on_demand = true;
- break;
- case CrxUpdateItem::kLastStatus:
- NOTREACHED() << uit->status;
- }
-
- // In case the current delay is long, set the timer to a shorter value
- // to get the ball rolling.
- if (timer_.IsRunning()) {
- timer_.Stop();
- timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->StepDelay()),
- this, &CrxUpdateService::ProcessPendingItems);
+ // If this is the first component registered we call Start to
+ // schedule the first timer. Otherwise, reset the timer to trigger another
+ // pass over the work items, if the component updater is sleeping, fact
+ // indicated by a running timer. If the timer is not running, it means that
+ // the service is busy updating something, and in that case, this component
+ // will be picked up at the next pass.
+ if (running_) {
+ if (work_items_.size() == 1) {
+ Start();
+ } else if (timer_.IsRunning()) {
+ timer_.Start(FROM_HERE,
+ base::TimeDelta::FromSeconds(config_->InitialDelay()),
+ this,
+ &CrxUpdateService::ProcessPendingItems);
+ }
}
return kOk;
}
-void CrxUpdateService::GetComponents(
- std::vector<CrxComponentInfo>* components) {
+std::vector<std::string> CrxUpdateService::GetComponentIDs() const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ std::vector<std::string> component_ids;
for (UpdateItems::const_iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
+ it != work_items_.end();
+ ++it) {
const CrxUpdateItem* item = *it;
- CrxComponentInfo info;
- info.id = GetCrxComponentID(item->component);
- info.version = item->component.version.GetString();
- info.name = item->component.name;
- components->push_back(info);
+ component_ids.push_back(item->id);
}
+ return component_ids;
+}
+
+bool CrxUpdateService::GetComponentDetails(const std::string& component_id,
+ CrxUpdateItem* item) const {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ const CrxUpdateItem* crx_update_item(FindUpdateItemById(component_id));
+ if (crx_update_item)
+ *item = *crx_update_item;
+ return crx_update_item != NULL;
}
-// This is the main loop of the component updater.
+OnDemandUpdater& CrxUpdateService::GetOnDemandUpdater() {
+ return *this;
+}
+
+// This is the main loop of the component updater. It updates one component
+// at a time if updates are available. Otherwise, it does an update check or
+// takes a long sleep until the loop runs again.
void CrxUpdateService::ProcessPendingItems() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+
CrxUpdateItem* ready_upgrade = FindReadyComponent();
if (ready_upgrade) {
UpdateComponent(ready_upgrade);
return;
}
- std::string query;
- AddUpdateCheckItems(&query);
- if (!query.empty()) {
- DoUpdateCheck(query);
- return;
- }
- // No components to update. The next check will be after a long sleep.
- ScheduleNextRun(kStepDelayLong);
+
+ if (!CheckForUpdates())
+ ScheduleNextRun(kStepDelayLong);
}
-CrxUpdateItem* CrxUpdateService::FindReadyComponent() {
+CrxUpdateItem* CrxUpdateService::FindReadyComponent() const {
class Helper {
public:
static bool IsReadyOnDemand(CrxUpdateItem* item) {
}
};
- std::vector<CrxUpdateItem*>::iterator it = std::find_if(
+ std::vector<CrxUpdateItem*>::const_iterator it = std::find_if(
work_items_.begin(), work_items_.end(), Helper::IsReadyOnDemand);
if (it != work_items_.end())
return *it;
return NULL;
}
-void CrxUpdateService::UpdateComponent(CrxUpdateItem* workitem) {
- CRXContext* context = new CRXContext;
- context->pk_hash = workitem->component.pk_hash;
- context->id = workitem->id;
- context->installer = workitem->component.installer;
- context->fingerprint = workitem->next_fp;
- GURL package_url;
- if (CanTryDiffUpdate(workitem, *config_)) {
- package_url = workitem->diff_crx_url;
- ChangeItemState(workitem, CrxUpdateItem::kDownloadingDiff);
- } else {
- package_url = workitem->crx_url;
- ChangeItemState(workitem, CrxUpdateItem::kDownloading);
- }
- url_fetcher_.reset(net::URLFetcher::Create(
- 0, package_url, net::URLFetcher::GET,
- MakeContextDelegate(this, context)));
- StartFetch(url_fetcher_.get(),
- config_->RequestContext(),
- true,
- blocking_task_runner_);
-}
-
-// Given that our |work_items_| list is expected to contain relatively few
-// items, we simply loop several times.
-void CrxUpdateService::AddUpdateCheckItems(std::string* query){
- for (UpdateItems::const_iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
- CrxUpdateItem* item = *it;
- if (item->status != CrxUpdateItem::kNew)
- continue;
- if (!AddItemToUpdateCheck(item, query))
- break;
- }
-
- // Next we can go back to components we already checked, here
- // we can also batch them in a single url request, as long as
- // we have not checked them recently.
- const base::TimeDelta min_delta_time =
+// Prepares the components for an update check and initiates the request.
+// On demand components are always included in the update check request.
+// Otherwise, only include components that have not been checked recently.
+bool CrxUpdateService::CheckForUpdates() {
+ const base::TimeDelta minimum_recheck_wait_time =
base::TimeDelta::FromSeconds(config_->MinimumReCheckWait());
-
- for (UpdateItems::const_iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
- CrxUpdateItem* item = *it;
- if ((item->status != CrxUpdateItem::kNoUpdate) &&
- (item->status != CrxUpdateItem::kUpToDate))
- continue;
- base::TimeDelta delta = base::Time::Now() - item->last_check;
- if (delta < min_delta_time)
+ const base::Time now(base::Time::Now());
+
+ std::vector<CrxUpdateItem*> items_to_check;
+ for (size_t i = 0; i != work_items_.size(); ++i) {
+ CrxUpdateItem* item = work_items_[i];
+ DCHECK(item->status == CrxUpdateItem::kNew ||
+ item->status == CrxUpdateItem::kNoUpdate ||
+ item->status == CrxUpdateItem::kUpToDate ||
+ item->status == CrxUpdateItem::kUpdated);
+
+ const base::TimeDelta time_since_last_checked(now - item->last_check);
+
+ if (!item->on_demand &&
+ time_since_last_checked < minimum_recheck_wait_time) {
+ VLOG(1) << "Skipping check for component update: id=" << item->id
+ << ", time_since_last_checked="
+ << time_since_last_checked.InSeconds()
+ << " seconds: too soon to check for an update";
continue;
- if (!AddItemToUpdateCheck(item, query))
- break;
- }
+ }
- // Finally, we check components that we already updated as long as
- // we have not checked them recently.
- for (UpdateItems::const_iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
- CrxUpdateItem* item = *it;
- if (item->status != CrxUpdateItem::kUpdated)
- continue;
- base::TimeDelta delta = base::Time::Now() - item->last_check;
- if (delta < min_delta_time)
- continue;
- if (!AddItemToUpdateCheck(item, query))
- break;
+ VLOG(1) << "Scheduling update check for component id=" << item->id
+ << ", time_since_last_checked="
+ << time_since_last_checked.InSeconds() << " seconds";
+
+ item->last_check = now;
+ item->crx_urls.clear();
+ item->crx_diffurls.clear();
+ item->previous_version = item->component.version;
+ item->next_version = Version();
+ item->previous_fp = item->component.fingerprint;
+ item->next_fp.clear();
+ item->diff_update_failed = false;
+ item->error_category = 0;
+ item->error_code = 0;
+ item->extra_code1 = 0;
+ item->diff_error_category = 0;
+ item->diff_error_code = 0;
+ item->diff_extra_code1 = 0;
+ item->download_metrics.clear();
+
+ items_to_check.push_back(item);
+
+ ChangeItemState(item, CrxUpdateItem::kChecking);
}
-}
-void CrxUpdateService::DoUpdateCheck(const std::string& query) {
- const std::string full_query =
- MakeFinalQuery(config_->UpdateUrl().spec(),
- query,
- config_->ExtraRequestParams());
-
- url_fetcher_.reset(net::URLFetcher::Create(
- 0, GURL(full_query), net::URLFetcher::GET,
- MakeContextDelegate(this, new UpdateContext())));
- StartFetch(url_fetcher_.get(),
- config_->RequestContext(),
- false,
- blocking_task_runner_);
+ if (items_to_check.empty())
+ return false;
+
+ update_checker_ =
+ UpdateChecker::Create(config_->UpdateUrl(),
+ config_->RequestContext(),
+ base::Bind(&CrxUpdateService::UpdateCheckComplete,
+ base::Unretained(this))).Pass();
+ return update_checker_->CheckForUpdates(items_to_check,
+ config_->ExtraRequestParams());
}
-// Called when we got a response from the update server. It consists of an xml
-// document following the omaha update scheme.
-void CrxUpdateService::OnURLFetchComplete(const net::URLFetcher* source,
- UpdateContext* context) {
- DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- if (FetchSuccess(*source)) {
- std::string xml;
- source->GetResponseAsString(&xml);
- url_fetcher_.reset();
- ParseManifest(xml);
+void CrxUpdateService::UpdateComponent(CrxUpdateItem* workitem) {
+ scoped_ptr<CRXContext> crx_context(new CRXContext);
+ crx_context->pk_hash = workitem->component.pk_hash;
+ crx_context->id = workitem->id;
+ crx_context->installer = workitem->component.installer;
+ crx_context->fingerprint = workitem->next_fp;
+ const std::vector<GURL>* urls = NULL;
+ bool allow_background_download = false;
+ if (CanTryDiffUpdate(workitem, *config_)) {
+ urls = &workitem->crx_diffurls;
+ ChangeItemState(workitem, CrxUpdateItem::kDownloadingDiff);
} else {
- url_fetcher_.reset();
- CrxUpdateService::OnParseUpdateManifestFailed("network error");
+ // Background downloads are enabled only for selected components and
+ // only for full downloads (see issue 340448).
+ allow_background_download = workitem->component.allow_background_download;
+ urls = &workitem->crx_urls;
+ ChangeItemState(workitem, CrxUpdateItem::kDownloading);
}
- delete context;
+
+ // On demand component updates are always downloaded in foreground.
+ const bool is_background_download = !workitem->on_demand &&
+ allow_background_download &&
+ config_->UseBackgroundDownloader();
+
+ crx_downloader_.reset(CrxDownloader::Create(is_background_download,
+ config_->RequestContext(),
+ blocking_task_runner_));
+ crx_downloader_->set_progress_callback(
+ base::Bind(&CrxUpdateService::DownloadProgress,
+ base::Unretained(this),
+ crx_context->id));
+ crx_downloader_->StartDownload(*urls,
+ base::Bind(&CrxUpdateService::DownloadComplete,
+ base::Unretained(this),
+ base::Passed(&crx_context)));
}
-// Parsing the manifest is either done right now for tests or in a sandboxed
-// process for the production environment. This mitigates the case where an
-// attacker was able to feed us a malicious xml string.
-void CrxUpdateService::ParseManifest(const std::string& xml) {
+void CrxUpdateService::UpdateCheckComplete(
+ int error,
+ const std::string& error_message,
+ const UpdateResponse::Results& results) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- if (config_->InProcess()) {
- UpdateManifest manifest;
- if (!manifest.Parse(xml))
- CrxUpdateService::OnParseUpdateManifestFailed(manifest.errors());
- else
- CrxUpdateService::OnParseUpdateManifestSucceeded(manifest.results());
- } else {
- UtilityProcessHost* host =
- UtilityProcessHost::Create(new ManifestParserBridge(this),
- base::MessageLoopProxy::current().get());
- host->EnableZygote();
- host->Send(new ChromeUtilityMsg_ParseUpdateManifest(xml));
- }
+ update_checker_.reset();
+ if (!error)
+ OnUpdateCheckSucceeded(results);
+ else
+ OnUpdateCheckFailed(error, error_message);
}
-// A valid Omaha update check has arrived, from only the list of components that
-// we are currently upgrading we check for a match in which the server side
-// version is newer, if so we queue them for an upgrade. The next time we call
-// ProcessPendingItems() one of them will be drafted for the upgrade process.
-void CrxUpdateService::OnParseUpdateManifestSucceeded(
- const UpdateManifest::Results& results) {
+// Handles a valid Omaha update check response by matching the results with
+// the registered components which were checked for updates.
+// If updates are found, prepare the components for the actual version upgrade.
+// One of these components will be drafted for the upgrade next time
+// ProcessPendingItems is called.
+void CrxUpdateService::OnUpdateCheckSucceeded(
+ const UpdateResponse::Results& results) {
+ size_t num_updates_pending = 0;
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- size_t update_pending = 0;
- std::vector<UpdateManifest::Result>::const_iterator it;
+ VLOG(1) << "Update check succeeded.";
+ std::vector<UpdateResponse::Result>::const_iterator it;
for (it = results.list.begin(); it != results.list.end(); ++it) {
CrxUpdateItem* crx = FindUpdateItemById(it->extension_id);
if (!crx)
continue;
- if (crx->status != CrxUpdateItem::kChecking)
+ if (crx->status != CrxUpdateItem::kChecking) {
+ NOTREACHED();
continue; // Not updating this component now.
+ }
- if (it->version.empty()) {
+ if (it->manifest.version.empty()) {
// No version means no update available.
ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
+ VLOG(1) << "No update available for component: " << crx->id;
continue;
}
- if (!IsVersionNewer(crx->component.version, it->version)) {
- // Our component is up to date.
+
+ if (!IsVersionNewer(crx->component.version, it->manifest.version)) {
+ // The component is up to date.
ChangeItemState(crx, CrxUpdateItem::kUpToDate);
+ VLOG(1) << "Component already up-to-date: " << crx->id;
continue;
}
- if (!it->browser_min_version.empty()) {
- if (IsVersionNewer(chrome_version_, it->browser_min_version)) {
- // Does not apply for this chrome version.
+
+ if (!it->manifest.browser_min_version.empty()) {
+ if (IsVersionNewer(chrome_version_, it->manifest.browser_min_version)) {
+ // The component is not compatible with this Chrome version.
+ VLOG(1) << "Ignoring incompatible component: " << crx->id;
ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
continue;
}
}
- // All test passed. Queue an upgrade for this component and fire the
- // notifications.
- crx->crx_url = it->crx_url;
- crx->diff_crx_url = it->diff_crx_url;
+
+ if (it->manifest.packages.size() != 1) {
+ // Assume one and only one package per component.
+ VLOG(1) << "Ignoring multiple packages for component: " << crx->id;
+ ChangeItemState(crx, CrxUpdateItem::kNoUpdate);
+ continue;
+ }
+
+ // Parse the members of the result and queue an upgrade for this component.
+ crx->next_version = Version(it->manifest.version);
+
+ VLOG(1) << "Update found for component: " << crx->id;
+
+ typedef UpdateResponse::Result::Manifest::Package Package;
+ const Package& package(it->manifest.packages[0]);
+ crx->next_fp = package.fingerprint;
+
+ // Resolve the urls by combining the base urls with the package names.
+ for (size_t i = 0; i != it->crx_urls.size(); ++i) {
+ const GURL url(it->crx_urls[i].Resolve(package.name));
+ if (url.is_valid())
+ crx->crx_urls.push_back(url);
+ }
+ for (size_t i = 0; i != it->crx_diffurls.size(); ++i) {
+ const GURL url(it->crx_diffurls[i].Resolve(package.namediff));
+ if (url.is_valid())
+ crx->crx_diffurls.push_back(url);
+ }
+
ChangeItemState(crx, CrxUpdateItem::kCanUpdate);
- crx->next_version = Version(it->version);
- crx->next_fp = it->package_fingerprint;
- ++update_pending;
+ ++num_updates_pending;
}
- // All the components that are not mentioned in the manifest we
- // consider them up to date.
+ // All components that are not included in the update response are
+ // considered up to date.
ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate);
// If there are updates pending we do a short wait, otherwise we take
// a longer delay until we check the components again.
- ScheduleNextRun(update_pending > 0 ? kStepDelayShort : kStepDelayMedium);
+ ScheduleNextRun(num_updates_pending > 0 ? kStepDelayShort : kStepDelayLong);
}
-void CrxUpdateService::OnParseUpdateManifestFailed(
- const std::string& error_message) {
+void CrxUpdateService::OnUpdateCheckFailed(int error,
+ const std::string& error_message) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- size_t count = ChangeItemStatus(CrxUpdateItem::kChecking,
- CrxUpdateItem::kNoUpdate);
+ DCHECK(error);
+ size_t count =
+ ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kNoUpdate);
DCHECK_GT(count, 0ul);
+ VLOG(1) << "Update check failed.";
ScheduleNextRun(kStepDelayLong);
}
+// Called when progress is being made downloading a CRX. The progress may
+// not monotonically increase due to how the CRX downloader switches between
+// different downloaders and fallback urls.
+void CrxUpdateService::DownloadProgress(
+ const std::string& component_id,
+ const CrxDownloader::Result& download_result) {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ NotifyObservers(Observer::COMPONENT_UPDATE_DOWNLOADING, component_id);
+}
+
// Called when the CRX package has been downloaded to a temporary location.
// Here we fire the notifications and schedule the component-specific installer
// to be called in the file thread.
-void CrxUpdateService::OnURLFetchComplete(const net::URLFetcher* source,
- CRXContext* context) {
+void CrxUpdateService::DownloadComplete(
+ scoped_ptr<CRXContext> crx_context,
+ const CrxDownloader::Result& download_result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
- scoped_ptr<CRXContext> crx_context(context);
-
CrxUpdateItem* crx = FindUpdateItemById(crx_context->id);
DCHECK(crx->status == CrxUpdateItem::kDownloadingDiff ||
crx->status == CrxUpdateItem::kDownloading);
- if (!FetchSuccess(*source)) {
+ AppendDownloadMetrics(crx_downloader_->download_metrics(),
+ &crx->download_metrics);
+
+ crx_downloader_.reset();
+
+ if (download_result.error) {
if (crx->status == CrxUpdateItem::kDownloadingDiff) {
crx->diff_error_category = kNetworkError;
- crx->diff_error_code = GetFetchError(*source);
+ crx->diff_error_code = download_result.error;
crx->diff_update_failed = true;
size_t count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff,
CrxUpdateItem::kCanUpdate);
DCHECK_EQ(count, 1ul);
- url_fetcher_.reset();
ScheduleNextRun(kStepDelayShort);
return;
}
crx->error_category = kNetworkError;
- crx->error_code = GetFetchError(*source);
- size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading,
- CrxUpdateItem::kNoUpdate);
+ crx->error_code = download_result.error;
+ size_t count =
+ ChangeItemStatus(CrxUpdateItem::kDownloading, CrxUpdateItem::kNoUpdate);
DCHECK_EQ(count, 1ul);
- url_fetcher_.reset();
// At this point, since both the differential and the full downloads failed,
// the update for this component has finished with an error.
// Move on to the next update, if there is one available.
ScheduleNextRun(kStepDelayMedium);
} else {
- base::FilePath temp_crx_path;
- CHECK(source->GetResponseAsFilePath(true, &temp_crx_path));
-
size_t count = 0;
if (crx->status == CrxUpdateItem::kDownloadingDiff) {
count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff,
}
DCHECK_EQ(count, 1ul);
- url_fetcher_.reset();
-
// Why unretained? See comment at top of file.
blocking_task_runner_->PostDelayedTask(
FROM_HERE,
base::Bind(&CrxUpdateService::Install,
base::Unretained(this),
- crx_context.release(),
- temp_crx_path),
+ base::Passed(&crx_context),
+ download_result.response),
base::TimeDelta::FromMilliseconds(config_->StepDelay()));
}
}
// Install consists of digital signature verification, unpacking and then
// calling the component specific installer. All that is handled by the
-// |unpacker|. If there is an error this function is in charge of deleting
+// |unpacker_|. If there is an error this function is in charge of deleting
// the files created.
-void CrxUpdateService::Install(const CRXContext* context,
+void CrxUpdateService::Install(scoped_ptr<CRXContext> context,
const base::FilePath& crx_path) {
// This function owns the file at |crx_path| and the |context| object.
- ComponentUnpacker unpacker(context->pk_hash,
- crx_path,
- context->fingerprint,
- component_patcher_.get(),
- context->installer);
- if (!base::DeleteFile(crx_path, false))
+ unpacker_ = new ComponentUnpacker(context->pk_hash,
+ crx_path,
+ context->fingerprint,
+ context->installer,
+ config_->InProcess(),
+ blocking_task_runner_);
+ unpacker_->Unpack(base::Bind(&CrxUpdateService::EndUnpacking,
+ base::Unretained(this),
+ context->id,
+ crx_path));
+}
+
+void CrxUpdateService::EndUnpacking(const std::string& component_id,
+ const base::FilePath& crx_path,
+ ComponentUnpacker::Error error,
+ int extended_error) {
+ if (!DeleteFileAndEmptyParentDirectory(crx_path))
NOTREACHED() << crx_path.value();
- // Why unretained? See comment at top of file.
BrowserThread::PostDelayedTask(
BrowserThread::UI,
FROM_HERE,
- base::Bind(&CrxUpdateService::DoneInstalling, base::Unretained(this),
- context->id, unpacker.error(), unpacker.extended_error()),
+ base::Bind(&CrxUpdateService::DoneInstalling,
+ base::Unretained(this),
+ component_id,
+ error,
+ extended_error),
base::TimeDelta::FromMilliseconds(config_->StepDelay()));
- delete context;
+ // Reset the unpacker last, otherwise we free our own arguments.
+ unpacker_ = NULL;
}
// Installation has been completed. Adjust the component status and
DCHECK_EQ(count, 1ul);
ScheduleNextRun(kStepDelayShort);
return;
- }
+ }
if (is_success) {
- ChangeItemState(item, CrxUpdateItem::kUpdated);
item->component.version = item->next_version;
item->component.fingerprint = item->next_fp;
+ ChangeItemState(item, CrxUpdateItem::kUpdated);
} else {
- ChangeItemState(item, CrxUpdateItem::kNoUpdate);
item->error_category = error_category;
item->error_code = error;
item->extra_code1 = extra_code;
+ ChangeItemState(item, CrxUpdateItem::kNoUpdate);
}
ping_manager_->OnUpdateComplete(item);
ScheduleNextRun(kStepDelayMedium);
}
-void CrxUpdateService::NotifyComponentObservers(
- ComponentObserver::Events event, int extra) const {
- for (UpdateItems::const_iterator it = work_items_.begin();
- it != work_items_.end(); ++it) {
- ComponentObserver* observer = (*it)->component.observer;
- if (observer)
- observer->OnEvent(event, 0);
- }
+void CrxUpdateService::NotifyObservers(Observer::Events event,
+ const std::string& id) {
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ FOR_EACH_OBSERVER(Observer, observer_list_, OnEvent(event, id));
}
content::ResourceThrottle* CrxUpdateService::GetOnDemandResourceThrottle(
- net::URLRequest* request, const std::string& crx_id) {
+ net::URLRequest* request,
+ const std::string& crx_id) {
// We give the raw pointer to the caller, who will delete it at will
// and we keep for ourselves a weak pointer to it so we can post tasks
// from the UI thread without having to track lifetime directly.
CUResourceThrottle* rt = new CUResourceThrottle(request);
- BrowserThread::PostTask(
- BrowserThread::UI,
- FROM_HERE,
- base::Bind(&CrxUpdateService::OnNewResourceThrottle,
- base::Unretained(this),
- rt->AsWeakPtr(),
- crx_id));
+ BrowserThread::PostTask(BrowserThread::UI,
+ FROM_HERE,
+ base::Bind(&CrxUpdateService::OnNewResourceThrottle,
+ base::Unretained(this),
+ rt->AsWeakPtr(),
+ crx_id));
return rt;
}
void CrxUpdateService::OnNewResourceThrottle(
- base::WeakPtr<CUResourceThrottle> rt, const std::string& crx_id) {
+ base::WeakPtr<CUResourceThrottle> rt,
+ const std::string& crx_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Check if we can on-demand update, else unblock the request anyway.
CrxUpdateItem* item = FindUpdateItemById(crx_id);
- Status status = OnDemandUpdateInternal(item);
+ Status status = OnDemandUpdateWithCooldown(item);
if (status == kOk || status == kInProgress) {
item->throttles.push_back(rt);
return;
UnblockResourceThrottle(rt);
}
+// Start the process of checking for an update, for a particular component
+// that was previously registered.
+// |component_id| is a value returned from GetCrxComponentID().
+ComponentUpdateService::Status CrxUpdateService::OnDemandUpdate(
+ const std::string& component_id) {
+ return OnDemandUpdateInternal(FindUpdateItemById(component_id));
+}
+
+ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateWithCooldown(
+ CrxUpdateItem* uit) {
+ if (!uit)
+ return kError;
+
+ // Check if the request is too soon.
+ base::TimeDelta delta = base::Time::Now() - uit->last_check;
+ if (delta < base::TimeDelta::FromSeconds(config_->OnDemandDelay()))
+ return kError;
+
+ return OnDemandUpdateInternal(uit);
+}
+
+ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateInternal(
+ CrxUpdateItem* uit) {
+ if (!uit)
+ return kError;
+
+ uit->on_demand = true;
+
+ // If there is an update available for this item, then continue processing
+ // the update. This is an artifact of how update checks are done: in addition
+ // to the on-demand item, the update check may include other items as well.
+ if (uit->status != CrxUpdateItem::kCanUpdate) {
+ Status service_status = GetServiceStatus(uit->status);
+ // If the item is already in the process of being updated, there is
+ // no point in this call, so return kInProgress.
+ if (service_status == kInProgress)
+ return service_status;
+
+ // Otherwise the item was already checked a while back (or it is new),
+ // set its status to kNew to give it a slightly higher priority.
+ ChangeItemState(uit, CrxUpdateItem::kNew);
+ }
+
+ // In case the current delay is long, set the timer to a shorter value
+ // to get the ball rolling.
+ if (timer_.IsRunning()) {
+ timer_.Stop();
+ timer_.Start(FROM_HERE,
+ base::TimeDelta::FromSeconds(config_->StepDelay()),
+ this,
+ &CrxUpdateService::ProcessPendingItems);
+ }
+
+ return kOk;
+}
+
+ComponentUpdateService::Status CrxUpdateService::GetServiceStatus(
+ CrxUpdateItem::Status status) {
+ switch (status) {
+ case CrxUpdateItem::kChecking:
+ case CrxUpdateItem::kCanUpdate:
+ case CrxUpdateItem::kDownloadingDiff:
+ case CrxUpdateItem::kDownloading:
+ case CrxUpdateItem::kUpdatingDiff:
+ case CrxUpdateItem::kUpdating:
+ return kInProgress;
+ case CrxUpdateItem::kNew:
+ case CrxUpdateItem::kUpdated:
+ case CrxUpdateItem::kUpToDate:
+ case CrxUpdateItem::kNoUpdate:
+ return kOk;
+ case CrxUpdateItem::kLastStatus:
+ NOTREACHED() << status;
+ }
+ return kError;
+}
+
///////////////////////////////////////////////////////////////////////////////
CUResourceThrottle::CUResourceThrottle(const net::URLRequest* request)
WillStartRequest(defer);
}
+const char* CUResourceThrottle::GetNameForLogging() const {
+ return "ComponentUpdateResourceThrottle";
+}
+
void CUResourceThrottle::Unblock() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (state_ == BLOCKED)
DCHECK(config);
return new CrxUpdateService(config);
}
+
+} // namespace component_updater