1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
|
// Copyright (c) 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 "chrome/browser/policy/app_pack_updater.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros_settings.h"
#include "chrome/browser/chromeos/cros_settings_names.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/external_extension_loader.h"
#include "chrome/browser/extensions/external_extension_provider_impl.h"
#include "chrome/browser/extensions/updater/extension_downloader.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
using content::BrowserThread;
using file_util::FileEnumerator;
namespace policy {
namespace {
// Directory where the AppPack extensions are cached.
const char kAppPackCacheDir[] = "/var/cache/app_pack";
// File name extension for CRX files (not case sensitive).
const char kCRXFileExtension[] = ".crx";
} // namespace
const char AppPackUpdater::kExtensionId[] = "extension-id";
const char AppPackUpdater::kUpdateUrl[] = "update-url";
// A custom ExternalExtensionLoader that the AppPackUpdater creates and uses to
// publish AppPack updates to the extensions system.
class AppPackExternalExtensionLoader
: public ExternalExtensionLoader,
public base::SupportsWeakPtr<AppPackExternalExtensionLoader> {
public:
AppPackExternalExtensionLoader() {}
virtual ~AppPackExternalExtensionLoader() {}
// Used by the AppPackUpdater to update the current list of extensions.
// The format of |prefs| is detailed in the ExternalExtensionLoader/Provider
// headers.
void SetCurrentAppPackExtensions(scoped_ptr<base::DictionaryValue> prefs) {
app_pack_prefs_.Swap(prefs.get());
StartLoading();
}
// Implementation of ExternalExtensionLoader:
virtual void StartLoading() OVERRIDE {
prefs_.reset(app_pack_prefs_.DeepCopy());
VLOG(1) << "AppPack extension loader publishing "
<< app_pack_prefs_.size() << " crx files.";
LoadFinished();
}
private:
base::DictionaryValue app_pack_prefs_;
DISALLOW_COPY_AND_ASSIGN(AppPackExternalExtensionLoader);
};
AppPackUpdater::AppPackUpdater(net::URLRequestContextGetter* request_context,
BrowserPolicyConnector* connector)
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)),
created_extension_loader_(false),
request_context_(request_context) {
if (connector->GetDeviceMode() == DEVICE_MODE_KIOSK) {
// Already in Kiosk mode, start loading.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&AppPackUpdater::Init,
weak_ptr_factory_.GetWeakPtr()));
} else if ((connector->GetDeviceMode() == DEVICE_MODE_NOT_SET ||
connector->GetDeviceMode() == DEVICE_MODE_PENDING) &&
connector->device_cloud_policy_subsystem()) {
// Not enrolled yet, listen for enrollment.
policy_registrar_.reset(new CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
} else {
// Linger as a stub.
}
}
AppPackUpdater::~AppPackUpdater() {
chromeos::CrosSettings::Get()->RemoveSettingsObserver(
chromeos::kAppPack, this);
net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
}
ExternalExtensionLoader* AppPackUpdater::CreateExternalExtensionLoader() {
if (created_extension_loader_) {
NOTREACHED();
return NULL;
}
created_extension_loader_ = true;
AppPackExternalExtensionLoader* loader = new AppPackExternalExtensionLoader();
extension_loader_ = loader->AsWeakPtr();
// The cache may have been already checked. In that case, load the current
// extensions into the loader immediately.
UpdateExtensionLoader();
return loader;
}
void AppPackUpdater::SetScreenSaverUpdateCallback(
const AppPackUpdater::ScreenSaverUpdateCallback& callback) {
screen_saver_update_callback_ = callback;
if (!screen_saver_update_callback_.is_null() && !screen_saver_path_.empty()) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(screen_saver_update_callback_, screen_saver_path_));
}
}
void AppPackUpdater::Init() {
worker_pool_token_ = BrowserThread::GetBlockingPool()->GetSequenceToken();
chromeos::CrosSettings::Get()->AddSettingsObserver(chromeos::kAppPack, this);
notification_registrar_.Add(
this,
chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR,
content::NotificationService::AllBrowserContextsAndSources());
net::NetworkChangeNotifier::AddIPAddressObserver(this);
LoadPolicy();
}
void AppPackUpdater::OnPolicyStateChanged(
CloudPolicySubsystem::PolicySubsystemState state,
CloudPolicySubsystem::ErrorDetails error_details) {
if (state == CloudPolicySubsystem::SUCCESS) {
policy_registrar_.reset();
Init();
}
}
void AppPackUpdater::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED:
DCHECK_EQ(chromeos::kAppPack,
*content::Details<const std::string>(details).ptr());
LoadPolicy();
break;
case chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR:
OnCrxInstallFailed(content::Source<CrxInstaller>(source).ptr());
break;
default:
NOTREACHED();
}
}
void AppPackUpdater::OnIPAddressChanged() {
// Check if the AppPack has been fully downloaded whenever the network
// changes. This allows the AppPack to recover in case the network wasn't
// ready early during startup.
// To avoid performing too many update checks in case the network conditions
// change too often, an update is only triggered now if there are extensions
// configured via policy that haven't been checked for updates yet.
for (PolicyEntryMap::iterator it = app_pack_extensions_.begin();
it != app_pack_extensions_.end(); ++it) {
if (!it->second.update_checked) {
// |id| is configured via policy, but hasn't been updated before.
// Drop any pending requests and start a full check now.
VLOG(1) << "Extension " << it->first << " hasn't been checked yet, "
<< "new update triggered now by network change notification.";
downloader_.reset();
weak_ptr_factory_.InvalidateWeakPtrs();
LoadPolicy();
break;
}
}
}
void AppPackUpdater::LoadPolicy() {
chromeos::CrosSettings* settings = chromeos::CrosSettings::Get();
if (chromeos::CrosSettingsProvider::TRUSTED != settings->PrepareTrustedValues(
base::Bind(&AppPackUpdater::LoadPolicy,
weak_ptr_factory_.GetWeakPtr()))) {
return;
}
app_pack_extensions_.clear();
const base::Value* value = settings->GetPref(chromeos::kAppPack);
const base::ListValue* list = NULL;
if (value && value->GetAsList(&list)) {
for (base::ListValue::const_iterator it = list->begin();
it != list->end(); ++it) {
base::DictionaryValue* dict = NULL;
if (!(*it)->GetAsDictionary(&dict)) {
LOG(WARNING) << "AppPack entry is not a dictionary, ignoring.";
continue;
}
std::string id;
std::string update_url;
if (dict->GetString(kExtensionId, &id) &&
dict->GetString(kUpdateUrl, &update_url)) {
app_pack_extensions_[id].update_url = update_url;
app_pack_extensions_[id].update_checked = false;
} else {
LOG(WARNING) << "Failed to read required fields for an AppPack entry, "
<< "ignoring.";
}
}
}
VLOG(1) << "Refreshed AppPack policy, got " << app_pack_extensions_.size()
<< " entries.";
value = settings->GetPref(chromeos::kScreenSaverExtensionId);
if (!value || !value->GetAsString(&screen_saver_id_)) {
screen_saver_id_.clear();
SetScreenSaverPath(FilePath());
}
CheckCacheNow();
}
void AppPackUpdater::CheckCacheNow() {
std::set<std::string>* valid_ids = new std::set<std::string>();
for (PolicyEntryMap::iterator it = app_pack_extensions_.begin();
it != app_pack_extensions_.end(); ++it) {
valid_ids->insert(it->first);
}
PostBlockingTask(FROM_HERE,
base::Bind(&AppPackUpdater::BlockingCheckCache,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(valid_ids)));
}
// static
void AppPackUpdater::BlockingCheckCache(
base::WeakPtr<AppPackUpdater> app_pack_updater,
const std::set<std::string>* valid_ids) {
CacheEntryMap* entries = new CacheEntryMap();
BlockingCheckCacheInternal(valid_ids, entries);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&AppPackUpdater::OnCacheUpdated,
app_pack_updater,
base::Owned(entries)));
}
// static
void AppPackUpdater::BlockingCheckCacheInternal(
const std::set<std::string>* valid_ids,
CacheEntryMap* entries) {
// Start by verifying that the cache dir exists.
FilePath dir(kAppPackCacheDir);
if (!file_util::DirectoryExists(dir)) {
// Create it now.
if (!file_util::CreateDirectory(dir))
LOG(ERROR) << "Failed to create AppPack directory at " << dir.value();
// Nothing else to do.
return;
}
// Enumerate all the files in the cache |dir|, including directories
// and symlinks. Each unrecognized file will be erased.
FileEnumerator::FileType types = static_cast<FileEnumerator::FileType>(
FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
FileEnumerator::SHOW_SYM_LINKS);
FileEnumerator enumerator(dir, false /* recursive */, types);
for (FilePath path = enumerator.Next();
!path.empty(); path = enumerator.Next()) {
FileEnumerator::FindInfo info;
enumerator.GetFindInfo(&info);
std::string basename = path.BaseName().value();
if (FileEnumerator::IsDirectory(info) || FileEnumerator::IsLink(info)) {
LOG(ERROR) << "Erasing bad file in AppPack directory: " << basename;
file_util::Delete(path, true /* recursive */);
continue;
}
// crx files in the cache are named <extension-id>-<version>.crx.
std::string id;
std::string version;
if (EndsWith(basename, kCRXFileExtension, false /* case-sensitive */)) {
size_t n = basename.find('-');
if (n != std::string::npos && n + 1 < basename.size() - 4) {
id = basename.substr(0, n);
// Size of |version| = total size - "<id>" - "-" - ".crx"
version = basename.substr(n + 1, basename.size() - 5 - id.size());
}
}
if (!extensions::Extension::IdIsValid(id)) {
LOG(ERROR) << "Bad AppPack extension id in cache: " << id;
id.clear();
} else if (!ContainsKey(*valid_ids, id)) {
LOG(WARNING) << basename << " is in the cache but is not configured by "
<< "the AppPack policy, and will be erased.";
id.clear();
}
if (!Version(version).IsValid()) {
LOG(ERROR) << "Bad AppPack extension version in cache: " << version;
version.clear();
}
if (id.empty() || version.empty()) {
LOG(ERROR) << "Invalid file in AppPack cache, erasing: " << basename;
file_util::Delete(path, true /* recursive */);
continue;
}
// Enforce a lower-case id.
id = StringToLowerASCII(id);
// File seems good so far. Make sure there isn't another entry with the
// same id but a different version.
if (ContainsKey(*entries, id)) {
LOG(ERROR) << "Found two AppPack files for the same extension, will "
"erase the oldest version";
CacheEntry& entry = (*entries)[id];
Version vEntry(entry.cached_version);
Version vCurrent(version);
DCHECK(vEntry.IsValid());
DCHECK(vCurrent.IsValid());
if (vEntry.CompareTo(vCurrent) < 0) {
file_util::Delete(FilePath(entry.path), true /* recursive */);
entry.path = path.value();
} else {
file_util::Delete(path, true /* recursive */);
}
continue;
}
// This is the only file for this |id| so far, add it.
CacheEntry& entry = (*entries)[id];
entry.path = path.value();
entry.cached_version = version;
}
}
void AppPackUpdater::OnCacheUpdated(CacheEntryMap* cache_entries) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
cached_extensions_.swap(*cache_entries);
CacheEntryMap::iterator it = cached_extensions_.find(screen_saver_id_);
if (it != cached_extensions_.end())
SetScreenSaverPath(FilePath(it->second.path));
else
SetScreenSaverPath(FilePath());
VLOG(1) << "Updated AppPack cache, there are " << cached_extensions_.size()
<< " extensions cached and "
<< (screen_saver_path_.empty() ? "no" : "the") << " screensaver";
UpdateExtensionLoader();
DownloadMissingExtensions();
}
void AppPackUpdater::UpdateExtensionLoader() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!extension_loader_) {
VLOG(1) << "No AppPack loader created yet, not pushing extensions.";
return;
}
// Build a DictionaryValue with the format that ExternalExtensionProviderImpl
// expects, containing info about the locally cached extensions.
scoped_ptr<base::DictionaryValue> prefs(new base::DictionaryValue());
for (CacheEntryMap::iterator it = cached_extensions_.begin();
it != cached_extensions_.end(); ++it) {
// The screensaver isn't installed into the Profile.
if (it->first == screen_saver_id_)
continue;
base::DictionaryValue* dict = new base::DictionaryValue();
dict->SetString(ExternalExtensionProviderImpl::kExternalCrx,
it->second.path);
dict->SetString(ExternalExtensionProviderImpl::kExternalVersion,
it->second.cached_version);
prefs->Set(it->first, dict);
VLOG(1) << "Updating AppPack extension loader, added " << it->second.path;
}
extension_loader_->SetCurrentAppPackExtensions(prefs.Pass());
}
void AppPackUpdater::DownloadMissingExtensions() {
// Check for updates for all extensions configured by the policy. Some of
// them may already be in the cache; only those with updated version will be
// downloaded, in that case.
if (!downloader_.get()) {
downloader_.reset(new extensions::ExtensionDownloader(this,
request_context_));
}
for (PolicyEntryMap::iterator it = app_pack_extensions_.begin();
it != app_pack_extensions_.end(); ++it) {
downloader_->AddPendingExtension(it->first, GURL(it->second.update_url));
}
VLOG(1) << "Downloading AppPack update manifest now";
downloader_->StartAllPending();
}
void AppPackUpdater::OnExtensionDownloadFailed(
const std::string& id,
extensions::ExtensionDownloaderDelegate::Error error,
const extensions::ExtensionDownloaderDelegate::PingResult& ping_result) {
if (error == NO_UPDATE_AVAILABLE) {
if (!ContainsKey(cached_extensions_, id))
LOG(ERROR) << "AppPack extension " << id << " not found on update server";
SetUpdateChecked(id);
} else {
LOG(ERROR) << "AppPack failed to download extension " << id
<< ", error " << error;
}
}
void AppPackUpdater::OnExtensionDownloadFinished(
const std::string& id,
const FilePath& path,
const GURL& download_url,
const std::string& version,
const extensions::ExtensionDownloaderDelegate::PingResult& ping_result) {
// Just downloaded the latest version, no need to do further update checks
// for this extension.
SetUpdateChecked(id);
// The explicit copy ctors are to make sure that Bind() binds a copy and not
// a reference to the arguments.
PostBlockingTask(FROM_HERE,
base::Bind(&AppPackUpdater::BlockingInstallCacheEntry,
weak_ptr_factory_.GetWeakPtr(),
std::string(id),
FilePath(path),
std::string(version)));
}
void AppPackUpdater::OnBlacklistDownloadFinished(
const std::string& data,
const std::string& package_hash,
const std::string& version,
const extensions::ExtensionDownloaderDelegate::PingResult& ping_result) {
NOTREACHED();
}
bool AppPackUpdater::IsExtensionPending(const std::string& id) {
// Pending means that there is no installed version yet.
return ContainsKey(app_pack_extensions_, id) &&
!ContainsKey(cached_extensions_, id);
}
bool AppPackUpdater::GetExtensionExistingVersion(const std::string& id,
std::string* version) {
if (!ContainsKey(app_pack_extensions_, id) ||
!ContainsKey(cached_extensions_, id)) {
return false;
}
*version = cached_extensions_[id].cached_version;
return true;
}
// static
void AppPackUpdater::BlockingInstallCacheEntry(
base::WeakPtr<AppPackUpdater> app_pack_updater,
const std::string& id,
const FilePath& path,
const std::string& version) {
Version version_validator(version);
if (!version_validator.IsValid()) {
LOG(ERROR) << "AppPack downloaded extension " << id << " but got bad "
<< "version: " << version;
file_util::Delete(path, true /* recursive */);
return;
}
std::string basename = id + "-" + version + kCRXFileExtension;
FilePath cache_dir(kAppPackCacheDir);
FilePath cached_crx_path = cache_dir.Append(basename);
if (file_util::PathExists(cached_crx_path)) {
LOG(WARNING) << "AppPack downloaded a crx whose filename will overwrite "
<< "an existing cached crx.";
file_util::Delete(cached_crx_path, true /* recursive */);
}
if (!file_util::DirectoryExists(cache_dir)) {
LOG(ERROR) << "AppPack cache directory does not exist, creating now: "
<< cache_dir.value();
if (!file_util::CreateDirectory(cache_dir)) {
LOG(ERROR) << "Failed to create the AppPack cache dir!";
file_util::Delete(path, true /* recursive */);
return;
}
}
if (!file_util::Move(path, cached_crx_path)) {
LOG(ERROR) << "Failed to move AppPack crx from " << path.value()
<< " to " << cached_crx_path.value();
file_util::Delete(path, true /* recursive */);
return;
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&AppPackUpdater::OnCacheEntryInstalled,
app_pack_updater,
std::string(id),
cached_crx_path.value(),
std::string(version)));
}
void AppPackUpdater::OnCacheEntryInstalled(const std::string& id,
const std::string& path,
const std::string& version) {
VLOG(1) << "AppPack installed a new extension in the cache: " << path;
// Add to the list of cached extensions.
CacheEntry& entry = cached_extensions_[id];
entry.path = path;
entry.cached_version = version;
if (id == screen_saver_id_) {
VLOG(1) << "AppPack got the screen saver extension at " << path;
SetScreenSaverPath(FilePath(path));
} else {
UpdateExtensionLoader();
}
}
void AppPackUpdater::OnCrxInstallFailed(CrxInstaller* installer) {
FilePath path = installer->source_file();
// Search for |path| in |cached_extensions_|, and delete it if found.
for (CacheEntryMap::iterator it = cached_extensions_.begin();
it != cached_extensions_.end(); ++it) {
if (it->second.path == path.value()) {
LOG(ERROR) << "AppPack extension at " << path.value() << " failed to "
<< "install, deleting it.";
cached_extensions_.erase(it);
UpdateExtensionLoader();
// The file will be downloaded again on the next restart.
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(base::IgnoreResult(file_util::Delete), path, true));
// Don't try to DownloadMissingExtensions() from here,
// since it can cause a fail/retry loop.
break;
}
}
}
void AppPackUpdater::PostBlockingTask(const tracked_objects::Location& location,
const base::Closure& task) {
BrowserThread::GetBlockingPool()->PostSequencedWorkerTaskWithShutdownBehavior(
worker_pool_token_, location, task,
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
}
void AppPackUpdater::SetScreenSaverPath(const FilePath& path) {
// Don't invoke the callback if the path isn't changing.
if (path != screen_saver_path_) {
screen_saver_path_ = path;
if (!screen_saver_update_callback_.is_null())
screen_saver_update_callback_.Run(screen_saver_path_);
}
}
void AppPackUpdater::SetUpdateChecked(const std::string& id) {
PolicyEntryMap::iterator entry = app_pack_extensions_.find(id);
if (entry != app_pack_extensions_.end())
entry->second.update_checked = true;
}
} // namespace policy
|