app_list: Re-enable people search.
[chromium-blink-merge.git] / chrome / browser / extensions / extension_system_impl.cc
blobd1d5e12b0f6a73a792a8946f3f59a38150e41718
1 // Copyright 2014 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.
5 #include "chrome/browser/extensions/extension_system_impl.h"
7 #include "base/base_switches.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/memory/weak_ptr.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/strings/string_tokenizer.h"
15 #include "base/strings/string_util.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/content_settings/cookie_settings.h"
18 #include "chrome/browser/extensions/component_loader.h"
19 #include "chrome/browser/extensions/declarative_user_script_manager.h"
20 #include "chrome/browser/extensions/error_console/error_console.h"
21 #include "chrome/browser/extensions/extension_error_reporter.h"
22 #include "chrome/browser/extensions/extension_management.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/extensions/extension_system_factory.h"
25 #include "chrome/browser/extensions/extension_util.h"
26 #include "chrome/browser/extensions/install_verifier.h"
27 #include "chrome/browser/extensions/navigation_observer.h"
28 #include "chrome/browser/extensions/shared_module_service.h"
29 #include "chrome/browser/extensions/shared_user_script_master.h"
30 #include "chrome/browser/extensions/state_store_notification_observer.h"
31 #include "chrome/browser/extensions/unpacked_installer.h"
32 #include "chrome/browser/profiles/profile.h"
33 #include "chrome/browser/profiles/profile_manager.h"
34 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/chrome_version_info.h"
37 #include "chrome/common/extensions/extension_constants.h"
38 #include "chrome/common/extensions/features/feature_channel.h"
39 #include "content/public/browser/browser_thread.h"
40 #include "content/public/browser/url_data_source.h"
41 #include "extensions/browser/content_verifier.h"
42 #include "extensions/browser/content_verifier_delegate.h"
43 #include "extensions/browser/event_router.h"
44 #include "extensions/browser/extension_pref_store.h"
45 #include "extensions/browser/extension_pref_value_map.h"
46 #include "extensions/browser/extension_pref_value_map_factory.h"
47 #include "extensions/browser/extension_prefs.h"
48 #include "extensions/browser/extension_registry.h"
49 #include "extensions/browser/info_map.h"
50 #include "extensions/browser/lazy_background_task_queue.h"
51 #include "extensions/browser/management_policy.h"
52 #include "extensions/browser/quota_service.h"
53 #include "extensions/browser/runtime_data.h"
54 #include "extensions/browser/state_store.h"
55 #include "extensions/common/constants.h"
56 #include "extensions/common/extension.h"
57 #include "extensions/common/extension_urls.h"
58 #include "extensions/common/extensions_client.h"
59 #include "extensions/common/manifest.h"
60 #include "extensions/common/manifest_url_handlers.h"
61 #include "net/base/escape.h"
63 #if defined(ENABLE_NOTIFICATIONS)
64 #include "chrome/browser/notifications/desktop_notification_service.h"
65 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
66 #include "ui/message_center/notifier_settings.h"
67 #endif
69 #if defined(OS_CHROMEOS)
70 #include "chrome/browser/app_mode/app_mode_utils.h"
71 #include "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h"
72 #include "chrome/browser/chromeos/policy/device_local_account.h"
73 #include "chrome/browser/extensions/extension_assets_manager_chromeos.h"
74 #include "chromeos/chromeos_switches.h"
75 #include "chromeos/login/login_state.h"
76 #include "components/user_manager/user.h"
77 #include "components/user_manager/user_manager.h"
78 #endif
80 using content::BrowserThread;
82 namespace {
84 const char kContentVerificationExperimentName[] =
85 "ExtensionContentVerification";
87 } // namespace
89 namespace extensions {
92 // ExtensionSystemImpl::Shared
95 ExtensionSystemImpl::Shared::Shared(Profile* profile)
96 : profile_(profile) {
99 ExtensionSystemImpl::Shared::~Shared() {
102 void ExtensionSystemImpl::Shared::InitPrefs() {
103 lazy_background_task_queue_.reset(new LazyBackgroundTaskQueue(profile_));
104 event_router_.reset(new EventRouter(profile_, ExtensionPrefs::Get(profile_)));
105 // Two state stores. The latter, which contains declarative rules, must be
106 // loaded immediately so that the rules are ready before we issue network
107 // requests.
108 state_store_.reset(new StateStore(
109 profile_,
110 profile_->GetPath().AppendASCII(extensions::kStateStoreName),
111 true));
112 state_store_notification_observer_.reset(
113 new StateStoreNotificationObserver(state_store_.get()));
115 rules_store_.reset(new StateStore(
116 profile_,
117 profile_->GetPath().AppendASCII(extensions::kRulesStoreName),
118 false));
120 #if defined(OS_CHROMEOS)
121 const user_manager::User* user =
122 user_manager::UserManager::Get()->GetActiveUser();
123 policy::DeviceLocalAccount::Type device_local_account_type;
124 if (user && policy::IsDeviceLocalAccountUser(user->email(),
125 &device_local_account_type)) {
126 device_local_account_management_policy_provider_.reset(
127 new chromeos::DeviceLocalAccountManagementPolicyProvider(
128 device_local_account_type));
130 #endif // defined(OS_CHROMEOS)
133 void ExtensionSystemImpl::Shared::RegisterManagementPolicyProviders() {
134 management_policy_->RegisterProviders(
135 ExtensionManagementFactory::GetForBrowserContext(profile_)
136 ->GetProviders());
138 #if defined(OS_CHROMEOS)
139 if (device_local_account_management_policy_provider_) {
140 management_policy_->RegisterProvider(
141 device_local_account_management_policy_provider_.get());
143 #endif // defined(OS_CHROMEOS)
145 management_policy_->RegisterProvider(install_verifier_.get());
148 namespace {
150 class ContentVerifierDelegateImpl : public ContentVerifierDelegate {
151 public:
152 explicit ContentVerifierDelegateImpl(ExtensionService* service)
153 : service_(service->AsWeakPtr()), default_mode_(GetDefaultMode()) {}
155 ~ContentVerifierDelegateImpl() override {}
157 Mode ShouldBeVerified(const Extension& extension) override {
158 #if defined(OS_CHROMEOS)
159 if (ExtensionAssetsManagerChromeOS::IsSharedInstall(&extension))
160 return ContentVerifierDelegate::ENFORCE_STRICT;
161 #endif
163 if (!extension.is_extension() && !extension.is_legacy_packaged_app())
164 return ContentVerifierDelegate::NONE;
165 if (!Manifest::IsAutoUpdateableLocation(extension.location()))
166 return ContentVerifierDelegate::NONE;
168 if (!ManifestURL::UpdatesFromGallery(&extension)) {
169 // It's possible that the webstore update url was overridden for testing
170 // so also consider extensions with the default (production) update url
171 // to be from the store as well.
172 GURL default_webstore_url = extension_urls::GetDefaultWebstoreUpdateUrl();
173 if (ManifestURL::GetUpdateURL(&extension) != default_webstore_url)
174 return ContentVerifierDelegate::NONE;
177 return default_mode_;
180 const ContentVerifierKey& PublicKey() override {
181 static ContentVerifierKey key(
182 extension_misc::kWebstoreSignaturesPublicKey,
183 extension_misc::kWebstoreSignaturesPublicKeySize);
184 return key;
187 GURL GetSignatureFetchUrl(const std::string& extension_id,
188 const base::Version& version) override {
189 // TODO(asargent) Factor out common code from the extension updater's
190 // ManifestFetchData class that can be shared for use here.
191 std::vector<std::string> parts;
192 parts.push_back("uc");
193 parts.push_back("installsource=signature");
194 parts.push_back("id=" + extension_id);
195 parts.push_back("v=" + version.GetString());
196 std::string x_value =
197 net::EscapeQueryParamValue(JoinString(parts, "&"), true);
198 std::string query = "response=redirect&x=" + x_value;
200 GURL base_url = extension_urls::GetWebstoreUpdateUrl();
201 GURL::Replacements replacements;
202 replacements.SetQuery(query.c_str(), url::Component(0, query.length()));
203 return base_url.ReplaceComponents(replacements);
206 std::set<base::FilePath> GetBrowserImagePaths(
207 const extensions::Extension* extension) override {
208 return ExtensionsClient::Get()->GetBrowserImagePaths(extension);
211 void VerifyFailed(const std::string& extension_id,
212 ContentVerifyJob::FailureReason reason) override {
213 if (!service_)
214 return;
215 ExtensionRegistry* registry = ExtensionRegistry::Get(service_->profile());
216 const Extension* extension =
217 registry->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
218 if (!extension)
219 return;
220 Mode mode = ShouldBeVerified(*extension);
221 if (mode >= ContentVerifierDelegate::ENFORCE) {
222 service_->DisableExtension(extension_id, Extension::DISABLE_CORRUPTED);
223 ExtensionPrefs::Get(service_->profile())
224 ->IncrementCorruptedDisableCount();
225 UMA_HISTOGRAM_BOOLEAN("Extensions.CorruptExtensionBecameDisabled", true);
226 UMA_HISTOGRAM_ENUMERATION("Extensions.CorruptExtensionDisabledReason",
227 reason, ContentVerifyJob::FAILURE_REASON_MAX);
228 } else if (!ContainsKey(would_be_disabled_ids_, extension_id)) {
229 UMA_HISTOGRAM_BOOLEAN("Extensions.CorruptExtensionWouldBeDisabled", true);
230 would_be_disabled_ids_.insert(extension_id);
234 static Mode GetDefaultMode() {
235 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
237 Mode experiment_value = NONE;
238 const std::string group = base::FieldTrialList::FindFullName(
239 kContentVerificationExperimentName);
240 if (group == "EnforceStrict")
241 experiment_value = ContentVerifierDelegate::ENFORCE_STRICT;
242 else if (group == "Enforce")
243 experiment_value = ContentVerifierDelegate::ENFORCE;
244 else if (group == "Bootstrap")
245 experiment_value = ContentVerifierDelegate::BOOTSTRAP;
247 // The field trial value that normally comes from the server can be
248 // overridden on the command line, which we don't want to allow since
249 // malware can set chrome command line flags. There isn't currently a way
250 // to find out what the server-provided value is in this case, so we
251 // conservatively default to the strictest mode if we detect our experiment
252 // name being overridden.
253 if (command_line->HasSwitch(switches::kForceFieldTrials)) {
254 std::string forced_trials =
255 command_line->GetSwitchValueASCII(switches::kForceFieldTrials);
256 if (forced_trials.find(kContentVerificationExperimentName) !=
257 std::string::npos)
258 experiment_value = ContentVerifierDelegate::ENFORCE_STRICT;
261 Mode cmdline_value = NONE;
262 if (command_line->HasSwitch(switches::kExtensionContentVerification)) {
263 std::string switch_value = command_line->GetSwitchValueASCII(
264 switches::kExtensionContentVerification);
265 if (switch_value == switches::kExtensionContentVerificationBootstrap)
266 cmdline_value = ContentVerifierDelegate::BOOTSTRAP;
267 else if (switch_value == switches::kExtensionContentVerificationEnforce)
268 cmdline_value = ContentVerifierDelegate::ENFORCE;
269 else if (switch_value ==
270 switches::kExtensionContentVerificationEnforceStrict)
271 cmdline_value = ContentVerifierDelegate::ENFORCE_STRICT;
272 else
273 // If no value was provided (or the wrong one), just default to enforce.
274 cmdline_value = ContentVerifierDelegate::ENFORCE;
277 // We don't want to allow the command-line flags to eg disable enforcement
278 // if the experiment group says it should be on, or malware may just modify
279 // the command line flags. So return the more restrictive of the 2 values.
280 return std::max(experiment_value, cmdline_value);
283 private:
284 base::WeakPtr<ExtensionService> service_;
285 ContentVerifierDelegate::Mode default_mode_;
287 // For reporting metrics in BOOTSTRAP mode, when an extension would be
288 // disabled if content verification was in ENFORCE mode.
289 std::set<std::string> would_be_disabled_ids_;
291 DISALLOW_COPY_AND_ASSIGN(ContentVerifierDelegateImpl);
294 } // namespace
296 void ExtensionSystemImpl::Shared::Init(bool extensions_enabled) {
297 const base::CommandLine* command_line =
298 base::CommandLine::ForCurrentProcess();
300 navigation_observer_.reset(new NavigationObserver(profile_));
302 bool allow_noisy_errors = !command_line->HasSwitch(switches::kNoErrorDialogs);
303 ExtensionErrorReporter::Init(allow_noisy_errors);
305 shared_user_script_master_.reset(new SharedUserScriptMaster(profile_));
306 declarative_user_script_manager_.reset(
307 new DeclarativeUserScriptManager(profile_));
309 // ExtensionService depends on RuntimeData.
310 runtime_data_.reset(new RuntimeData(ExtensionRegistry::Get(profile_)));
312 bool autoupdate_enabled = !profile_->IsGuestSession();
313 #if defined(OS_CHROMEOS)
314 if (!extensions_enabled)
315 autoupdate_enabled = false;
316 #endif
317 extension_service_.reset(new ExtensionService(
318 profile_, base::CommandLine::ForCurrentProcess(),
319 profile_->GetPath().AppendASCII(extensions::kInstallDirectoryName),
320 ExtensionPrefs::Get(profile_), Blacklist::Get(profile_),
321 autoupdate_enabled, extensions_enabled, &ready_));
323 // These services must be registered before the ExtensionService tries to
324 // load any extensions.
326 install_verifier_.reset(
327 new InstallVerifier(ExtensionPrefs::Get(profile_), profile_));
328 install_verifier_->Init();
329 content_verifier_ = new ContentVerifier(
330 profile_, new ContentVerifierDelegateImpl(extension_service_.get()));
331 ContentVerifierDelegate::Mode mode =
332 ContentVerifierDelegateImpl::GetDefaultMode();
333 #if defined(OS_CHROMEOS)
334 mode = std::max(mode, ContentVerifierDelegate::BOOTSTRAP);
335 #endif
336 if (mode >= ContentVerifierDelegate::BOOTSTRAP)
337 content_verifier_->Start();
338 info_map()->SetContentVerifier(content_verifier_.get());
340 management_policy_.reset(new ManagementPolicy);
341 RegisterManagementPolicyProviders();
344 bool skip_session_extensions = false;
345 #if defined(OS_CHROMEOS)
346 // Skip loading session extensions if we are not in a user session.
347 skip_session_extensions = !chromeos::LoginState::Get()->IsUserLoggedIn();
348 if (chrome::IsRunningInForcedAppMode()) {
349 extension_service_->component_loader()->
350 AddDefaultComponentExtensionsForKioskMode(skip_session_extensions);
351 } else {
352 extension_service_->component_loader()->AddDefaultComponentExtensions(
353 skip_session_extensions);
355 #else
356 extension_service_->component_loader()->AddDefaultComponentExtensions(
357 skip_session_extensions);
358 #endif
359 if (command_line->HasSwitch(switches::kLoadComponentExtension)) {
360 base::CommandLine::StringType path_list =
361 command_line->GetSwitchValueNative(switches::kLoadComponentExtension);
362 base::StringTokenizerT<base::CommandLine::StringType,
363 base::CommandLine::StringType::const_iterator>
364 t(path_list, FILE_PATH_LITERAL(","));
365 while (t.GetNext()) {
366 // Load the component extension manifest synchronously.
367 // Blocking the UI thread is acceptable here since
368 // this flag designated for developers.
369 base::ThreadRestrictions::ScopedAllowIO allow_io;
370 extension_service_->component_loader()->AddOrReplace(
371 base::FilePath(t.token()));
374 extension_service_->Init();
376 // Make the chrome://extension-icon/ resource available.
377 content::URLDataSource::Add(profile_, new ExtensionIconSource(profile_));
379 error_console_.reset(new ErrorConsole(profile_));
380 quota_service_.reset(new QuotaService);
382 if (extensions_enabled) {
383 // Load any extensions specified with --load-extension.
384 // TODO(yoz): Seems like this should move into ExtensionService::Init.
385 // But maybe it's no longer important.
386 if (command_line->HasSwitch(switches::kLoadExtension)) {
387 base::CommandLine::StringType path_list =
388 command_line->GetSwitchValueNative(switches::kLoadExtension);
389 base::StringTokenizerT<base::CommandLine::StringType,
390 base::CommandLine::StringType::const_iterator>
391 t(path_list, FILE_PATH_LITERAL(","));
392 while (t.GetNext()) {
393 std::string extension_id;
394 UnpackedInstaller::Create(extension_service_.get())->
395 LoadFromCommandLine(base::FilePath(t.token()), &extension_id);
401 void ExtensionSystemImpl::Shared::Shutdown() {
402 if (content_verifier_.get())
403 content_verifier_->Shutdown();
404 if (extension_service_)
405 extension_service_->Shutdown();
408 StateStore* ExtensionSystemImpl::Shared::state_store() {
409 return state_store_.get();
412 StateStore* ExtensionSystemImpl::Shared::rules_store() {
413 return rules_store_.get();
416 ExtensionService* ExtensionSystemImpl::Shared::extension_service() {
417 return extension_service_.get();
420 RuntimeData* ExtensionSystemImpl::Shared::runtime_data() {
421 return runtime_data_.get();
424 ManagementPolicy* ExtensionSystemImpl::Shared::management_policy() {
425 return management_policy_.get();
428 SharedUserScriptMaster*
429 ExtensionSystemImpl::Shared::shared_user_script_master() {
430 return shared_user_script_master_.get();
433 DeclarativeUserScriptManager*
434 ExtensionSystemImpl::Shared::declarative_user_script_manager() {
435 return declarative_user_script_manager_.get();
438 InfoMap* ExtensionSystemImpl::Shared::info_map() {
439 if (!extension_info_map_.get())
440 extension_info_map_ = new InfoMap();
441 return extension_info_map_.get();
444 LazyBackgroundTaskQueue*
445 ExtensionSystemImpl::Shared::lazy_background_task_queue() {
446 return lazy_background_task_queue_.get();
449 EventRouter* ExtensionSystemImpl::Shared::event_router() {
450 return event_router_.get();
453 ErrorConsole* ExtensionSystemImpl::Shared::error_console() {
454 return error_console_.get();
457 InstallVerifier* ExtensionSystemImpl::Shared::install_verifier() {
458 return install_verifier_.get();
461 QuotaService* ExtensionSystemImpl::Shared::quota_service() {
462 return quota_service_.get();
465 ContentVerifier* ExtensionSystemImpl::Shared::content_verifier() {
466 return content_verifier_.get();
470 // ExtensionSystemImpl
473 ExtensionSystemImpl::ExtensionSystemImpl(Profile* profile)
474 : profile_(profile) {
475 shared_ = ExtensionSystemSharedFactory::GetForBrowserContext(profile);
477 if (!profile->IsOffTheRecord()) {
478 shared_->InitPrefs();
482 ExtensionSystemImpl::~ExtensionSystemImpl() {
485 void ExtensionSystemImpl::Shutdown() {
488 void ExtensionSystemImpl::InitForRegularProfile(bool extensions_enabled) {
489 DCHECK(!profile_->IsOffTheRecord());
490 if (shared_user_script_master() || extension_service())
491 return; // Already initialized.
493 // The InfoMap needs to be created before the ProcessManager.
494 shared_->info_map();
495 shared_->Init(extensions_enabled);
498 ExtensionService* ExtensionSystemImpl::extension_service() {
499 return shared_->extension_service();
502 RuntimeData* ExtensionSystemImpl::runtime_data() {
503 return shared_->runtime_data();
506 ManagementPolicy* ExtensionSystemImpl::management_policy() {
507 return shared_->management_policy();
510 SharedUserScriptMaster* ExtensionSystemImpl::shared_user_script_master() {
511 return shared_->shared_user_script_master();
514 DeclarativeUserScriptManager*
515 ExtensionSystemImpl::declarative_user_script_manager() {
516 return shared_->declarative_user_script_manager();
519 StateStore* ExtensionSystemImpl::state_store() {
520 return shared_->state_store();
523 StateStore* ExtensionSystemImpl::rules_store() {
524 return shared_->rules_store();
527 InfoMap* ExtensionSystemImpl::info_map() { return shared_->info_map(); }
529 LazyBackgroundTaskQueue* ExtensionSystemImpl::lazy_background_task_queue() {
530 return shared_->lazy_background_task_queue();
533 EventRouter* ExtensionSystemImpl::event_router() {
534 return shared_->event_router();
537 const OneShotEvent& ExtensionSystemImpl::ready() const {
538 return shared_->ready();
541 ErrorConsole* ExtensionSystemImpl::error_console() {
542 return shared_->error_console();
545 InstallVerifier* ExtensionSystemImpl::install_verifier() {
546 return shared_->install_verifier();
549 QuotaService* ExtensionSystemImpl::quota_service() {
550 return shared_->quota_service();
553 ContentVerifier* ExtensionSystemImpl::content_verifier() {
554 return shared_->content_verifier();
557 scoped_ptr<ExtensionSet> ExtensionSystemImpl::GetDependentExtensions(
558 const Extension* extension) {
559 return extension_service()->shared_module_service()->GetDependentExtensions(
560 extension);
563 void ExtensionSystemImpl::RegisterExtensionWithRequestContexts(
564 const Extension* extension) {
565 base::Time install_time;
566 if (extension->location() != Manifest::COMPONENT) {
567 install_time = ExtensionPrefs::Get(profile_)->
568 GetInstallTime(extension->id());
570 bool incognito_enabled = util::IsIncognitoEnabled(extension->id(), profile_);
572 bool notifications_disabled = false;
573 #if defined(ENABLE_NOTIFICATIONS)
574 message_center::NotifierId notifier_id(
575 message_center::NotifierId::APPLICATION,
576 extension->id());
578 DesktopNotificationService* notification_service =
579 DesktopNotificationServiceFactory::GetForProfile(profile_);
580 notifications_disabled =
581 !notification_service->IsNotifierEnabled(notifier_id);
582 #endif
584 BrowserThread::PostTask(
585 BrowserThread::IO, FROM_HERE,
586 base::Bind(&InfoMap::AddExtension, info_map(),
587 make_scoped_refptr(extension), install_time,
588 incognito_enabled, notifications_disabled));
591 void ExtensionSystemImpl::UnregisterExtensionWithRequestContexts(
592 const std::string& extension_id,
593 const UnloadedExtensionInfo::Reason reason) {
594 BrowserThread::PostTask(
595 BrowserThread::IO,
596 FROM_HERE,
597 base::Bind(&InfoMap::RemoveExtension, info_map(), extension_id, reason));
600 } // namespace extensions