blob: 15782473cb97ba69f31cd85f1d97c6d2633b77af [file] [log] [blame]
[email protected]e8f96ff2011-08-03 05:07:331// Copyright (c) 2011 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 <vector>
9
10#include "base/at_exit.h"
[email protected]44da56e2011-11-21 19:59:1411#include "base/bind.h"
[email protected]e8f96ff2011-08-03 05:07:3312#include "base/file_path.h"
13#include "base/file_util.h"
14#include "base/logging.h"
[email protected]7226b33c2011-08-18 08:44:2215#include "base/memory/scoped_ptr.h"
[email protected]e8f96ff2011-08-03 05:07:3316#include "base/stl_util.h"
17#include "base/string_number_conversions.h"
[email protected]eb72b272011-12-19 16:10:5518#include "base/string_piece.h"
[email protected]e8f96ff2011-08-03 05:07:3319#include "base/string_util.h"
20#include "base/stringprintf.h"
21#include "base/timer.h"
22#include "chrome/browser/browser_process.h"
23#include "chrome/browser/component_updater/component_unpacker.h"
24#include "chrome/common/chrome_notification_types.h"
25#include "chrome/common/chrome_utility_messages.h"
26#include "chrome/common/chrome_version_info.h"
27#include "chrome/common/extensions/extension.h"
28#include "content/browser/utility_process_host.h"
[email protected]ad50def52011-10-19 23:17:0729#include "content/public/browser/notification_service.h"
[email protected]c530c852011-10-24 18:18:3430#include "content/public/common/url_fetcher_delegate.h"
[email protected]36aea2702011-10-26 01:12:2231#include "content/public/common/url_fetcher.h"
[email protected]e8f96ff2011-08-03 05:07:3332#include "googleurl/src/gurl.h"
33#include "net/base/escape.h"
34#include "net/base/load_flags.h"
35
[email protected]631bb742011-11-02 11:29:3936using content::BrowserThread;
37
[email protected]44da56e2011-11-21 19:59:1438// The component updater is designed to live until process shutdown, so
39// base::Bind() calls are not refcounted.
40
[email protected]e8f96ff2011-08-03 05:07:3341namespace {
42// Extends an omaha compatible update check url |query| string. Does
43// not mutate the string if it would be longer than |limit| chars.
[email protected]4c37b452011-12-21 01:33:5244bool AddQueryString(const std::string& id,
45 const std::string& version,
46 size_t limit,
47 std::string* query) {
[email protected]e8f96ff2011-08-03 05:07:3348 std::string additional =
49 base::StringPrintf("id=%s&v=%s&uc", id.c_str(), version.c_str());
[email protected]4a19be92011-09-22 14:25:0250 additional = "x=" + net::EscapeQueryParamValue(additional, true);
[email protected]e8f96ff2011-08-03 05:07:3351 if ((additional.size() + query->size() + 1) > limit)
52 return false;
[email protected]926d36332011-10-05 01:06:2553 if (!query->empty())
54 query->append(1, '&');
[email protected]e8f96ff2011-08-03 05:07:3355 query->append(additional);
56 return true;
57}
58
[email protected]926d36332011-10-05 01:06:2559// Create the final omaha compatible query. The |extra| is optional and can
60// be null. It should contain top level (non-escaped) parameters.
61std::string MakeFinalQuery(const std::string& host,
62 const std::string& query,
63 const char* extra) {
64 std::string request(host);
65 request.append(1, '?');
66 if (extra) {
67 request.append(extra);
68 request.append(1, '&');
69 }
70 request.append(query);
71 return request;
72}
73
[email protected]e8f96ff2011-08-03 05:07:3374// Produces an extension-like friendly |id|. This might be removed in the
75// future if we roll our on packing tools.
76static std::string HexStringToID(const std::string& hexstr) {
77 std::string id;
78 for (size_t i = 0; i < hexstr.size(); ++i) {
79 int val;
[email protected]eb72b272011-12-19 16:10:5580 if (base::HexStringToInt(base::StringPiece(hexstr.begin() + i,
81 hexstr.begin() + i + 1),
82 &val)) {
[email protected]e8f96ff2011-08-03 05:07:3383 id.append(1, val + 'a');
[email protected]eb72b272011-12-19 16:10:5584 } else {
[email protected]e8f96ff2011-08-03 05:07:3385 id.append(1, 'a');
[email protected]eb72b272011-12-19 16:10:5586 }
[email protected]e8f96ff2011-08-03 05:07:3387 }
88 DCHECK(Extension::IdIsValid(id));
89 return id;
90}
91
[email protected]360b8bb2011-09-01 21:48:0692// Returns given a crx id it returns a small number, less than 100, that has a
93// decent chance of being unique among the registered components. It also has
94// the nice property that can be trivially computed by hand.
95static int CrxIdtoUMAId(const std::string& id) {
96 CHECK(id.size() > 2);
97 return id[0] + id[1] + id[2] - ('a' * 3);
98}
99
[email protected]e8f96ff2011-08-03 05:07:33100// Helper to do version check for components.
101bool IsVersionNewer(const Version& current, const std::string& proposed) {
102 Version proposed_ver(proposed);
103 if (!proposed_ver.IsValid())
104 return false;
105 return (current.CompareTo(proposed_ver) < 0);
106}
107
108// Helper template class that allows our main class to have separate
109// OnURLFetchComplete() callbacks for diffent types of url requests
110// they are differentiated by the |Ctx| type.
111template <typename Del, typename Ctx>
[email protected]c530c852011-10-24 18:18:34112class DelegateWithContext : public content::URLFetcherDelegate {
[email protected]e8f96ff2011-08-03 05:07:33113 public:
114 DelegateWithContext(Del* delegate, Ctx* context)
115 : delegate_(delegate), context_(context) {}
116
[email protected]7cc6e5632011-10-25 17:56:12117 virtual void OnURLFetchComplete(const content::URLFetcher* source) OVERRIDE {
[email protected]e8f96ff2011-08-03 05:07:33118 delegate_->OnURLFetchComplete(source, context_);
119 delete this;
120 }
121
122 private:
123 ~DelegateWithContext() {}
124
125 Del* delegate_;
126 Ctx* context_;
127};
128// This function creates the right DelegateWithContext using template inference.
129template <typename Del, typename Ctx>
[email protected]c530c852011-10-24 18:18:34130content::URLFetcherDelegate* MakeContextDelegate(Del* delegate, Ctx* context) {
[email protected]e8f96ff2011-08-03 05:07:33131 return new DelegateWithContext<Del, Ctx>(delegate, context);
132}
133
134// Helper to start a url request using |fetcher| with the common flags.
[email protected]7cc6e5632011-10-25 17:56:12135void StartFetch(content::URLFetcher* fetcher,
[email protected]e8f96ff2011-08-03 05:07:33136 net::URLRequestContextGetter* context_getter,
137 bool save_to_file) {
[email protected]7cc6e5632011-10-25 17:56:12138 fetcher->SetRequestContext(context_getter);
139 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
140 net::LOAD_DO_NOT_SAVE_COOKIES |
141 net::LOAD_DISABLE_CACHE);
[email protected]e8f96ff2011-08-03 05:07:33142 // TODO(cpu): Define our retry and backoff policy.
[email protected]7cc6e5632011-10-25 17:56:12143 fetcher->SetAutomaticallyRetryOn5xx(false);
[email protected]e8f96ff2011-08-03 05:07:33144 if (save_to_file) {
145 fetcher->SaveResponseToTemporaryFile(
146 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
147 }
148 fetcher->Start();
149}
150
151// Returs true if the url request of |fetcher| was succesful.
[email protected]7cc6e5632011-10-25 17:56:12152bool FetchSuccess(const content::URLFetcher& fetcher) {
153 return (fetcher.GetStatus().status() == net::URLRequestStatus::SUCCESS) &&
154 (fetcher.GetResponseCode() == 200);
[email protected]e8f96ff2011-08-03 05:07:33155}
156
157// This is the one and only per-item state structure. Designed to be hosted
158// in a std::vector or a std::list. The two main members are |component|
159// which is supplied by the the component updater client and |status| which
160// is modified as the item is processed by the update pipeline. The expected
161// transition graph is:
162// error error error
163// +--kNoUpdate<------<-------+------<------+------<------+
164// | | | |
165// V yes | | |
166// kNew --->kChecking-->[update?]----->kCanUpdate-->kDownloading-->kUpdating
167// ^ | |
168// | |no |
169// |--kUpToDate<---+ |
170// | success |
171// +--kUpdated<-------------------------------------------+
172//
173struct CrxUpdateItem {
174 enum Status {
175 kNew,
176 kChecking,
177 kCanUpdate,
178 kDownloading,
179 kUpdating,
180 kUpdated,
181 kUpToDate,
182 kNoUpdate,
183 kLastStatus
184 };
185
186 Status status;
187 GURL crx_url;
188 std::string id;
189 base::Time last_check;
190 CrxComponent component;
[email protected]07f93af12011-08-17 20:57:22191 Version next_version;
[email protected]e8f96ff2011-08-03 05:07:33192
193 CrxUpdateItem() : status(kNew) {}
194
195 // Function object used to find a specific component.
196 class FindById {
197 public:
198 explicit FindById(const std::string& id) : id_(id) {}
199
200 bool operator() (CrxUpdateItem* item) const {
201 return (item->id == id_);
202 }
203 private:
204 const std::string& id_;
205 };
206};
207
208} // namespace.
209
210typedef ComponentUpdateService::Configurator Config;
211
212CrxComponent::CrxComponent() {}
213CrxComponent::~CrxComponent() {}
214
215//////////////////////////////////////////////////////////////////////////////
216// The one and only implementation of the ComponentUpdateService interface. In
217// charge of running the show. The main method is ProcessPendingItems() which
218// is called periodically to do the updgrades/installs or the update checks.
219// An important consideration here is to be as "low impact" as we can to the
220// rest of the browser, so even if we have many components registered and
221// elegible for update, we only do one thing at a time with pauses in between
222// the tasks. Also when we do network requests there is only one |url_fetcher_|
223// in flight at at a time.
224// There are no locks in this code, the main structure |work_items_| is mutated
225// only from the UI thread. The unpack and installation is done in the file
226// thread and the network requests are done in the IO thread and in the file
227// thread.
228class CrxUpdateService : public ComponentUpdateService {
229 public:
230 explicit CrxUpdateService(ComponentUpdateService::Configurator* config);
231
232 virtual ~CrxUpdateService();
233
234 // Overrides for ComponentUpdateService.
235 virtual Status Start() OVERRIDE;
236 virtual Status Stop() OVERRIDE;
237 virtual Status RegisterComponent(const CrxComponent& component) OVERRIDE;
238
239 // The only purpose of this class is to forward the
240 // UtilityProcessHost::Client callbacks so CrxUpdateService does
241 // not have to derive from it because that is refcounted.
242 class ManifestParserBridge : public UtilityProcessHost::Client {
243 public:
244 explicit ManifestParserBridge(CrxUpdateService* service)
245 : service_(service) {}
246
247 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
248 bool handled = true;
249 IPC_BEGIN_MESSAGE_MAP(ManifestParserBridge, message)
[email protected]2ccf45c2011-08-19 23:35:50250 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded,
[email protected]e8f96ff2011-08-03 05:07:33251 OnParseUpdateManifestSucceeded)
[email protected]2ccf45c2011-08-19 23:35:50252 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Failed,
[email protected]e8f96ff2011-08-03 05:07:33253 OnParseUpdateManifestFailed)
254 IPC_MESSAGE_UNHANDLED(handled = false)
255 IPC_END_MESSAGE_MAP()
256 return handled;
257 }
258
259 private:
260 // Omaha update response XML was succesfuly parsed.
261 void OnParseUpdateManifestSucceeded(const UpdateManifest::Results& r) {
262 service_->OnParseUpdateManifestSucceeded(r);
263 }
264 // Omaha update response XML could not be parsed.
265 void OnParseUpdateManifestFailed(const std::string& e) {
266 service_->OnParseUpdateManifestFailed(e);
267 }
268
269 CrxUpdateService* service_;
270 DISALLOW_COPY_AND_ASSIGN(ManifestParserBridge);
271 };
272
273 // Context for a update check url request. See DelegateWithContext above.
274 struct UpdateContext {
275 base::Time start;
276 UpdateContext() : start(base::Time::Now()) {}
277 };
278
279 // Context for a crx download url request. See DelegateWithContext above.
280 struct CRXContext {
281 ComponentInstaller* installer;
282 std::vector<uint8> pk_hash;
283 std::string id;
284 CRXContext() : installer(NULL) {}
285 };
286
[email protected]7cc6e5632011-10-25 17:56:12287 void OnURLFetchComplete(const content::URLFetcher* source,
288 UpdateContext* context);
[email protected]e8f96ff2011-08-03 05:07:33289
[email protected]7cc6e5632011-10-25 17:56:12290 void OnURLFetchComplete(const content::URLFetcher* source,
291 CRXContext* context);
[email protected]e8f96ff2011-08-03 05:07:33292
293 private:
294 // See ManifestParserBridge.
295 void OnParseUpdateManifestSucceeded(
296 const UpdateManifest::Results& results);
297
298 // See ManifestParserBridge.
299 void OnParseUpdateManifestFailed(
300 const std::string& error_message);
301
302 bool AddItemToUpdateCheck(CrxUpdateItem* item, std::string* query);
303
304 void ProcessPendingItems();
305
306 void ScheduleNextRun(bool step_delay);
307
308 void ParseManifest(const std::string& xml);
309
310 void Install(const CRXContext* context, const FilePath& crx_path);
311
[email protected]07f93af12011-08-17 20:57:22312 void DoneInstalling(const std::string& component_id,
313 ComponentUnpacker::Error error);
[email protected]e8f96ff2011-08-03 05:07:33314
315 size_t ChangeItemStatus(CrxUpdateItem::Status from,
316 CrxUpdateItem::Status to);
317
318 CrxUpdateItem* FindUpdateItemById(const std::string& id);
319
320 scoped_ptr<Config> config_;
321
[email protected]7cc6e5632011-10-25 17:56:12322 scoped_ptr<content::URLFetcher> url_fetcher_;
[email protected]e8f96ff2011-08-03 05:07:33323
324 typedef std::vector<CrxUpdateItem*> UpdateItems;
325 UpdateItems work_items_;
326
327 base::OneShotTimer<CrxUpdateService> timer_;
328
329 Version chrome_version_;
330
331 bool running_;
332
333 DISALLOW_COPY_AND_ASSIGN(CrxUpdateService);
334};
335
[email protected]e8f96ff2011-08-03 05:07:33336//////////////////////////////////////////////////////////////////////////////
337
338CrxUpdateService::CrxUpdateService(
339 ComponentUpdateService::Configurator* config)
340 : config_(config),
341 chrome_version_(chrome::VersionInfo().Version()),
342 running_(false) {
343}
344
345CrxUpdateService::~CrxUpdateService() {
346 // Because we are a singleton, at this point only the UI thread should be
347 // alive, this simplifies the management of the work that could be in
348 // flight in other threads.
349 Stop();
350 STLDeleteElements(&work_items_);
351}
352
353ComponentUpdateService::Status CrxUpdateService::Start() {
354 // Note that RegisterComponent will call Start() when the first
355 // component is registered, so it can be called twice. This way
356 // we avoid scheduling the timer if there is no work to do.
357 running_ = true;
358 if (work_items_.empty())
359 return kOk;
360
[email protected]ad50def52011-10-19 23:17:07361 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33362 chrome::NOTIFICATION_COMPONENT_UPDATER_STARTED,
[email protected]6c2381d2011-10-19 02:52:53363 content::Source<ComponentUpdateService>(this),
[email protected]ad50def52011-10-19 23:17:07364 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33365
[email protected]d323a172011-09-02 18:23:02366 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->InitialDelay()),
[email protected]e8f96ff2011-08-03 05:07:33367 this, &CrxUpdateService::ProcessPendingItems);
368 return kOk;
369}
370
371// Stop the main check + update loop. In flight operations will be
372// completed.
373ComponentUpdateService::Status CrxUpdateService::Stop() {
374 running_ = false;
375 timer_.Stop();
376 return kOk;
377}
378
379// This function sets the timer which will call ProcessPendingItems() there
380// are two kind of waits, the short one (with step_delay = true) and the
381// long one.
382void CrxUpdateService::ScheduleNextRun(bool step_delay) {
383 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cf442612011-08-09 20:20:12384 DCHECK(url_fetcher_.get() == NULL);
[email protected]e8f96ff2011-08-03 05:07:33385 CHECK(!timer_.IsRunning());
386 // It could be the case that Stop() had been called while a url request
387 // or unpacking was in flight, if so we arrive here but |running_| is
388 // false. In that case do not loop again.
389 if (!running_)
390 return;
391
[email protected]cf442612011-08-09 20:20:12392 int64 delay = step_delay ? config_->StepDelay() : config_->NextCheckDelay();
393
[email protected]e8f96ff2011-08-03 05:07:33394 if (!step_delay) {
[email protected]ad50def52011-10-19 23:17:07395 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33396 chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING,
[email protected]6c2381d2011-10-19 02:52:53397 content::Source<ComponentUpdateService>(this),
[email protected]ad50def52011-10-19 23:17:07398 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33399 // Zero is only used for unit tests.
[email protected]cf442612011-08-09 20:20:12400 if (0 == delay)
[email protected]e8f96ff2011-08-03 05:07:33401 return;
402 }
403
[email protected]d323a172011-09-02 18:23:02404 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(delay),
[email protected]e8f96ff2011-08-03 05:07:33405 this, &CrxUpdateService::ProcessPendingItems);
406}
407
408// Given a extension-like component id, find the associated component.
409CrxUpdateItem* CrxUpdateService::FindUpdateItemById(const std::string& id) {
410 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
411 CrxUpdateItem::FindById finder(id);
412 UpdateItems::iterator it = std::find_if(work_items_.begin(),
413 work_items_.end(),
414 finder);
415 if (it == work_items_.end())
416 return NULL;
417 return (*it);
418}
419
420// Changes all the components in |work_items_| that have |from| status to
421// |to| statatus and returns how many have been changed.
422size_t CrxUpdateService::ChangeItemStatus(CrxUpdateItem::Status from,
423 CrxUpdateItem::Status to) {
424 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
425 size_t count = 0;
426 for (UpdateItems::iterator it = work_items_.begin();
427 it != work_items_.end(); ++it) {
428 CrxUpdateItem* item = *it;
429 if (item->status != from)
430 continue;
431 item->status = to;
432 ++count;
433 }
434 return count;
435}
436
437// Adds a component to be checked for upgrades. If the component exists it
438// it will be replaced and the return code is kReplaced.
439//
440// TODO(cpu): Evaluate if we want to support un-registration.
441ComponentUpdateService::Status CrxUpdateService::RegisterComponent(
442 const CrxComponent& component) {
443 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
444 if (component.pk_hash.empty() ||
445 !component.version.IsValid() ||
446 !component.installer)
447 return kError;
448
449 std::string id =
450 HexStringToID(StringToLowerASCII(base::HexEncode(&component.pk_hash[0],
451 component.pk_hash.size()/2)));
452 CrxUpdateItem* uit;
453 uit = FindUpdateItemById(id);
454 if (uit) {
455 uit->component = component;
456 return kReplaced;
457 }
458
459 uit = new CrxUpdateItem;
460 uit->id.swap(id);
461 uit->component = component;
462 work_items_.push_back(uit);
463 // If this is the first component registered we call Start to
464 // schedule the first timer.
465 if (running_ && (work_items_.size() == 1))
466 Start();
467
468 return kOk;
469}
470
471// Sets a component to be checked for updates.
472// The componet to add is |crxit| and the |query| string is modified with the
473// required omaha compatible query. Returns false when the query strings
474// is longer than specified by UrlSizeLimit().
475bool CrxUpdateService::AddItemToUpdateCheck(CrxUpdateItem* item,
476 std::string* query) {
477 if (!AddQueryString(item->id,
478 item->component.version.GetString(),
479 config_->UrlSizeLimit(), query))
480 return false;
481 item->status = CrxUpdateItem::kChecking;
482 item->last_check = base::Time::Now();
483 return true;
484}
485
486// Here is where the work gets scheduled. Given that our |work_items_| list
487// is expected to be ten or less items, we simply loop several times.
488void CrxUpdateService::ProcessPendingItems() {
489 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
490 // First check for ready upgrades and do one. The first
491 // step is to fetch the crx package.
492 for (UpdateItems::const_iterator it = work_items_.begin();
493 it != work_items_.end(); ++it) {
494 CrxUpdateItem* item = *it;
495 if (item->status != CrxUpdateItem::kCanUpdate)
496 continue;
497 // Found component to update, start the process.
498 item->status = CrxUpdateItem::kDownloading;
499 CRXContext* context = new CRXContext;
500 context->pk_hash = item->component.pk_hash;
501 context->id = item->id;
502 context->installer = item->component.installer;
[email protected]36aea2702011-10-26 01:12:22503 url_fetcher_.reset(content::URLFetcher::Create(
504 0, item->crx_url, content::URLFetcher::GET,
[email protected]e8f96ff2011-08-03 05:07:33505 MakeContextDelegate(this, context)));
506 StartFetch(url_fetcher_.get(), config_->RequestContext(), true);
507 return;
508 }
509
510 std::string query;
511 // If no pending upgrades, we check the if there are new
512 // components we have not checked against the server. We
513 // can batch a bunch in a single url request.
514 for (UpdateItems::const_iterator it = work_items_.begin();
515 it != work_items_.end(); ++it) {
516 CrxUpdateItem* item = *it;
517 if (item->status != CrxUpdateItem::kNew)
518 continue;
519 if (!AddItemToUpdateCheck(item, &query))
520 break;
521 }
522
523 // Next we can go back to components we already checked, here
524 // we can also batch them in a single url request, as long as
525 // we have not checked them recently.
526 base::TimeDelta min_delta_time =
527 base::TimeDelta::FromSeconds(config_->MinimumReCheckWait());
528
529 for (UpdateItems::const_iterator it = work_items_.begin();
530 it != work_items_.end(); ++it) {
531 CrxUpdateItem* item = *it;
[email protected]cf442612011-08-09 20:20:12532 if ((item->status != CrxUpdateItem::kNoUpdate) &&
[email protected]e8f96ff2011-08-03 05:07:33533 (item->status != CrxUpdateItem::kUpToDate))
534 continue;
535 base::TimeDelta delta = base::Time::Now() - item->last_check;
536 if (delta < min_delta_time)
537 continue;
538 if (!AddItemToUpdateCheck(item, &query))
539 break;
540 }
541 // Finally, we check components that we already updated.
542 for (UpdateItems::const_iterator it = work_items_.begin();
543 it != work_items_.end(); ++it) {
544 CrxUpdateItem* item = *it;
545 if (item->status != CrxUpdateItem::kUpdated)
546 continue;
547 base::TimeDelta delta = base::Time::Now() - item->last_check;
548 if (delta < min_delta_time)
549 continue;
550 if (!AddItemToUpdateCheck(item, &query))
551 break;
552 }
553
554 if (query.empty()) {
555 // Next check after the long sleep.
556 ScheduleNextRun(false);
557 return;
558 }
559
560 // We got components to check. Start the url request.
[email protected]926d36332011-10-05 01:06:25561 const std::string full_query = MakeFinalQuery(config_->UpdateUrl().spec(),
562 query,
563 config_->ExtraRequestParams());
[email protected]36aea2702011-10-26 01:12:22564 url_fetcher_.reset(content::URLFetcher::Create(
565 0, GURL(full_query), content::URLFetcher::GET,
[email protected]e8f96ff2011-08-03 05:07:33566 MakeContextDelegate(this, new UpdateContext())));
567 StartFetch(url_fetcher_.get(), config_->RequestContext(), false);
568}
569
570// Caled when we got a response from the update server. It consists of an xml
571// document following the omaha update scheme.
[email protected]7cc6e5632011-10-25 17:56:12572void CrxUpdateService::OnURLFetchComplete(const content::URLFetcher* source,
[email protected]07f93af12011-08-17 20:57:22573 UpdateContext* context) {
[email protected]e8f96ff2011-08-03 05:07:33574 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
575 if (FetchSuccess(*source)) {
576 std::string xml;
577 source->GetResponseAsString(&xml);
[email protected]cf442612011-08-09 20:20:12578 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33579 ParseManifest(xml);
580 } else {
[email protected]cf442612011-08-09 20:20:12581 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33582 CrxUpdateService::OnParseUpdateManifestFailed("network error");
583 }
[email protected]07f93af12011-08-17 20:57:22584 delete context;
[email protected]e8f96ff2011-08-03 05:07:33585}
586
587// Parsing the manifest is either done right now for tests or in a sandboxed
588// process for the production environment. This mitigates the case where an
589// attacker was able to feed us a malicious xml string.
590void CrxUpdateService::ParseManifest(const std::string& xml) {
591 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
592 if (config_->InProcess()) {
593 UpdateManifest manifest;
594 if (!manifest.Parse(xml)) {
595 CrxUpdateService::OnParseUpdateManifestFailed(manifest.errors());
596 } else {
597 CrxUpdateService::OnParseUpdateManifestSucceeded(manifest.results());
598 }
599 } else {
600 UtilityProcessHost* host =
601 new UtilityProcessHost(new ManifestParserBridge(this),
602 BrowserThread::UI);
[email protected]80d341a2011-12-13 01:24:47603 host->set_use_linux_zygote(true);
[email protected]2ccf45c2011-08-19 23:35:50604 host->Send(new ChromeUtilityMsg_ParseUpdateManifest(xml));
[email protected]e8f96ff2011-08-03 05:07:33605 }
606}
607
608// A valid Omaha update check has arrived, from only the list of components that
609// we are currently upgrading we check for a match in which the server side
610// version is newer, if so we queue them for an upgrade. The next time we call
611// ProcessPendingItems() one of them will be drafted for the upgrade process.
612void CrxUpdateService::OnParseUpdateManifestSucceeded(
613 const UpdateManifest::Results& results) {
614 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
615 int update_pending = 0;
616 std::vector<UpdateManifest::Result>::const_iterator it;
617 for (it = results.list.begin(); it != results.list.end(); ++it) {
618 CrxUpdateItem* crx = FindUpdateItemById(it->extension_id);
619 if (!crx)
620 continue;
621
622 if (crx->status != CrxUpdateItem::kChecking)
623 continue; // Not updating this component now.
624
[email protected]360b8bb2011-09-01 21:48:06625 config_->OnEvent(Configurator::kManifestCheck, CrxIdtoUMAId(crx->id));
626
[email protected]e8f96ff2011-08-03 05:07:33627 if (it->version.empty()) {
[email protected]cf442612011-08-09 20:20:12628 // No version means no update available.
[email protected]e8f96ff2011-08-03 05:07:33629 crx->status = CrxUpdateItem::kNoUpdate;
[email protected]cf442612011-08-09 20:20:12630 continue;
[email protected]e8f96ff2011-08-03 05:07:33631 }
632 if (!IsVersionNewer(crx->component.version, it->version)) {
[email protected]cf442612011-08-09 20:20:12633 // Our component is up to date.
[email protected]e8f96ff2011-08-03 05:07:33634 crx->status = CrxUpdateItem::kUpToDate;
[email protected]cf442612011-08-09 20:20:12635 continue;
[email protected]e8f96ff2011-08-03 05:07:33636 }
637 if (!it->browser_min_version.empty()) {
[email protected]cf442612011-08-09 20:20:12638 if (IsVersionNewer(chrome_version_, it->browser_min_version)) {
639 // Does not apply for this chrome version.
640 crx->status = CrxUpdateItem::kNoUpdate;
641 continue;
642 }
[email protected]e8f96ff2011-08-03 05:07:33643 }
644 // All test passed. Queue an upgrade for this component and fire the
645 // notifications.
646 crx->crx_url = it->crx_url;
647 crx->status = CrxUpdateItem::kCanUpdate;
[email protected]07f93af12011-08-17 20:57:22648 crx->next_version = Version(it->version);
[email protected]e8f96ff2011-08-03 05:07:33649 ++update_pending;
650
[email protected]ad50def52011-10-19 23:17:07651 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33652 chrome::NOTIFICATION_COMPONENT_UPDATE_FOUND,
[email protected]6c2381d2011-10-19 02:52:53653 content::Source<std::string>(&crx->id),
[email protected]ad50def52011-10-19 23:17:07654 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33655 }
[email protected]cf442612011-08-09 20:20:12656
657 // All the components that are not mentioned in the manifest we
658 // consider them up to date.
659 ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate);
660
[email protected]e8f96ff2011-08-03 05:07:33661 // If there are updates pending we do a short wait.
662 ScheduleNextRun(update_pending ? true : false);
663}
664
665void CrxUpdateService::OnParseUpdateManifestFailed(
666 const std::string& error_message) {
667 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
668 size_t count = ChangeItemStatus(CrxUpdateItem::kChecking,
669 CrxUpdateItem::kNoUpdate);
[email protected]360b8bb2011-09-01 21:48:06670 config_->OnEvent(Configurator::kManifestError, static_cast<int>(count));
[email protected]e8f96ff2011-08-03 05:07:33671 DCHECK_GT(count, 0ul);
672 ScheduleNextRun(false);
673}
674
675// Called when the CRX package has been downloaded to a temporary location.
676// Here we fire the notifications and schedule the component-specific installer
677// to be called in the file thread.
[email protected]7cc6e5632011-10-25 17:56:12678void CrxUpdateService::OnURLFetchComplete(const content::URLFetcher* source,
[email protected]e8f96ff2011-08-03 05:07:33679 CRXContext* context) {
680 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
681 base::PlatformFileError error_code;
682
683 if (source->FileErrorOccurred(&error_code) || !FetchSuccess(*source)) {
684 size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading,
685 CrxUpdateItem::kNoUpdate);
686 DCHECK_EQ(count, 1ul);
[email protected]360b8bb2011-09-01 21:48:06687 config_->OnEvent(Configurator::kNetworkError, CrxIdtoUMAId(context->id));
[email protected]cf442612011-08-09 20:20:12688 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33689 ScheduleNextRun(false);
690 } else {
691 FilePath temp_crx_path;
692 CHECK(source->GetResponseAsFilePath(true, &temp_crx_path));
693 size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading,
694 CrxUpdateItem::kUpdating);
695 DCHECK_EQ(count, 1ul);
[email protected]cf442612011-08-09 20:20:12696 url_fetcher_.reset();
697
[email protected]ad50def52011-10-19 23:17:07698 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33699 chrome::NOTIFICATION_COMPONENT_UPDATE_READY,
[email protected]6c2381d2011-10-19 02:52:53700 content::Source<std::string>(&context->id),
[email protected]ad50def52011-10-19 23:17:07701 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33702
[email protected]44da56e2011-11-21 19:59:14703 // Why unretained? See comment at top of file.
[email protected]e8f96ff2011-08-03 05:07:33704 BrowserThread::PostDelayedTask(BrowserThread::FILE, FROM_HERE,
[email protected]44da56e2011-11-21 19:59:14705 base::Bind(&CrxUpdateService::Install,
706 base::Unretained(this),
707 context,
708 temp_crx_path),
[email protected]e8f96ff2011-08-03 05:07:33709 config_->StepDelay());
710 }
[email protected]e8f96ff2011-08-03 05:07:33711}
712
713// Install consists of digital signature verification, unpacking and then
714// calling the component specific installer. All that is handled by the
715// |unpacker|. If there is an error this function is in charge of deleting
716// the files created.
717void CrxUpdateService::Install(const CRXContext* context,
718 const FilePath& crx_path) {
719 // This function owns the |crx_path| and the |context| object.
720 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
721 ComponentUnpacker
722 unpacker(context->pk_hash, crx_path, context->installer);
[email protected]e8f96ff2011-08-03 05:07:33723 if (!file_util::Delete(crx_path, false)) {
724 NOTREACHED() << crx_path.value();
725 }
[email protected]44da56e2011-11-21 19:59:14726 // Why unretained? See comment at top of file.
[email protected]e8f96ff2011-08-03 05:07:33727 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
[email protected]44da56e2011-11-21 19:59:14728 base::Bind(&CrxUpdateService::DoneInstalling, base::Unretained(this),
729 context->id, unpacker.error()),
[email protected]e8f96ff2011-08-03 05:07:33730 config_->StepDelay());
[email protected]07f93af12011-08-17 20:57:22731 delete context;
[email protected]e8f96ff2011-08-03 05:07:33732}
733
734// Installation has been completed. Adjust the component status and
735// schedule the next check.
[email protected]07f93af12011-08-17 20:57:22736void CrxUpdateService::DoneInstalling(const std::string& component_id,
737 ComponentUnpacker::Error error) {
[email protected]e8f96ff2011-08-03 05:07:33738 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]07f93af12011-08-17 20:57:22739
740 CrxUpdateItem* item = FindUpdateItemById(component_id);
741 item->status = (error == ComponentUnpacker::kNone) ? CrxUpdateItem::kUpdated :
742 CrxUpdateItem::kNoUpdate;
743 if (item->status == CrxUpdateItem::kUpdated)
744 item->component.version = item->next_version;
745
[email protected]360b8bb2011-09-01 21:48:06746 Configurator::Events event;
747 switch (error) {
748 case ComponentUnpacker::kNone:
749 event = Configurator::kComponentUpdated;
750 break;
751 case ComponentUnpacker::kInstallerError:
752 event = Configurator::kInstallerError;
753 break;
754 default:
755 event = Configurator::kUnpackError;
756 break;
757 }
758
759 config_->OnEvent(event, CrxIdtoUMAId(component_id));
[email protected]e8f96ff2011-08-03 05:07:33760 ScheduleNextRun(false);
761}
762
763// The component update factory. Using the component updater as a singleton
764// is the job of the browser process.
765ComponentUpdateService* ComponentUpdateServiceFactory(
766 ComponentUpdateService::Configurator* config) {
767 DCHECK(config);
768 return new CrxUpdateService(config);
769}