1 // Copyright (c) 2012 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/prefs/chrome_pref_service_factory.h"
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/files/file_path.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/prefs/default_pref_store.h"
16 #include "base/prefs/json_pref_store.h"
17 #include "base/prefs/pref_filter.h"
18 #include "base/prefs/pref_notifier_impl.h"
19 #include "base/prefs/pref_registry.h"
20 #include "base/prefs/pref_registry_simple.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/prefs/pref_store.h"
23 #include "base/prefs/pref_value_store.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/time/time.h"
26 #include "base/trace_event/trace_event.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/prefs/command_line_pref_store.h"
29 #include "chrome/browser/prefs/pref_model_associator.h"
30 #include "chrome/browser/prefs/pref_service_syncable.h"
31 #include "chrome/browser/prefs/pref_service_syncable_factory.h"
32 #include "chrome/browser/prefs/profile_pref_store_manager.h"
33 #include "chrome/browser/prefs/tracked/pref_hash_filter.h"
34 #include "chrome/browser/profiles/file_path_verifier_win.h"
35 #include "chrome/browser/profiles/profile.h"
36 #include "chrome/browser/search_engines/default_search_pref_migration.h"
37 #include "chrome/browser/sync/glue/sync_start_util.h"
38 #include "chrome/browser/ui/profile_error_dialog.h"
39 #include "chrome/common/chrome_constants.h"
40 #include "chrome/common/pref_names.h"
41 #include "chrome/grit/chromium_strings.h"
42 #include "chrome/grit/generated_resources.h"
43 #include "components/component_updater/pref_names.h"
44 #include "components/pref_registry/pref_registry_syncable.h"
45 #include "components/search_engines/default_search_manager.h"
46 #include "components/search_engines/search_engines_pref_names.h"
47 #include "components/sync_driver/pref_names.h"
48 #include "content/public/browser/browser_context.h"
49 #include "content/public/browser/browser_thread.h"
50 #include "grit/browser_resources.h"
51 #include "sync/internal_api/public/base/model_type.h"
52 #include "ui/base/resource/resource_bundle.h"
54 #if defined(ENABLE_CONFIGURATION_POLICY)
55 #include "components/policy/core/browser/browser_policy_connector.h"
56 #include "components/policy/core/browser/configuration_policy_pref_store.h"
57 #include "components/policy/core/common/policy_types.h"
60 #if defined(ENABLE_EXTENSIONS)
61 #include "extensions/browser/pref_names.h"
64 #if defined(ENABLE_SUPERVISED_USERS)
65 #include "chrome/browser/supervised_user/supervised_user_pref_store.h"
69 #include "base/win/win_util.h"
70 #if defined(ENABLE_RLZ)
71 #include "rlz/lib/machine_id.h"
72 #endif // defined(ENABLE_RLZ)
73 #endif // defined(OS_WIN)
75 using content::BrowserContext
;
76 using content::BrowserThread
;
81 // Whether we are in testing mode; can be enabled via
82 // DisableDomainCheckForTesting(). Forces startup checks to ignore the presence
83 // of a domain when determining the active SettingsEnforcement group.
84 bool g_disable_domain_check_for_testing
= false;
87 // These preferences must be kept in sync with the TrackedPreference enum in
88 // tools/metrics/histograms/histograms.xml. To add a new preference, append it
89 // to the array and add a corresponding value to the histogram enum. Each
90 // tracked preference must be given a unique reporting ID.
91 // See CleanupDeprecatedTrackedPreferences() in pref_hash_filter.cc to remove a
92 // deprecated tracked preference.
93 const PrefHashFilter::TrackedPreferenceMetadata kTrackedPrefs
[] = {
95 0, prefs::kShowHomeButton
,
96 PrefHashFilter::ENFORCE_ON_LOAD
,
97 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
98 PrefHashFilter::VALUE_IMPERSONAL
101 1, prefs::kHomePageIsNewTabPage
,
102 PrefHashFilter::ENFORCE_ON_LOAD
,
103 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
104 PrefHashFilter::VALUE_IMPERSONAL
108 PrefHashFilter::ENFORCE_ON_LOAD
,
109 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
110 PrefHashFilter::VALUE_IMPERSONAL
113 3, prefs::kRestoreOnStartup
,
114 PrefHashFilter::ENFORCE_ON_LOAD
,
115 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
116 PrefHashFilter::VALUE_IMPERSONAL
119 4, prefs::kURLsToRestoreOnStartup
,
120 PrefHashFilter::ENFORCE_ON_LOAD
,
121 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
122 PrefHashFilter::VALUE_IMPERSONAL
124 #if defined(ENABLE_EXTENSIONS)
126 5, extensions::pref_names::kExtensions
,
127 PrefHashFilter::NO_ENFORCEMENT
,
128 PrefHashFilter::TRACKING_STRATEGY_SPLIT
,
129 PrefHashFilter::VALUE_IMPERSONAL
133 6, prefs::kGoogleServicesLastUsername
,
134 PrefHashFilter::ENFORCE_ON_LOAD
,
135 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
136 PrefHashFilter::VALUE_PERSONAL
139 7, prefs::kSearchProviderOverrides
,
140 PrefHashFilter::ENFORCE_ON_LOAD
,
141 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
142 PrefHashFilter::VALUE_IMPERSONAL
145 8, prefs::kDefaultSearchProviderSearchURL
,
146 PrefHashFilter::ENFORCE_ON_LOAD
,
147 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
148 PrefHashFilter::VALUE_IMPERSONAL
151 9, prefs::kDefaultSearchProviderKeyword
,
152 PrefHashFilter::ENFORCE_ON_LOAD
,
153 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
154 PrefHashFilter::VALUE_IMPERSONAL
157 10, prefs::kDefaultSearchProviderName
,
158 PrefHashFilter::ENFORCE_ON_LOAD
,
159 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
160 PrefHashFilter::VALUE_IMPERSONAL
162 #if !defined(OS_ANDROID)
164 11, prefs::kPinnedTabs
,
165 PrefHashFilter::ENFORCE_ON_LOAD
,
166 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
167 PrefHashFilter::VALUE_IMPERSONAL
170 13, prefs::kProfileResetPromptMementoInProfilePrefs
,
171 PrefHashFilter::ENFORCE_ON_LOAD
,
172 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
173 PrefHashFilter::VALUE_IMPERSONAL
177 14, DefaultSearchManager::kDefaultSearchProviderDataPrefName
,
178 PrefHashFilter::NO_ENFORCEMENT
,
179 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
180 PrefHashFilter::VALUE_IMPERSONAL
183 // Protecting kPreferenceResetTime does two things:
184 // 1) It ensures this isn't accidently set by someone stomping the pref
186 // 2) More importantly, it declares kPreferenceResetTime as a protected
187 // pref which is required for it to be visible when queried via the
188 // SegregatedPrefStore. This is because it's written directly in the
189 // protected JsonPrefStore by that store's PrefHashFilter if there was
190 // a reset in FilterOnLoad and SegregatedPrefStore will not look for it
191 // in the protected JsonPrefStore unless it's declared as a protected
193 15, prefs::kPreferenceResetTime
,
194 PrefHashFilter::ENFORCE_ON_LOAD
,
195 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
196 PrefHashFilter::VALUE_IMPERSONAL
199 17, sync_driver::prefs::kSyncRemainingRollbackTries
,
200 PrefHashFilter::ENFORCE_ON_LOAD
,
201 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
202 PrefHashFilter::VALUE_IMPERSONAL
205 18, prefs::kSafeBrowsingIncidentsSent
,
206 PrefHashFilter::ENFORCE_ON_LOAD
,
207 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
208 PrefHashFilter::VALUE_IMPERSONAL
212 19, prefs::kSwReporterPromptVersion
,
213 PrefHashFilter::ENFORCE_ON_LOAD
,
214 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
215 PrefHashFilter::VALUE_IMPERSONAL
218 20, prefs::kSwReporterPromptReason
,
219 PrefHashFilter::ENFORCE_ON_LOAD
,
220 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
221 PrefHashFilter::VALUE_IMPERSONAL
225 21, prefs::kGoogleServicesUsername
,
226 PrefHashFilter::ENFORCE_ON_LOAD
,
227 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
228 PrefHashFilter::VALUE_PERSONAL
232 22, prefs::kSwReporterPromptSeed
,
233 PrefHashFilter::ENFORCE_ON_LOAD
,
234 PrefHashFilter::TRACKING_STRATEGY_ATOMIC
,
235 PrefHashFilter::VALUE_IMPERSONAL
238 // See note at top, new items added here also need to be added to
239 // histograms.xml's TrackedPreference enum.
242 // One more than the last tracked preferences ID above.
243 const size_t kTrackedPrefsReportingIDsCount
=
244 kTrackedPrefs
[arraysize(kTrackedPrefs
) - 1].reporting_id
+ 1;
246 // Each group enforces a superset of the protection provided by the previous
248 enum SettingsEnforcementGroup
{
249 GROUP_NO_ENFORCEMENT
,
250 // Enforce protected settings on profile loads.
251 GROUP_ENFORCE_ALWAYS
,
252 // Also enforce extension default search.
253 GROUP_ENFORCE_ALWAYS_WITH_DSE
,
254 // Also enforce extension settings and default search.
255 GROUP_ENFORCE_ALWAYS_WITH_EXTENSIONS_AND_DSE
,
256 // The default enforcement group contains all protection features.
257 GROUP_ENFORCE_DEFAULT
260 SettingsEnforcementGroup
GetSettingsEnforcementGroup() {
262 if (!g_disable_domain_check_for_testing
) {
263 static bool first_call
= true;
264 static const bool is_enrolled_to_domain
= base::win::IsEnrolledToDomain();
266 UMA_HISTOGRAM_BOOLEAN("Settings.TrackedPreferencesNoEnforcementOnDomain",
267 is_enrolled_to_domain
);
270 if (is_enrolled_to_domain
)
271 return GROUP_NO_ENFORCEMENT
;
276 const char* group_name
;
277 SettingsEnforcementGroup group
;
278 } static const kEnforcementLevelMap
[] = {
279 { chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement
,
280 GROUP_NO_ENFORCEMENT
},
281 { chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways
,
282 GROUP_ENFORCE_ALWAYS
},
283 { chrome_prefs::internals::
284 kSettingsEnforcementGroupEnforceAlwaysWithDSE
,
285 GROUP_ENFORCE_ALWAYS_WITH_DSE
},
286 { chrome_prefs::internals::
287 kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE
,
288 GROUP_ENFORCE_ALWAYS_WITH_EXTENSIONS_AND_DSE
},
291 // Use the strongest enforcement setting in the absence of a field trial
292 // config on Windows. Remember to update the OFFICIAL_BUILD section of
293 // extension_startup_browsertest.cc and pref_hash_browsertest.cc when updating
294 // the default value below.
295 // TODO(gab): Enforce this on all platforms.
296 SettingsEnforcementGroup enforcement_group
=
298 GROUP_ENFORCE_DEFAULT
;
300 GROUP_NO_ENFORCEMENT
;
302 bool group_determined_from_trial
= false;
303 base::FieldTrial
* trial
=
304 base::FieldTrialList::Find(
305 chrome_prefs::internals::kSettingsEnforcementTrialName
);
307 const std::string
& group_name
= trial
->group_name();
308 for (size_t i
= 0; i
< arraysize(kEnforcementLevelMap
); ++i
) {
309 if (kEnforcementLevelMap
[i
].group_name
== group_name
) {
310 enforcement_group
= kEnforcementLevelMap
[i
].group
;
311 group_determined_from_trial
= true;
316 UMA_HISTOGRAM_BOOLEAN("Settings.EnforcementGroupDeterminedFromTrial",
317 group_determined_from_trial
);
318 return enforcement_group
;
321 // Returns the effective preference tracking configuration.
322 std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>
323 GetTrackingConfiguration() {
324 const SettingsEnforcementGroup enforcement_group
=
325 GetSettingsEnforcementGroup();
327 std::vector
<PrefHashFilter::TrackedPreferenceMetadata
> result
;
328 for (size_t i
= 0; i
< arraysize(kTrackedPrefs
); ++i
) {
329 PrefHashFilter::TrackedPreferenceMetadata data
= kTrackedPrefs
[i
];
331 if (GROUP_NO_ENFORCEMENT
== enforcement_group
) {
332 // Remove enforcement for all tracked preferences.
333 data
.enforcement_level
= PrefHashFilter::NO_ENFORCEMENT
;
336 if (enforcement_group
>= GROUP_ENFORCE_ALWAYS_WITH_DSE
&&
337 data
.name
== DefaultSearchManager::kDefaultSearchProviderDataPrefName
) {
338 // Specifically enable default search settings enforcement.
339 data
.enforcement_level
= PrefHashFilter::ENFORCE_ON_LOAD
;
342 #if defined(ENABLE_EXTENSIONS)
343 if (enforcement_group
>= GROUP_ENFORCE_ALWAYS_WITH_EXTENSIONS_AND_DSE
&&
344 data
.name
== extensions::pref_names::kExtensions
) {
345 // Specifically enable extension settings enforcement.
346 data
.enforcement_level
= PrefHashFilter::ENFORCE_ON_LOAD
;
350 result
.push_back(data
);
355 // Shows notifications which correspond to PersistentPrefStore's reading errors.
356 void HandleReadError(PersistentPrefStore::PrefReadError error
) {
357 // Sample the histogram also for the successful case in order to get a
358 // baseline on the success rate in addition to the error distribution.
359 UMA_HISTOGRAM_ENUMERATION("PrefService.ReadError", error
,
360 PersistentPrefStore::PREF_READ_ERROR_MAX_ENUM
);
362 if (error
!= PersistentPrefStore::PREF_READ_ERROR_NONE
) {
363 #if !defined(OS_CHROMEOS)
364 // Failing to load prefs on startup is a bad thing(TM). See bug 38352 for
365 // an example problem that this can cause.
366 // Do some diagnosis and try to avoid losing data.
368 if (error
<= PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE
||
369 error
== PersistentPrefStore::PREF_READ_ERROR_LEVELDB_CORRUPTION
) {
370 message_id
= IDS_PREFERENCES_CORRUPT_ERROR
;
371 } else if (error
!= PersistentPrefStore::PREF_READ_ERROR_NO_FILE
) {
372 message_id
= IDS_PREFERENCES_UNREADABLE_ERROR
;
376 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
377 base::Bind(&ShowProfileErrorDialog
,
378 PROFILE_ERROR_PREFERENCES
,
382 // On ChromeOS error screen with message about broken local state
383 // will be displayed.
385 // A supplementary error message about broken local state - is included
386 // in logs and user feedbacks.
387 if (error
!= PersistentPrefStore::PREF_READ_ERROR_NONE
&&
388 error
!= PersistentPrefStore::PREF_READ_ERROR_NO_FILE
) {
389 LOG(ERROR
) << "An error happened during prefs loading: " << error
;
395 scoped_ptr
<ProfilePrefStoreManager
> CreateProfilePrefStoreManager(
396 const base::FilePath
& profile_path
) {
397 std::string device_id
;
398 #if defined(OS_WIN) && defined(ENABLE_RLZ)
400 // chrome/browser/extensions/api/music_manager_private/device_id_win.cc
401 // but that API is private (http://crbug.com/276485) and other platforms are
402 // not available synchronously.
403 // As part of improving pref metrics on other platforms we may want to find
404 // ways to defer preference loading until the device ID can be used.
405 rlz_lib::GetMachineId(&device_id
);
408 #if defined(GOOGLE_CHROME_BUILD)
409 seed
= ResourceBundle::GetSharedInstance().GetRawDataResource(
410 IDR_PREF_HASH_SEED_BIN
).as_string();
412 return make_scoped_ptr(new ProfilePrefStoreManager(
414 GetTrackingConfiguration(),
415 kTrackedPrefsReportingIDsCount
,
418 g_browser_process
->local_state()));
422 PrefServiceSyncableFactory
* factory
,
423 policy::PolicyService
* policy_service
,
424 SupervisedUserSettingsService
* supervised_user_settings
,
425 scoped_refptr
<PersistentPrefStore
> user_pref_store
,
426 const scoped_refptr
<PrefStore
>& extension_prefs
,
428 #if defined(ENABLE_CONFIGURATION_POLICY)
429 using policy::ConfigurationPolicyPrefStore
;
430 factory
->set_managed_prefs(
431 make_scoped_refptr(new ConfigurationPolicyPrefStore(
433 g_browser_process
->browser_policy_connector()->GetHandlerList(),
434 policy::POLICY_LEVEL_MANDATORY
)));
435 factory
->set_recommended_prefs(
436 make_scoped_refptr(new ConfigurationPolicyPrefStore(
438 g_browser_process
->browser_policy_connector()->GetHandlerList(),
439 policy::POLICY_LEVEL_RECOMMENDED
)));
440 #endif // ENABLE_CONFIGURATION_POLICY
442 #if defined(ENABLE_SUPERVISED_USERS)
443 if (supervised_user_settings
) {
444 scoped_refptr
<PrefStore
> supervised_user_prefs
= make_scoped_refptr(
445 new SupervisedUserPrefStore(supervised_user_settings
));
446 // TODO(bauerb): Temporary CHECK while investigating
447 // https://crbug.com/425785. Remove when that bug is fixed.
448 CHECK(async
|| supervised_user_prefs
->IsInitializationComplete());
449 factory
->set_supervised_user_prefs(supervised_user_prefs
);
453 factory
->set_async(async
);
454 factory
->set_extension_prefs(extension_prefs
);
455 factory
->set_command_line_prefs(make_scoped_refptr(
456 new CommandLinePrefStore(base::CommandLine::ForCurrentProcess())));
457 factory
->set_read_error_callback(base::Bind(&HandleReadError
));
458 factory
->set_user_prefs(user_pref_store
);
463 namespace chrome_prefs
{
465 namespace internals
{
467 // Group modifications should be reflected in first_run_browsertest.cc and
468 // pref_hash_browsertest.cc.
469 const char kSettingsEnforcementTrialName
[] = "SettingsEnforcement";
470 const char kSettingsEnforcementGroupNoEnforcement
[] = "no_enforcement";
471 const char kSettingsEnforcementGroupEnforceAlways
[] = "enforce_always";
472 const char kSettingsEnforcementGroupEnforceAlwaysWithDSE
[] =
473 "enforce_always_with_dse";
474 const char kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE
[] =
475 "enforce_always_with_extensions_and_dse";
477 } // namespace internals
479 scoped_ptr
<PrefService
> CreateLocalState(
480 const base::FilePath
& pref_filename
,
481 base::SequencedTaskRunner
* pref_io_task_runner
,
482 policy::PolicyService
* policy_service
,
483 const scoped_refptr
<PrefRegistry
>& pref_registry
,
485 PrefServiceSyncableFactory factory
;
489 NULL
, // supervised_user_settings
491 pref_filename
, pref_io_task_runner
, scoped_ptr
<PrefFilter
>()),
492 NULL
, // extension_prefs
494 return factory
.Create(pref_registry
.get());
497 scoped_ptr
<PrefServiceSyncable
> CreateProfilePrefs(
498 const base::FilePath
& profile_path
,
499 base::SequencedTaskRunner
* pref_io_task_runner
,
500 TrackedPreferenceValidationDelegate
* validation_delegate
,
501 policy::PolicyService
* policy_service
,
502 SupervisedUserSettingsService
* supervised_user_settings
,
503 const scoped_refptr
<PrefStore
>& extension_prefs
,
504 const scoped_refptr
<user_prefs::PrefRegistrySyncable
>& pref_registry
,
506 TRACE_EVENT0("browser", "chrome_prefs::CreateProfilePrefs");
507 SCOPED_UMA_HISTOGRAM_TIMER("PrefService.CreateProfilePrefsTime");
509 // A StartSyncFlare used to kick sync early in case of a reset event. This is
510 // done since sync may bring back the user's server value post-reset which
511 // could potentially cause a "settings flash" between the factory default and
512 // the re-instantiated server value. Starting sync ASAP minimizes the window
513 // before the server value is re-instantiated (this window can otherwise be
514 // as long as 10 seconds by default).
515 const base::Closure start_sync_flare_for_prefs
=
516 base::Bind(sync_start_util::GetFlareForSyncableService(profile_path
),
517 syncer::PREFERENCES
);
519 PrefServiceSyncableFactory factory
;
520 scoped_refptr
<PersistentPrefStore
> user_pref_store(
521 CreateProfilePrefStoreManager(profile_path
)
522 ->CreateProfilePrefStore(pref_io_task_runner
,
523 start_sync_flare_for_prefs
,
524 validation_delegate
));
525 PrepareFactory(&factory
,
527 supervised_user_settings
,
531 scoped_ptr
<PrefServiceSyncable
> pref_service
=
532 factory
.CreateSyncable(pref_registry
.get());
534 ConfigureDefaultSearchPrefMigrationToDictionaryValue(pref_service
.get());
536 return pref_service
.Pass();
539 void SchedulePrefsFilePathVerification(const base::FilePath
& profile_path
) {
541 // Only do prefs file verification on Windows.
542 const int kVerifyPrefsFileDelaySeconds
= 60;
543 BrowserThread::GetBlockingPool()->PostDelayedTask(
545 base::Bind(&VerifyPreferencesFile
,
546 ProfilePrefStoreManager::GetPrefFilePathFromProfilePath(
548 base::TimeDelta::FromSeconds(kVerifyPrefsFileDelaySeconds
));
552 void DisableDomainCheckForTesting() {
554 g_disable_domain_check_for_testing
= true;
558 bool InitializePrefsFromMasterPrefs(
559 const base::FilePath
& profile_path
,
560 const base::DictionaryValue
& master_prefs
) {
561 return CreateProfilePrefStoreManager(profile_path
)
562 ->InitializePrefsFromMasterPrefs(master_prefs
);
565 base::Time
GetResetTime(Profile
* profile
) {
566 return ProfilePrefStoreManager::GetResetTime(profile
->GetPrefs());
569 void ClearResetTime(Profile
* profile
) {
570 ProfilePrefStoreManager::ClearResetTime(profile
->GetPrefs());
573 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
) {
574 ProfilePrefStoreManager::RegisterProfilePrefs(registry
);
577 void RegisterPrefs(PrefRegistrySimple
* registry
) {
578 ProfilePrefStoreManager::RegisterPrefs(registry
);
581 } // namespace chrome_prefs