blob: f3c3e5c76a15942c29ac307cfabe7be7358fec6e [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"
11#include "base/file_path.h"
12#include "base/file_util.h"
13#include "base/logging.h"
[email protected]7226b33c2011-08-18 08:44:2214#include "base/memory/scoped_ptr.h"
[email protected]e8f96ff2011-08-03 05:07:3315#include "base/stl_util.h"
16#include "base/string_number_conversions.h"
17#include "base/string_util.h"
18#include "base/stringprintf.h"
19#include "base/timer.h"
20#include "chrome/browser/browser_process.h"
21#include "chrome/browser/component_updater/component_unpacker.h"
22#include "chrome/common/chrome_notification_types.h"
23#include "chrome/common/chrome_utility_messages.h"
24#include "chrome/common/chrome_version_info.h"
25#include "chrome/common/extensions/extension.h"
26#include "content/browser/utility_process_host.h"
[email protected]ffd7d732011-09-13 04:20:3427#include "content/common/net/url_fetcher.h"
[email protected]ad50def52011-10-19 23:17:0728#include "content/public/browser/notification_service.h"
[email protected]c530c852011-10-24 18:18:3429#include "content/public/common/url_fetcher_delegate.h"
[email protected]e8f96ff2011-08-03 05:07:3330#include "googleurl/src/gurl.h"
31#include "net/base/escape.h"
32#include "net/base/load_flags.h"
33
34namespace {
35// Extends an omaha compatible update check url |query| string. Does
36// not mutate the string if it would be longer than |limit| chars.
37bool AddQueryString(std::string id, std::string version,
38 size_t limit, std::string* query) {
39 std::string additional =
40 base::StringPrintf("id=%s&v=%s&uc", id.c_str(), version.c_str());
[email protected]4a19be92011-09-22 14:25:0241 additional = "x=" + net::EscapeQueryParamValue(additional, true);
[email protected]e8f96ff2011-08-03 05:07:3342 if ((additional.size() + query->size() + 1) > limit)
43 return false;
[email protected]926d36332011-10-05 01:06:2544 if (!query->empty())
45 query->append(1, '&');
[email protected]e8f96ff2011-08-03 05:07:3346 query->append(additional);
47 return true;
48}
49
[email protected]926d36332011-10-05 01:06:2550// Create the final omaha compatible query. The |extra| is optional and can
51// be null. It should contain top level (non-escaped) parameters.
52std::string MakeFinalQuery(const std::string& host,
53 const std::string& query,
54 const char* extra) {
55 std::string request(host);
56 request.append(1, '?');
57 if (extra) {
58 request.append(extra);
59 request.append(1, '&');
60 }
61 request.append(query);
62 return request;
63}
64
[email protected]e8f96ff2011-08-03 05:07:3365// Produces an extension-like friendly |id|. This might be removed in the
66// future if we roll our on packing tools.
67static std::string HexStringToID(const std::string& hexstr) {
68 std::string id;
69 for (size_t i = 0; i < hexstr.size(); ++i) {
70 int val;
71 if (base::HexStringToInt(hexstr.begin() + i, hexstr.begin() + i + 1, &val))
72 id.append(1, val + 'a');
73 else
74 id.append(1, 'a');
75 }
76 DCHECK(Extension::IdIsValid(id));
77 return id;
78}
79
[email protected]360b8bb2011-09-01 21:48:0680// Returns given a crx id it returns a small number, less than 100, that has a
81// decent chance of being unique among the registered components. It also has
82// the nice property that can be trivially computed by hand.
83static int CrxIdtoUMAId(const std::string& id) {
84 CHECK(id.size() > 2);
85 return id[0] + id[1] + id[2] - ('a' * 3);
86}
87
[email protected]e8f96ff2011-08-03 05:07:3388// Helper to do version check for components.
89bool IsVersionNewer(const Version& current, const std::string& proposed) {
90 Version proposed_ver(proposed);
91 if (!proposed_ver.IsValid())
92 return false;
93 return (current.CompareTo(proposed_ver) < 0);
94}
95
96// Helper template class that allows our main class to have separate
97// OnURLFetchComplete() callbacks for diffent types of url requests
98// they are differentiated by the |Ctx| type.
99template <typename Del, typename Ctx>
[email protected]c530c852011-10-24 18:18:34100class DelegateWithContext : public content::URLFetcherDelegate {
[email protected]e8f96ff2011-08-03 05:07:33101 public:
102 DelegateWithContext(Del* delegate, Ctx* context)
103 : delegate_(delegate), context_(context) {}
104
[email protected]7cc6e5632011-10-25 17:56:12105 virtual void OnURLFetchComplete(const content::URLFetcher* source) OVERRIDE {
[email protected]e8f96ff2011-08-03 05:07:33106 delegate_->OnURLFetchComplete(source, context_);
107 delete this;
108 }
109
110 private:
111 ~DelegateWithContext() {}
112
113 Del* delegate_;
114 Ctx* context_;
115};
116// This function creates the right DelegateWithContext using template inference.
117template <typename Del, typename Ctx>
[email protected]c530c852011-10-24 18:18:34118content::URLFetcherDelegate* MakeContextDelegate(Del* delegate, Ctx* context) {
[email protected]e8f96ff2011-08-03 05:07:33119 return new DelegateWithContext<Del, Ctx>(delegate, context);
120}
121
122// Helper to start a url request using |fetcher| with the common flags.
[email protected]7cc6e5632011-10-25 17:56:12123void StartFetch(content::URLFetcher* fetcher,
[email protected]e8f96ff2011-08-03 05:07:33124 net::URLRequestContextGetter* context_getter,
125 bool save_to_file) {
[email protected]7cc6e5632011-10-25 17:56:12126 fetcher->SetRequestContext(context_getter);
127 fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
128 net::LOAD_DO_NOT_SAVE_COOKIES |
129 net::LOAD_DISABLE_CACHE);
[email protected]e8f96ff2011-08-03 05:07:33130 // TODO(cpu): Define our retry and backoff policy.
[email protected]7cc6e5632011-10-25 17:56:12131 fetcher->SetAutomaticallyRetryOn5xx(false);
[email protected]e8f96ff2011-08-03 05:07:33132 if (save_to_file) {
133 fetcher->SaveResponseToTemporaryFile(
134 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
135 }
136 fetcher->Start();
137}
138
139// Returs true if the url request of |fetcher| was succesful.
[email protected]7cc6e5632011-10-25 17:56:12140bool FetchSuccess(const content::URLFetcher& fetcher) {
141 return (fetcher.GetStatus().status() == net::URLRequestStatus::SUCCESS) &&
142 (fetcher.GetResponseCode() == 200);
[email protected]e8f96ff2011-08-03 05:07:33143}
144
145// This is the one and only per-item state structure. Designed to be hosted
146// in a std::vector or a std::list. The two main members are |component|
147// which is supplied by the the component updater client and |status| which
148// is modified as the item is processed by the update pipeline. The expected
149// transition graph is:
150// error error error
151// +--kNoUpdate<------<-------+------<------+------<------+
152// | | | |
153// V yes | | |
154// kNew --->kChecking-->[update?]----->kCanUpdate-->kDownloading-->kUpdating
155// ^ | |
156// | |no |
157// |--kUpToDate<---+ |
158// | success |
159// +--kUpdated<-------------------------------------------+
160//
161struct CrxUpdateItem {
162 enum Status {
163 kNew,
164 kChecking,
165 kCanUpdate,
166 kDownloading,
167 kUpdating,
168 kUpdated,
169 kUpToDate,
170 kNoUpdate,
171 kLastStatus
172 };
173
174 Status status;
175 GURL crx_url;
176 std::string id;
177 base::Time last_check;
178 CrxComponent component;
[email protected]07f93af12011-08-17 20:57:22179 Version next_version;
[email protected]e8f96ff2011-08-03 05:07:33180
181 CrxUpdateItem() : status(kNew) {}
182
183 // Function object used to find a specific component.
184 class FindById {
185 public:
186 explicit FindById(const std::string& id) : id_(id) {}
187
188 bool operator() (CrxUpdateItem* item) const {
189 return (item->id == id_);
190 }
191 private:
192 const std::string& id_;
193 };
194};
195
196} // namespace.
197
198typedef ComponentUpdateService::Configurator Config;
199
200CrxComponent::CrxComponent() {}
201CrxComponent::~CrxComponent() {}
202
203//////////////////////////////////////////////////////////////////////////////
204// The one and only implementation of the ComponentUpdateService interface. In
205// charge of running the show. The main method is ProcessPendingItems() which
206// is called periodically to do the updgrades/installs or the update checks.
207// An important consideration here is to be as "low impact" as we can to the
208// rest of the browser, so even if we have many components registered and
209// elegible for update, we only do one thing at a time with pauses in between
210// the tasks. Also when we do network requests there is only one |url_fetcher_|
211// in flight at at a time.
212// There are no locks in this code, the main structure |work_items_| is mutated
213// only from the UI thread. The unpack and installation is done in the file
214// thread and the network requests are done in the IO thread and in the file
215// thread.
216class CrxUpdateService : public ComponentUpdateService {
217 public:
218 explicit CrxUpdateService(ComponentUpdateService::Configurator* config);
219
220 virtual ~CrxUpdateService();
221
222 // Overrides for ComponentUpdateService.
223 virtual Status Start() OVERRIDE;
224 virtual Status Stop() OVERRIDE;
225 virtual Status RegisterComponent(const CrxComponent& component) OVERRIDE;
226
227 // The only purpose of this class is to forward the
228 // UtilityProcessHost::Client callbacks so CrxUpdateService does
229 // not have to derive from it because that is refcounted.
230 class ManifestParserBridge : public UtilityProcessHost::Client {
231 public:
232 explicit ManifestParserBridge(CrxUpdateService* service)
233 : service_(service) {}
234
235 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
236 bool handled = true;
237 IPC_BEGIN_MESSAGE_MAP(ManifestParserBridge, message)
[email protected]2ccf45c2011-08-19 23:35:50238 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded,
[email protected]e8f96ff2011-08-03 05:07:33239 OnParseUpdateManifestSucceeded)
[email protected]2ccf45c2011-08-19 23:35:50240 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseUpdateManifest_Failed,
[email protected]e8f96ff2011-08-03 05:07:33241 OnParseUpdateManifestFailed)
242 IPC_MESSAGE_UNHANDLED(handled = false)
243 IPC_END_MESSAGE_MAP()
244 return handled;
245 }
246
247 private:
248 // Omaha update response XML was succesfuly parsed.
249 void OnParseUpdateManifestSucceeded(const UpdateManifest::Results& r) {
250 service_->OnParseUpdateManifestSucceeded(r);
251 }
252 // Omaha update response XML could not be parsed.
253 void OnParseUpdateManifestFailed(const std::string& e) {
254 service_->OnParseUpdateManifestFailed(e);
255 }
256
257 CrxUpdateService* service_;
258 DISALLOW_COPY_AND_ASSIGN(ManifestParserBridge);
259 };
260
261 // Context for a update check url request. See DelegateWithContext above.
262 struct UpdateContext {
263 base::Time start;
264 UpdateContext() : start(base::Time::Now()) {}
265 };
266
267 // Context for a crx download url request. See DelegateWithContext above.
268 struct CRXContext {
269 ComponentInstaller* installer;
270 std::vector<uint8> pk_hash;
271 std::string id;
272 CRXContext() : installer(NULL) {}
273 };
274
[email protected]7cc6e5632011-10-25 17:56:12275 void OnURLFetchComplete(const content::URLFetcher* source,
276 UpdateContext* context);
[email protected]e8f96ff2011-08-03 05:07:33277
[email protected]7cc6e5632011-10-25 17:56:12278 void OnURLFetchComplete(const content::URLFetcher* source,
279 CRXContext* context);
[email protected]e8f96ff2011-08-03 05:07:33280
281 private:
282 // See ManifestParserBridge.
283 void OnParseUpdateManifestSucceeded(
284 const UpdateManifest::Results& results);
285
286 // See ManifestParserBridge.
287 void OnParseUpdateManifestFailed(
288 const std::string& error_message);
289
290 bool AddItemToUpdateCheck(CrxUpdateItem* item, std::string* query);
291
292 void ProcessPendingItems();
293
294 void ScheduleNextRun(bool step_delay);
295
296 void ParseManifest(const std::string& xml);
297
298 void Install(const CRXContext* context, const FilePath& crx_path);
299
[email protected]07f93af12011-08-17 20:57:22300 void DoneInstalling(const std::string& component_id,
301 ComponentUnpacker::Error error);
[email protected]e8f96ff2011-08-03 05:07:33302
303 size_t ChangeItemStatus(CrxUpdateItem::Status from,
304 CrxUpdateItem::Status to);
305
306 CrxUpdateItem* FindUpdateItemById(const std::string& id);
307
308 scoped_ptr<Config> config_;
309
[email protected]7cc6e5632011-10-25 17:56:12310 scoped_ptr<content::URLFetcher> url_fetcher_;
[email protected]e8f96ff2011-08-03 05:07:33311
312 typedef std::vector<CrxUpdateItem*> UpdateItems;
313 UpdateItems work_items_;
314
315 base::OneShotTimer<CrxUpdateService> timer_;
316
317 Version chrome_version_;
318
319 bool running_;
320
321 DISALLOW_COPY_AND_ASSIGN(CrxUpdateService);
322};
323
324// The component updater is designed to live until process shutdown, besides
325// we can't be refcounted because we are a singleton.
326DISABLE_RUNNABLE_METHOD_REFCOUNT(CrxUpdateService);
327
328//////////////////////////////////////////////////////////////////////////////
329
330CrxUpdateService::CrxUpdateService(
331 ComponentUpdateService::Configurator* config)
332 : config_(config),
333 chrome_version_(chrome::VersionInfo().Version()),
334 running_(false) {
335}
336
337CrxUpdateService::~CrxUpdateService() {
338 // Because we are a singleton, at this point only the UI thread should be
339 // alive, this simplifies the management of the work that could be in
340 // flight in other threads.
341 Stop();
342 STLDeleteElements(&work_items_);
343}
344
345ComponentUpdateService::Status CrxUpdateService::Start() {
346 // Note that RegisterComponent will call Start() when the first
347 // component is registered, so it can be called twice. This way
348 // we avoid scheduling the timer if there is no work to do.
349 running_ = true;
350 if (work_items_.empty())
351 return kOk;
352
[email protected]ad50def52011-10-19 23:17:07353 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33354 chrome::NOTIFICATION_COMPONENT_UPDATER_STARTED,
[email protected]6c2381d2011-10-19 02:52:53355 content::Source<ComponentUpdateService>(this),
[email protected]ad50def52011-10-19 23:17:07356 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33357
[email protected]d323a172011-09-02 18:23:02358 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->InitialDelay()),
[email protected]e8f96ff2011-08-03 05:07:33359 this, &CrxUpdateService::ProcessPendingItems);
360 return kOk;
361}
362
363// Stop the main check + update loop. In flight operations will be
364// completed.
365ComponentUpdateService::Status CrxUpdateService::Stop() {
366 running_ = false;
367 timer_.Stop();
368 return kOk;
369}
370
371// This function sets the timer which will call ProcessPendingItems() there
372// are two kind of waits, the short one (with step_delay = true) and the
373// long one.
374void CrxUpdateService::ScheduleNextRun(bool step_delay) {
375 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cf442612011-08-09 20:20:12376 DCHECK(url_fetcher_.get() == NULL);
[email protected]e8f96ff2011-08-03 05:07:33377 CHECK(!timer_.IsRunning());
378 // It could be the case that Stop() had been called while a url request
379 // or unpacking was in flight, if so we arrive here but |running_| is
380 // false. In that case do not loop again.
381 if (!running_)
382 return;
383
[email protected]cf442612011-08-09 20:20:12384 int64 delay = step_delay ? config_->StepDelay() : config_->NextCheckDelay();
385
[email protected]e8f96ff2011-08-03 05:07:33386 if (!step_delay) {
[email protected]ad50def52011-10-19 23:17:07387 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33388 chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING,
[email protected]6c2381d2011-10-19 02:52:53389 content::Source<ComponentUpdateService>(this),
[email protected]ad50def52011-10-19 23:17:07390 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33391 // Zero is only used for unit tests.
[email protected]cf442612011-08-09 20:20:12392 if (0 == delay)
[email protected]e8f96ff2011-08-03 05:07:33393 return;
394 }
395
[email protected]d323a172011-09-02 18:23:02396 timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(delay),
[email protected]e8f96ff2011-08-03 05:07:33397 this, &CrxUpdateService::ProcessPendingItems);
398}
399
400// Given a extension-like component id, find the associated component.
401CrxUpdateItem* CrxUpdateService::FindUpdateItemById(const std::string& id) {
402 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
403 CrxUpdateItem::FindById finder(id);
404 UpdateItems::iterator it = std::find_if(work_items_.begin(),
405 work_items_.end(),
406 finder);
407 if (it == work_items_.end())
408 return NULL;
409 return (*it);
410}
411
412// Changes all the components in |work_items_| that have |from| status to
413// |to| statatus and returns how many have been changed.
414size_t CrxUpdateService::ChangeItemStatus(CrxUpdateItem::Status from,
415 CrxUpdateItem::Status to) {
416 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
417 size_t count = 0;
418 for (UpdateItems::iterator it = work_items_.begin();
419 it != work_items_.end(); ++it) {
420 CrxUpdateItem* item = *it;
421 if (item->status != from)
422 continue;
423 item->status = to;
424 ++count;
425 }
426 return count;
427}
428
429// Adds a component to be checked for upgrades. If the component exists it
430// it will be replaced and the return code is kReplaced.
431//
432// TODO(cpu): Evaluate if we want to support un-registration.
433ComponentUpdateService::Status CrxUpdateService::RegisterComponent(
434 const CrxComponent& component) {
435 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
436 if (component.pk_hash.empty() ||
437 !component.version.IsValid() ||
438 !component.installer)
439 return kError;
440
441 std::string id =
442 HexStringToID(StringToLowerASCII(base::HexEncode(&component.pk_hash[0],
443 component.pk_hash.size()/2)));
444 CrxUpdateItem* uit;
445 uit = FindUpdateItemById(id);
446 if (uit) {
447 uit->component = component;
448 return kReplaced;
449 }
450
451 uit = new CrxUpdateItem;
452 uit->id.swap(id);
453 uit->component = component;
454 work_items_.push_back(uit);
455 // If this is the first component registered we call Start to
456 // schedule the first timer.
457 if (running_ && (work_items_.size() == 1))
458 Start();
459
460 return kOk;
461}
462
463// Sets a component to be checked for updates.
464// The componet to add is |crxit| and the |query| string is modified with the
465// required omaha compatible query. Returns false when the query strings
466// is longer than specified by UrlSizeLimit().
467bool CrxUpdateService::AddItemToUpdateCheck(CrxUpdateItem* item,
468 std::string* query) {
469 if (!AddQueryString(item->id,
470 item->component.version.GetString(),
471 config_->UrlSizeLimit(), query))
472 return false;
473 item->status = CrxUpdateItem::kChecking;
474 item->last_check = base::Time::Now();
475 return true;
476}
477
478// Here is where the work gets scheduled. Given that our |work_items_| list
479// is expected to be ten or less items, we simply loop several times.
480void CrxUpdateService::ProcessPendingItems() {
481 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
482 // First check for ready upgrades and do one. The first
483 // step is to fetch the crx package.
484 for (UpdateItems::const_iterator it = work_items_.begin();
485 it != work_items_.end(); ++it) {
486 CrxUpdateItem* item = *it;
487 if (item->status != CrxUpdateItem::kCanUpdate)
488 continue;
489 // Found component to update, start the process.
490 item->status = CrxUpdateItem::kDownloading;
491 CRXContext* context = new CRXContext;
492 context->pk_hash = item->component.pk_hash;
493 context->id = item->id;
494 context->installer = item->component.installer;
495 url_fetcher_.reset(URLFetcher::Create(0, item->crx_url, URLFetcher::GET,
496 MakeContextDelegate(this, context)));
497 StartFetch(url_fetcher_.get(), config_->RequestContext(), true);
498 return;
499 }
500
501 std::string query;
502 // If no pending upgrades, we check the if there are new
503 // components we have not checked against the server. We
504 // can batch a bunch in a single url request.
505 for (UpdateItems::const_iterator it = work_items_.begin();
506 it != work_items_.end(); ++it) {
507 CrxUpdateItem* item = *it;
508 if (item->status != CrxUpdateItem::kNew)
509 continue;
510 if (!AddItemToUpdateCheck(item, &query))
511 break;
512 }
513
514 // Next we can go back to components we already checked, here
515 // we can also batch them in a single url request, as long as
516 // we have not checked them recently.
517 base::TimeDelta min_delta_time =
518 base::TimeDelta::FromSeconds(config_->MinimumReCheckWait());
519
520 for (UpdateItems::const_iterator it = work_items_.begin();
521 it != work_items_.end(); ++it) {
522 CrxUpdateItem* item = *it;
[email protected]cf442612011-08-09 20:20:12523 if ((item->status != CrxUpdateItem::kNoUpdate) &&
[email protected]e8f96ff2011-08-03 05:07:33524 (item->status != CrxUpdateItem::kUpToDate))
525 continue;
526 base::TimeDelta delta = base::Time::Now() - item->last_check;
527 if (delta < min_delta_time)
528 continue;
529 if (!AddItemToUpdateCheck(item, &query))
530 break;
531 }
532 // Finally, we check components that we already updated.
533 for (UpdateItems::const_iterator it = work_items_.begin();
534 it != work_items_.end(); ++it) {
535 CrxUpdateItem* item = *it;
536 if (item->status != CrxUpdateItem::kUpdated)
537 continue;
538 base::TimeDelta delta = base::Time::Now() - item->last_check;
539 if (delta < min_delta_time)
540 continue;
541 if (!AddItemToUpdateCheck(item, &query))
542 break;
543 }
544
545 if (query.empty()) {
546 // Next check after the long sleep.
547 ScheduleNextRun(false);
548 return;
549 }
550
551 // We got components to check. Start the url request.
[email protected]926d36332011-10-05 01:06:25552 const std::string full_query = MakeFinalQuery(config_->UpdateUrl().spec(),
553 query,
554 config_->ExtraRequestParams());
555 url_fetcher_.reset(URLFetcher::Create(0, GURL(full_query), URLFetcher::GET,
[email protected]e8f96ff2011-08-03 05:07:33556 MakeContextDelegate(this, new UpdateContext())));
557 StartFetch(url_fetcher_.get(), config_->RequestContext(), false);
558}
559
560// Caled when we got a response from the update server. It consists of an xml
561// document following the omaha update scheme.
[email protected]7cc6e5632011-10-25 17:56:12562void CrxUpdateService::OnURLFetchComplete(const content::URLFetcher* source,
[email protected]07f93af12011-08-17 20:57:22563 UpdateContext* context) {
[email protected]e8f96ff2011-08-03 05:07:33564 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
565 if (FetchSuccess(*source)) {
566 std::string xml;
567 source->GetResponseAsString(&xml);
[email protected]cf442612011-08-09 20:20:12568 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33569 ParseManifest(xml);
570 } else {
[email protected]cf442612011-08-09 20:20:12571 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33572 CrxUpdateService::OnParseUpdateManifestFailed("network error");
573 }
[email protected]07f93af12011-08-17 20:57:22574 delete context;
[email protected]e8f96ff2011-08-03 05:07:33575}
576
577// Parsing the manifest is either done right now for tests or in a sandboxed
578// process for the production environment. This mitigates the case where an
579// attacker was able to feed us a malicious xml string.
580void CrxUpdateService::ParseManifest(const std::string& xml) {
581 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
582 if (config_->InProcess()) {
583 UpdateManifest manifest;
584 if (!manifest.Parse(xml)) {
585 CrxUpdateService::OnParseUpdateManifestFailed(manifest.errors());
586 } else {
587 CrxUpdateService::OnParseUpdateManifestSucceeded(manifest.results());
588 }
589 } else {
590 UtilityProcessHost* host =
591 new UtilityProcessHost(new ManifestParserBridge(this),
592 BrowserThread::UI);
[email protected]2ccf45c2011-08-19 23:35:50593 host->Send(new ChromeUtilityMsg_ParseUpdateManifest(xml));
[email protected]e8f96ff2011-08-03 05:07:33594 }
595}
596
597// A valid Omaha update check has arrived, from only the list of components that
598// we are currently upgrading we check for a match in which the server side
599// version is newer, if so we queue them for an upgrade. The next time we call
600// ProcessPendingItems() one of them will be drafted for the upgrade process.
601void CrxUpdateService::OnParseUpdateManifestSucceeded(
602 const UpdateManifest::Results& results) {
603 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
604 int update_pending = 0;
605 std::vector<UpdateManifest::Result>::const_iterator it;
606 for (it = results.list.begin(); it != results.list.end(); ++it) {
607 CrxUpdateItem* crx = FindUpdateItemById(it->extension_id);
608 if (!crx)
609 continue;
610
611 if (crx->status != CrxUpdateItem::kChecking)
612 continue; // Not updating this component now.
613
[email protected]360b8bb2011-09-01 21:48:06614 config_->OnEvent(Configurator::kManifestCheck, CrxIdtoUMAId(crx->id));
615
[email protected]e8f96ff2011-08-03 05:07:33616 if (it->version.empty()) {
[email protected]cf442612011-08-09 20:20:12617 // No version means no update available.
[email protected]e8f96ff2011-08-03 05:07:33618 crx->status = CrxUpdateItem::kNoUpdate;
[email protected]cf442612011-08-09 20:20:12619 continue;
[email protected]e8f96ff2011-08-03 05:07:33620 }
621 if (!IsVersionNewer(crx->component.version, it->version)) {
[email protected]cf442612011-08-09 20:20:12622 // Our component is up to date.
[email protected]e8f96ff2011-08-03 05:07:33623 crx->status = CrxUpdateItem::kUpToDate;
[email protected]cf442612011-08-09 20:20:12624 continue;
[email protected]e8f96ff2011-08-03 05:07:33625 }
626 if (!it->browser_min_version.empty()) {
[email protected]cf442612011-08-09 20:20:12627 if (IsVersionNewer(chrome_version_, it->browser_min_version)) {
628 // Does not apply for this chrome version.
629 crx->status = CrxUpdateItem::kNoUpdate;
630 continue;
631 }
[email protected]e8f96ff2011-08-03 05:07:33632 }
633 // All test passed. Queue an upgrade for this component and fire the
634 // notifications.
635 crx->crx_url = it->crx_url;
636 crx->status = CrxUpdateItem::kCanUpdate;
[email protected]07f93af12011-08-17 20:57:22637 crx->next_version = Version(it->version);
[email protected]e8f96ff2011-08-03 05:07:33638 ++update_pending;
639
[email protected]ad50def52011-10-19 23:17:07640 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33641 chrome::NOTIFICATION_COMPONENT_UPDATE_FOUND,
[email protected]6c2381d2011-10-19 02:52:53642 content::Source<std::string>(&crx->id),
[email protected]ad50def52011-10-19 23:17:07643 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33644 }
[email protected]cf442612011-08-09 20:20:12645
646 // All the components that are not mentioned in the manifest we
647 // consider them up to date.
648 ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate);
649
[email protected]e8f96ff2011-08-03 05:07:33650 // If there are updates pending we do a short wait.
651 ScheduleNextRun(update_pending ? true : false);
652}
653
654void CrxUpdateService::OnParseUpdateManifestFailed(
655 const std::string& error_message) {
656 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
657 size_t count = ChangeItemStatus(CrxUpdateItem::kChecking,
658 CrxUpdateItem::kNoUpdate);
[email protected]360b8bb2011-09-01 21:48:06659 config_->OnEvent(Configurator::kManifestError, static_cast<int>(count));
[email protected]e8f96ff2011-08-03 05:07:33660 DCHECK_GT(count, 0ul);
661 ScheduleNextRun(false);
662}
663
664// Called when the CRX package has been downloaded to a temporary location.
665// Here we fire the notifications and schedule the component-specific installer
666// to be called in the file thread.
[email protected]7cc6e5632011-10-25 17:56:12667void CrxUpdateService::OnURLFetchComplete(const content::URLFetcher* source,
[email protected]e8f96ff2011-08-03 05:07:33668 CRXContext* context) {
669 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
670 base::PlatformFileError error_code;
671
672 if (source->FileErrorOccurred(&error_code) || !FetchSuccess(*source)) {
673 size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading,
674 CrxUpdateItem::kNoUpdate);
675 DCHECK_EQ(count, 1ul);
[email protected]360b8bb2011-09-01 21:48:06676 config_->OnEvent(Configurator::kNetworkError, CrxIdtoUMAId(context->id));
[email protected]cf442612011-08-09 20:20:12677 url_fetcher_.reset();
[email protected]e8f96ff2011-08-03 05:07:33678 ScheduleNextRun(false);
679 } else {
680 FilePath temp_crx_path;
681 CHECK(source->GetResponseAsFilePath(true, &temp_crx_path));
682 size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading,
683 CrxUpdateItem::kUpdating);
684 DCHECK_EQ(count, 1ul);
[email protected]cf442612011-08-09 20:20:12685 url_fetcher_.reset();
686
[email protected]ad50def52011-10-19 23:17:07687 content::NotificationService::current()->Notify(
[email protected]e8f96ff2011-08-03 05:07:33688 chrome::NOTIFICATION_COMPONENT_UPDATE_READY,
[email protected]6c2381d2011-10-19 02:52:53689 content::Source<std::string>(&context->id),
[email protected]ad50def52011-10-19 23:17:07690 content::NotificationService::NoDetails());
[email protected]e8f96ff2011-08-03 05:07:33691
692 BrowserThread::PostDelayedTask(BrowserThread::FILE, FROM_HERE,
693 NewRunnableMethod(this, &CrxUpdateService::Install,
694 context,
695 temp_crx_path),
696 config_->StepDelay());
697 }
[email protected]e8f96ff2011-08-03 05:07:33698}
699
700// Install consists of digital signature verification, unpacking and then
701// calling the component specific installer. All that is handled by the
702// |unpacker|. If there is an error this function is in charge of deleting
703// the files created.
704void CrxUpdateService::Install(const CRXContext* context,
705 const FilePath& crx_path) {
706 // This function owns the |crx_path| and the |context| object.
707 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
708 ComponentUnpacker
709 unpacker(context->pk_hash, crx_path, context->installer);
[email protected]e8f96ff2011-08-03 05:07:33710 if (!file_util::Delete(crx_path, false)) {
711 NOTREACHED() << crx_path.value();
712 }
[email protected]e8f96ff2011-08-03 05:07:33713 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
714 NewRunnableMethod(this, &CrxUpdateService::DoneInstalling,
[email protected]07f93af12011-08-17 20:57:22715 context->id, unpacker.error()),
[email protected]e8f96ff2011-08-03 05:07:33716 config_->StepDelay());
[email protected]07f93af12011-08-17 20:57:22717 delete context;
[email protected]e8f96ff2011-08-03 05:07:33718}
719
720// Installation has been completed. Adjust the component status and
721// schedule the next check.
[email protected]07f93af12011-08-17 20:57:22722void CrxUpdateService::DoneInstalling(const std::string& component_id,
723 ComponentUnpacker::Error error) {
[email protected]e8f96ff2011-08-03 05:07:33724 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]07f93af12011-08-17 20:57:22725
726 CrxUpdateItem* item = FindUpdateItemById(component_id);
727 item->status = (error == ComponentUnpacker::kNone) ? CrxUpdateItem::kUpdated :
728 CrxUpdateItem::kNoUpdate;
729 if (item->status == CrxUpdateItem::kUpdated)
730 item->component.version = item->next_version;
731
[email protected]360b8bb2011-09-01 21:48:06732 Configurator::Events event;
733 switch (error) {
734 case ComponentUnpacker::kNone:
735 event = Configurator::kComponentUpdated;
736 break;
737 case ComponentUnpacker::kInstallerError:
738 event = Configurator::kInstallerError;
739 break;
740 default:
741 event = Configurator::kUnpackError;
742 break;
743 }
744
745 config_->OnEvent(event, CrxIdtoUMAId(component_id));
[email protected]e8f96ff2011-08-03 05:07:33746 ScheduleNextRun(false);
747}
748
749// The component update factory. Using the component updater as a singleton
750// is the job of the browser process.
751ComponentUpdateService* ComponentUpdateServiceFactory(
752 ComponentUpdateService::Configurator* config) {
753 DCHECK(config);
754 return new CrxUpdateService(config);
755}