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.
4 
5 #include "chrome/browser/profiles/profile_impl.h"
6 
7 #include <stddef.h>
8 
9 #include <memory>
10 #include <set>
11 #include <utility>
12 #include <vector>
13 
14 #include "base/barrier_closure.h"
15 #include "base/bind.h"
16 #include "base/callback.h"
17 #include "base/callback_helpers.h"
18 #include "base/command_line.h"
19 #include "base/compiler_specific.h"
20 #include "base/environment.h"
21 #include "base/files/file.h"
22 #include "base/files/file_path.h"
23 #include "base/files/file_util.h"
24 #include "base/logging.h"
25 #include "base/memory/ptr_util.h"
26 #include "base/memory/weak_ptr.h"
27 #include "base/no_destructor.h"
28 #include "base/path_service.h"
29 #include "base/sequenced_task_runner.h"
30 #include "base/stl_util.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_util.h"
33 #include "base/strings/stringprintf.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/task/post_task.h"
36 #include "base/task/task_traits.h"
37 #include "base/task/thread_pool.h"
38 #include "base/threading/scoped_blocking_call.h"
39 #include "base/trace_event/trace_event.h"
40 #include "base/version.h"
41 #include "build/build_config.h"
42 #include "chrome/browser/background/background_contents_service_factory.h"
43 #include "chrome/browser/background_fetch/background_fetch_delegate_factory.h"
44 #include "chrome/browser/background_fetch/background_fetch_delegate_impl.h"
45 #include "chrome/browser/background_sync/background_sync_controller_factory.h"
46 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
47 #include "chrome/browser/browser_process.h"
48 #include "chrome/browser/browser_process_platform_part.h"
49 #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
50 #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h"
51 #include "chrome/browser/chrome_notification_types.h"
52 #include "chrome/browser/chromeos/account_manager/account_manager_util.h"
53 #include "chrome/browser/client_hints/client_hints_factory.h"
54 #include "chrome/browser/content_index/content_index_provider_factory.h"
55 #include "chrome/browser/content_index/content_index_provider_impl.h"
56 #include "chrome/browser/content_settings/cookie_settings_factory.h"
57 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
58 #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h"
59 #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h"
60 #include "chrome/browser/dom_distiller/profile_utils.h"
61 #include "chrome/browser/download/chrome_download_manager_delegate.h"
62 #include "chrome/browser/download/download_core_service.h"
63 #include "chrome/browser/download/download_core_service_factory.h"
64 #include "chrome/browser/download/download_manager_utils.h"
65 #include "chrome/browser/federated_learning/floc_id_provider.h"
66 #include "chrome/browser/federated_learning/floc_id_provider_factory.h"
67 #include "chrome/browser/heavy_ad_intervention/heavy_ad_service.h"
68 #include "chrome/browser/heavy_ad_intervention/heavy_ad_service_factory.h"
69 #include "chrome/browser/media/media_device_id_salt.h"
70 #include "chrome/browser/native_file_system/chrome_native_file_system_permission_context.h"
71 #include "chrome/browser/native_file_system/native_file_system_permission_context_factory.h"
72 #include "chrome/browser/permissions/permission_manager_factory.h"
73 #include "chrome/browser/policy/chrome_browser_policy_connector.h"
74 #include "chrome/browser/policy/profile_policy_connector.h"
75 #include "chrome/browser/policy/profile_policy_connector_builder.h"
76 #include "chrome/browser/policy/schema_registry_service.h"
77 #include "chrome/browser/policy/schema_registry_service_builder.h"
78 #include "chrome/browser/prefetch/no_state_prefetch/prerender_manager_factory.h"
79 #include "chrome/browser/prefs/browser_prefs.h"
80 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
81 #include "chrome/browser/prefs/pref_service_syncable_util.h"
82 #include "chrome/browser/prefs/profile_pref_store_manager.h"
83 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
84 #include "chrome/browser/profiles/chrome_version_service.h"
85 #include "chrome/browser/profiles/gaia_info_update_service_factory.h"
86 #include "chrome/browser/profiles/pref_service_builder_utils.h"
87 #include "chrome/browser/profiles/profile_attributes_entry.h"
88 #include "chrome/browser/profiles/profile_attributes_storage.h"
89 #include "chrome/browser/profiles/profile_destroyer.h"
90 #include "chrome/browser/profiles/profile_key.h"
91 #include "chrome/browser/profiles/profile_manager.h"
92 #include "chrome/browser/profiles/profile_metrics.h"
93 #include "chrome/browser/push_messaging/push_messaging_service_factory.h"
94 #include "chrome/browser/push_messaging/push_messaging_service_impl.h"
95 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
96 #include "chrome/browser/sharing/sharing_service_factory.h"
97 #include "chrome/browser/signin/identity_manager_factory.h"
98 #include "chrome/browser/signin/signin_ui_util.h"
99 #include "chrome/browser/ssl/stateful_ssl_host_state_delegate_factory.h"
100 #include "chrome/browser/startup_data.h"
101 #include "chrome/browser/storage/storage_notification_service_factory.h"
102 #include "chrome/browser/transition_manager/full_browser_transition_manager.h"
103 #include "chrome/browser/ui/startup/startup_browser_creator.h"
104 #include "chrome/browser/ui/webui/prefs_internals_source.h"
105 #include "chrome/browser/updates/announcement_notification/announcement_notification_service.h"
106 #include "chrome/browser/updates/announcement_notification/announcement_notification_service_factory.h"
107 #include "chrome/common/buildflags.h"
108 #include "chrome/common/channel_info.h"
109 #include "chrome/common/chrome_constants.h"
110 #include "chrome/common/chrome_paths.h"
111 #include "chrome/common/chrome_paths_internal.h"
112 #include "chrome/common/chrome_switches.h"
113 #include "chrome/common/net/safe_search_util.h"
114 #include "chrome/common/pref_names.h"
115 #include "chrome/common/url_constants.h"
116 #include "chrome/grit/chromium_strings.h"
117 #include "components/background_sync/background_sync_controller_impl.h"
118 #include "components/bookmarks/browser/bookmark_model.h"
119 #include "components/content_settings/core/browser/cookie_settings.h"
120 #include "components/content_settings/core/browser/host_content_settings_map.h"
121 #include "components/content_settings/core/common/pref_names.h"
122 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
123 #include "components/data_reduction_proxy/core/browser/data_store_impl.h"
124 #include "components/history/core/common/pref_names.h"
125 #include "components/keyed_service/content/browser_context_dependency_manager.h"
126 #include "components/keyed_service/core/simple_dependency_manager.h"
127 #include "components/keyed_service/core/simple_key_map.h"
128 #include "components/keyed_service/core/simple_keyed_service_factory.h"
129 #include "components/language/core/browser/pref_names.h"
130 #include "components/language/core/common/locale_util.h"
131 #include "components/metrics/metrics_service.h"
132 #include "components/omnibox/browser/autocomplete_classifier.h"
133 #include "components/permissions/permission_manager.h"
134 #include "components/policy/core/common/cloud/cloud_policy_manager.h"
135 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
136 #include "components/pref_registry/pref_registry_syncable.h"
137 #include "components/prefs/scoped_user_pref_update.h"
138 #include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
139 #include "components/signin/public/base/signin_pref_names.h"
140 #include "components/signin/public/identity_manager/identity_manager.h"
141 #include "components/site_isolation/site_isolation_policy.h"
142 #include "components/sync_preferences/pref_service_syncable.h"
143 #include "components/url_formatter/url_fixer.h"
144 #include "components/user_prefs/user_prefs.h"
145 #include "components/version_info/channel.h"
146 #include "content/public/browser/browser_task_traits.h"
147 #include "content/public/browser/browser_thread.h"
148 #include "content/public/browser/cors_origin_pattern_setter.h"
149 #include "content/public/browser/dom_storage_context.h"
150 #include "content/public/browser/notification_service.h"
151 #include "content/public/browser/permission_controller.h"
152 #include "content/public/browser/permission_type.h"
153 #include "content/public/browser/render_process_host.h"
154 #include "content/public/browser/shared_cors_origin_access_list.h"
155 #include "content/public/browser/storage_partition.h"
156 #include "content/public/browser/url_data_source.h"
157 #include "content/public/common/content_constants.h"
158 #include "extensions/buildflags/buildflags.h"
159 #include "mojo/public/cpp/bindings/pending_remote.h"
160 #include "mojo/public/cpp/bindings/self_owned_receiver.h"
161 #include "ppapi/buildflags/buildflags.h"
162 #include "printing/buildflags/buildflags.h"
163 #include "services/data_decoder/public/cpp/data_decoder.h"
164 #include "services/preferences/public/mojom/preferences.mojom.h"
165 #include "services/preferences/public/mojom/tracked_preference_validation_delegate.mojom.h"
166 #include "services/service_manager/public/cpp/service.h"
167 #include "ui/base/l10n/l10n_util.h"
168 
169 #if defined(OS_CHROMEOS)
170 #include "chrome/browser/app_mode/app_mode_utils.h"
171 #include "chrome/browser/chromeos/app_mode/app_launch_utils.h"
172 #include "chrome/browser/chromeos/arc/session/arc_service_launcher.h"
173 #include "chrome/browser/chromeos/locale_change_guard.h"
174 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
175 #include "chrome/browser/chromeos/policy/active_directory_policy_manager.h"
176 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
177 #include "chrome/browser/chromeos/policy/user_policy_manager_builder_chromeos.h"
178 #include "chrome/browser/chromeos/preferences.h"
179 #include "chrome/browser/chromeos/profiles/profile_helper.h"
180 #include "chrome/browser/chromeos/secure_channel/secure_channel_client_provider.h"
181 #include "chrome/browser/chromeos/settings/device_settings_service.h"
182 #include "chrome/browser/signin/chrome_device_id_helper.h"
183 #include "chromeos/components/account_manager/account_manager.h"
184 #include "chromeos/components/account_manager/account_manager_factory.h"
185 #include "components/session_manager/core/session_manager.h"
186 #include "components/user_manager/user.h"
187 #include "components/user_manager/user_manager.h"
188 #else
189 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_builder.h"
190 #endif
191 
192 #if defined(OS_ANDROID)
193 #include "chrome/browser/android/profile_key_startup_accessor.h"
194 #else
195 #include "components/zoom/zoom_event_manager.h"
196 #include "content/public/common/page_zoom.h"
197 #endif
198 
199 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
200 #include "chrome/browser/background/background_mode_manager.h"
201 #endif
202 
203 #if BUILDFLAG(ENABLE_EXTENSIONS)
204 #include "chrome/browser/extensions/extension_service.h"
205 #include "chrome/browser/extensions/extension_special_storage_policy.h"
206 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
207 #include "components/guest_view/browser/guest_view_manager.h"
208 #include "extensions/browser/extension_pref_store.h"
209 #include "extensions/browser/extension_pref_value_map.h"
210 #include "extensions/browser/extension_pref_value_map_factory.h"
211 #include "extensions/browser/extension_prefs.h"
212 #include "extensions/browser/extension_system.h"
213 #endif
214 
215 #if BUILDFLAG(ENABLE_PLUGINS)
216 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
217 #include "chrome/browser/plugins/plugin_prefs.h"
218 #endif
219 
220 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
221 #include "chrome/browser/sessions/session_service_factory.h"
222 #endif
223 
224 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
225 #include "chrome/browser/content_settings/content_settings_supervised_provider.h"
226 #include "chrome/browser/supervised_user/supervised_user_constants.h"
227 #include "chrome/browser/supervised_user/supervised_user_settings_service.h"
228 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
229 #endif
230 
231 using base::TimeDelta;
232 using bookmarks::BookmarkModel;
233 using content::BrowserThread;
234 using content::CorsOriginPatternSetter;
235 using content::DownloadManagerDelegate;
236 
237 namespace {
238 
239 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
240 // Delay before we explicitly create the SessionService.
241 static constexpr TimeDelta kCreateSessionServiceDelay =
242     TimeDelta::FromMilliseconds(500);
243 #endif
244 
245 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
246 const char kPrefExitTypeCrashed[] = "Crashed";
247 const char kPrefExitTypeSessionEnded[] = "SessionEnded";
248 
249 // Gets the creation time for |path|, returning base::Time::Now() on failure.
GetCreationTimeForPath(const base::FilePath & path)250 base::Time GetCreationTimeForPath(const base::FilePath& path) {
251   base::File::Info info;
252   if (base::GetFileInfo(path, &info))
253     return info.creation_time;
254   return base::Time::Now();
255 }
256 
257 // Creates the profile directory synchronously if it doesn't exist. If
258 // |create_readme| is true, the profile README will be created asynchronously in
259 // the profile directory. Returns the creation time/date of the profile
260 // directory.
CreateProfileDirectory(base::SequencedTaskRunner * io_task_runner,const base::FilePath & path,bool create_readme)261 base::Time CreateProfileDirectory(base::SequencedTaskRunner* io_task_runner,
262                                   const base::FilePath& path,
263                                   bool create_readme) {
264   // Create the profile directory synchronously otherwise we would need to
265   // sequence every otherwise independent I/O operation inside the profile
266   // directory with this operation. base::PathExists() and
267   // base::CreateDirectory() should be lightweight I/O operations and avoiding
268   // the headache of sequencing all otherwise unrelated I/O after these
269   // justifies running them on the main thread.
270   base::ThreadRestrictions::ScopedAllowIO allow_io_to_create_directory;
271 
272   // If the readme exists, the profile directory must also already exist.
273   if (base::PathExists(path.Append(chrome::kReadmeFilename)))
274     return GetCreationTimeForPath(path);
275 
276   DVLOG(1) << "Creating directory " << path.value();
277   if (base::CreateDirectory(path)) {
278     if (create_readme) {
279       base::ThreadPool::PostTask(
280           FROM_HERE,
281           {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
282            base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
283           base::BindOnce(&CreateProfileReadme, path));
284     }
285     return GetCreationTimeForPath(path);
286   }
287   return base::Time::Now();
288 }
289 
290 // Converts the kSessionExitedCleanly pref to the corresponding EXIT_TYPE.
SessionTypePrefValueToExitType(const std::string & value)291 Profile::ExitType SessionTypePrefValueToExitType(const std::string& value) {
292   if (value == kPrefExitTypeSessionEnded)
293     return Profile::EXIT_SESSION_ENDED;
294   if (value == kPrefExitTypeCrashed)
295     return Profile::EXIT_CRASHED;
296   return Profile::EXIT_NORMAL;
297 }
298 
299 // Converts an ExitType into a string that is written to prefs.
ExitTypeToSessionTypePrefValue(Profile::ExitType type)300 std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
301   switch (type) {
302     case Profile::EXIT_NORMAL:
303       return ProfileImpl::kPrefExitTypeNormal;
304     case Profile::EXIT_SESSION_ENDED:
305       return kPrefExitTypeSessionEnded;
306     case Profile::EXIT_CRASHED:
307       return kPrefExitTypeCrashed;
308   }
309   NOTREACHED();
310   return std::string();
311 }
312 
313 #if defined(OS_CHROMEOS)
314 // Checks if |new_locale| is the same as |pref_locale| or |pref_locale| is used
315 // to show UI translation for |new_locale|. (e.g. "it" is used for "it-CH")
LocaleNotChanged(const std::string & pref_locale,const std::string & new_locale)316 bool LocaleNotChanged(const std::string& pref_locale,
317                       const std::string& new_locale) {
318   std::string new_locale_converted = new_locale;
319   language::ConvertToActualUILocale(&new_locale_converted);
320   return pref_locale == new_locale_converted;
321 }
322 #endif  // defined(OS_CHROMEOS)
323 
324 }  // namespace
325 
326 // static
CreateProfile(const base::FilePath & path,Delegate * delegate,CreateMode create_mode)327 std::unique_ptr<Profile> Profile::CreateProfile(const base::FilePath& path,
328                                                 Delegate* delegate,
329                                                 CreateMode create_mode) {
330   TRACE_EVENT1("browser,startup", "Profile::CreateProfile", "profile_path",
331                path.AsUTF8Unsafe());
332 
333   // Get sequenced task runner for making sure that file operations of
334   // this profile are executed in expected order (what was previously assured by
335   // the FILE thread).
336   scoped_refptr<base::SequencedTaskRunner> io_task_runner =
337       base::ThreadPool::CreateSequencedTaskRunner(
338           {base::TaskShutdownBehavior::BLOCK_SHUTDOWN, base::MayBlock()});
339   base::Time creation_time = base::Time::Now();
340   if (create_mode == CREATE_MODE_ASYNCHRONOUS) {
341     DCHECK(delegate);
342     creation_time = CreateProfileDirectory(io_task_runner.get(), path, true);
343   } else if (create_mode == CREATE_MODE_SYNCHRONOUS) {
344     if (base::PathExists(path)) {
345       creation_time = GetCreationTimeForPath(path);
346     } else {
347       // TODO(rogerta): http://crbug/160553 - Bad things happen if we can't
348       // write to the profile directory.  We should eventually be able to run in
349       // this situation.
350       if (!base::CreateDirectory(path))
351         return nullptr;
352 
353       CreateProfileReadme(path);
354     }
355   } else {
356     NOTREACHED();
357   }
358 
359   std::unique_ptr<Profile> profile = base::WrapUnique(new ProfileImpl(
360       path, delegate, create_mode, creation_time, io_task_runner));
361 #if BUILDFLAG(ENABLE_SUPERVISED_USERS) && !defined(OS_ANDROID) && \
362     !defined(OS_CHROMEOS)
363   if (create_mode == CREATE_MODE_SYNCHRONOUS && profile->IsLegacySupervised())
364     return nullptr;
365 #endif
366   return profile;
367 }
368 
369 // static
370 const char ProfileImpl::kPrefExitTypeNormal[] = "Normal";
371 
372 // static
RegisterProfilePrefs(user_prefs::PrefRegistrySyncable * registry)373 void ProfileImpl::RegisterProfilePrefs(
374     user_prefs::PrefRegistrySyncable* registry) {
375   registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, false);
376   registry->RegisterBooleanPref(prefs::kAllowDeletingBrowserHistory, true);
377   registry->RegisterBooleanPref(prefs::kForceGoogleSafeSearch, false);
378   registry->RegisterIntegerPref(prefs::kForceYouTubeRestrict,
379                                 safe_search_util::YOUTUBE_RESTRICT_OFF);
380   registry->RegisterStringPref(prefs::kAllowedDomainsForApps, std::string());
381 
382   registry->RegisterIntegerPref(prefs::kProfileAvatarIndex, -1);
383   // Whether a profile is using an avatar without having explicitely chosen it
384   // (i.e. was assigned by default by legacy profile creation).
385   registry->RegisterBooleanPref(prefs::kProfileUsingDefaultAvatar, true);
386   registry->RegisterBooleanPref(prefs::kProfileUsingGAIAAvatar, false);
387   // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
388   registry->RegisterBooleanPref(prefs::kProfileUsingDefaultName, true);
389   registry->RegisterStringPref(prefs::kProfileName, std::string());
390 
391   registry->RegisterStringPref(prefs::kSupervisedUserId, std::string());
392 #if defined(OS_ANDROID)
393   uint32_t home_page_flags = PrefRegistry::NO_REGISTRATION_FLAGS;
394 #else
395   uint32_t home_page_flags = user_prefs::PrefRegistrySyncable::SYNCABLE_PREF;
396 #endif
397   registry->RegisterStringPref(prefs::kHomePage, std::string(),
398                                home_page_flags);
399   registry->RegisterStringPref(prefs::kNewTabPageLocationOverride,
400                                std::string());
401 
402 #if BUILDFLAG(ENABLE_PRINTING)
403   registry->RegisterBooleanPref(prefs::kPrintingEnabled, true);
404 #endif  // BUILDFLAG(ENABLE_PRINTING)
405   registry->RegisterBooleanPref(prefs::kPrintPreviewDisabled, false);
406   registry->RegisterStringPref(
407       prefs::kPrintPreviewDefaultDestinationSelectionRules, std::string());
408 #if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINTING)
409   registry->RegisterIntegerPref(prefs::kPrintRasterizationMode, 0);
410 #endif
411 
412   registry->RegisterBooleanPref(prefs::kForceEphemeralProfiles, false);
413   registry->RegisterBooleanPref(prefs::kEnableMediaRouter, true);
414 #if defined(OS_CHROMEOS)
415   registry->RegisterBooleanPref(
416       prefs::kOobeMarketingOptInScreenFinished, false,
417       user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
418 #endif  // defined(OS_CHROMEOS)
419 #if !defined(OS_ANDROID)
420   registry->RegisterBooleanPref(prefs::kShowCastIconInToolbar, false);
421 #endif  // !defined(OS_ANDROID)
422   registry->RegisterTimePref(prefs::kProfileCreationTime, base::Time());
423 }
424 
ProfileImpl(const base::FilePath & path,Delegate * delegate,CreateMode create_mode,base::Time path_creation_time,scoped_refptr<base::SequencedTaskRunner> io_task_runner)425 ProfileImpl::ProfileImpl(
426     const base::FilePath& path,
427     Delegate* delegate,
428     CreateMode create_mode,
429     base::Time path_creation_time,
430     scoped_refptr<base::SequencedTaskRunner> io_task_runner)
431     : path_(path),
432       path_creation_time_(path_creation_time),
433       io_task_runner_(std::move(io_task_runner)),
434       io_data_(this),
435       last_session_exit_type_(EXIT_NORMAL),
436       start_time_(base::Time::Now()),
437       delegate_(delegate),
438       shared_cors_origin_access_list_(
439           content::SharedCorsOriginAccessList::Create()) {
440   TRACE_EVENT0("browser,startup", "ProfileImpl::ctor")
441   DCHECK(!path.empty()) << "Using an empty path will attempt to write "
442                         << "profile files to the root directory!";
443 
444 #if defined(OS_CHROMEOS)
445   const bool is_regular_profile =
446       chromeos::ProfileHelper::IsRegularProfile(this);
447 
448   if (is_regular_profile) {
449     const user_manager::User* user =
450         chromeos::ProfileHelper::Get()->GetUserByProfile(this);
451     // A |User| instance should always exist for a profile which is not the
452     // initial, the sign-in or the lock screen app profile.
453     CHECK(user);
454     LOG_IF(FATAL,
455            !session_manager::SessionManager::Get()->HasSessionForAccountId(
456                user->GetAccountId()))
457         << "Attempting to construct the profile before starting the user "
458            "session";
459   }
460 #endif
461 
462 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
463   create_session_service_timer_.Start(
464       FROM_HERE, kCreateSessionServiceDelay, this,
465       &ProfileImpl::EnsureSessionServiceCreated);
466 #endif
467 
468   set_is_guest_profile(path == ProfileManager::GetGuestProfilePath());
469   set_is_system_profile(path == ProfileManager::GetSystemProfilePath());
470 
471   // The ProfileImpl can be created both synchronously and asynchronously.
472   bool async_prefs = create_mode == CREATE_MODE_ASYNCHRONOUS;
473 
474 #if defined(OS_ANDROID)
475   auto* startup_data = g_browser_process->startup_data();
476   DCHECK(startup_data && startup_data->GetProfileKey());
477   TakePrefsFromStartupData();
478   async_prefs = false;
479 #else
480   LoadPrefsForNormalStartup(async_prefs);
481 #endif
482 
483   // Register on BrowserContext.
484   user_prefs::UserPrefs::Set(this, prefs_.get());
485 
486 #if defined(OS_ANDROID)
487   // On Android StartupData creates proto database provider for the profile
488   // before profile is created, so move ownership to storage partition.
489   GetDefaultStoragePartition(this)->SetProtoDatabaseProvider(
490       startup_data->TakeProtoDatabaseProvider());
491 #endif
492 
493   SimpleKeyMap::GetInstance()->Associate(this, key_.get());
494 
495 #if defined(OS_CHROMEOS)
496   if (is_regular_profile) {
497     // |chromeos::InitializeAccountManager| is called during a User's session
498     // initialization but some tests do not properly login to a User Session.
499     // This invocation of |chromeos::InitializeAccountManager| is used only
500     // during tests.
501     // Note: |chromeos::InitializeAccountManager| is idempotent and safe to call
502     // multiple times.
503     // TODO(https://crbug.com/982233): Remove this call.
504     chromeos::InitializeAccountManager(
505         path_, base::DoNothing() /* initialization_callback */);
506 
507     chromeos::AccountManager* account_manager =
508         g_browser_process->platform_part()
509             ->GetAccountManagerFactory()
510             ->GetAccountManager(path_.value());
511     account_manager->SetPrefService(GetPrefs());
512   }
513 #endif
514 
515   if (async_prefs) {
516     // Wait for the notification that prefs has been loaded
517     // (successfully or not).  Note that we can use base::Unretained
518     // because the PrefService is owned by this class and lives on
519     // the same thread.
520     prefs_->AddPrefInitObserver(base::BindOnce(
521         &ProfileImpl::OnPrefsLoaded, base::Unretained(this), create_mode));
522   } else {
523     // Prefs were loaded synchronously so we can continue directly.
524     OnPrefsLoaded(create_mode, true);
525   }
526 }
527 
528 #if defined(OS_ANDROID)
TakePrefsFromStartupData()529 void ProfileImpl::TakePrefsFromStartupData() {
530   auto* startup_data = g_browser_process->startup_data();
531 
532   // On Android, it is possible that the ProfileKey has been build before the
533   // ProfileImpl is created. The ownership of all these pre-created objects
534   // will be taken by ProfileImpl.
535   key_ = startup_data->TakeProfileKey();
536   prefs_ = startup_data->TakeProfilePrefService();
537   schema_registry_service_ = startup_data->TakeSchemaRegistryService();
538   user_cloud_policy_manager_ = startup_data->TakeUserCloudPolicyManager();
539   profile_policy_connector_ = startup_data->TakeProfilePolicyConnector();
540   pref_registry_ = startup_data->TakePrefRegistrySyncable();
541 
542   ProfileKeyStartupAccessor::GetInstance()->Reset();
543 }
544 #endif
545 
LoadPrefsForNormalStartup(bool async_prefs)546 void ProfileImpl::LoadPrefsForNormalStartup(bool async_prefs) {
547   key_ = std::make_unique<ProfileKey>(GetPath());
548   pref_registry_ = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
549 
550   policy::ChromeBrowserPolicyConnector* connector =
551       g_browser_process->browser_policy_connector();
552   schema_registry_service_ = BuildSchemaRegistryServiceForProfile(
553       this, connector->GetChromeSchema(), connector->GetSchemaRegistry());
554 
555   // If we are creating the profile synchronously, then we should load the
556   // policy data immediately.
557   bool force_immediate_policy_load = !async_prefs;
558 
559   policy::UserCloudPolicyManager* user_cloud_policy_manager;
560 #if defined(OS_CHROMEOS)
561   if (force_immediate_policy_load)
562     chromeos::DeviceSettingsService::Get()->LoadImmediately();
563 
564   policy::CreateConfigurationPolicyProvider(
565       this, force_immediate_policy_load, io_task_runner_,
566       &user_cloud_policy_manager_chromeos_, &active_directory_policy_manager_);
567 
568   user_cloud_policy_manager = nullptr;
569 #else
570   user_cloud_policy_manager_ = CreateUserCloudPolicyManager(
571       GetPath(), GetPolicySchemaRegistryService()->registry(),
572       force_immediate_policy_load, io_task_runner_);
573   user_cloud_policy_manager = user_cloud_policy_manager_.get();
574 #endif
575   profile_policy_connector_ =
576       policy::CreateProfilePolicyConnectorForBrowserContext(
577           schema_registry_service_->registry(), user_cloud_policy_manager,
578           g_browser_process->browser_policy_connector(),
579           force_immediate_policy_load, this);
580 
581   bool is_signin_profile = false;
582 #if defined(OS_CHROMEOS)
583   is_signin_profile = chromeos::ProfileHelper::IsSigninProfile(this);
584 #endif
585   ::RegisterProfilePrefs(is_signin_profile,
586                          g_browser_process->GetApplicationLocale(),
587                          pref_registry_.get());
588 
589   mojo::PendingRemote<prefs::mojom::TrackedPreferenceValidationDelegate>
590       pref_validation_delegate;
591   scoped_refptr<safe_browsing::SafeBrowsingService> safe_browsing_service(
592       g_browser_process->safe_browsing_service());
593   if (safe_browsing_service.get()) {
594     auto pref_validation_delegate_impl =
595         safe_browsing_service->CreatePreferenceValidationDelegate(this);
596     if (pref_validation_delegate_impl) {
597       mojo::MakeSelfOwnedReceiver(
598           std::move(pref_validation_delegate_impl),
599           pref_validation_delegate.InitWithNewPipeAndPassReceiver());
600     }
601   }
602 
603   prefs_ =
604       CreatePrefService(pref_registry_, CreateExtensionPrefStore(this, false),
605                         profile_policy_connector_->policy_service(),
606                         g_browser_process->browser_policy_connector(),
607                         std::move(pref_validation_delegate), GetIOTaskRunner(),
608                         key_.get(), path_, async_prefs);
609   key_->SetPrefs(prefs_.get());
610 }
611 
DoFinalInit()612 void ProfileImpl::DoFinalInit() {
613   TRACE_EVENT0("browser", "ProfileImpl::DoFinalInit")
614 
615   PrefService* prefs = GetPrefs();
616 
617   // Do not override the existing pref in case a profile directory is copied, or
618   // if the file system does not support creation time and the property (i.e.
619   // st_ctim in posix which is actually the last status change time when the
620   // inode was last updated) use to mimic it changes because of some other
621   // modification.
622   if (!prefs->HasPrefPath(prefs::kProfileCreationTime))
623     prefs->SetTime(prefs::kProfileCreationTime, path_creation_time_);
624 
625   pref_change_registrar_.Init(prefs);
626   pref_change_registrar_.Add(
627       prefs::kSupervisedUserId,
628       base::Bind(&ProfileImpl::UpdateSupervisedUserIdInStorage,
629                  base::Unretained(this)));
630 
631   // Changes in the profile avatar.
632   pref_change_registrar_.Add(
633       prefs::kProfileAvatarIndex,
634       base::Bind(&ProfileImpl::UpdateAvatarInStorage, base::Unretained(this)));
635   pref_change_registrar_.Add(
636       prefs::kProfileUsingDefaultAvatar,
637       base::Bind(&ProfileImpl::UpdateAvatarInStorage, base::Unretained(this)));
638   pref_change_registrar_.Add(
639       prefs::kProfileUsingGAIAAvatar,
640       base::Bind(&ProfileImpl::UpdateAvatarInStorage, base::Unretained(this)));
641 
642   // Changes in the profile name.
643   pref_change_registrar_.Add(
644       prefs::kProfileUsingDefaultName,
645       base::Bind(&ProfileImpl::UpdateNameInStorage, base::Unretained(this)));
646   pref_change_registrar_.Add(
647       prefs::kProfileName,
648       base::Bind(&ProfileImpl::UpdateNameInStorage, base::Unretained(this)));
649 
650   pref_change_registrar_.Add(
651       prefs::kForceEphemeralProfiles,
652       base::Bind(&ProfileImpl::UpdateIsEphemeralInStorage,
653                  base::Unretained(this)));
654 
655   media_device_id_salt_ = new MediaDeviceIDSalt(prefs_.get());
656 
657   base::FilePath base_cache_path;
658   // It would be nice to use PathService for fetching this directory, but
659   // the cache directory depends on the profile directory, which isn't available
660   // to PathService.
661   chrome::GetUserCacheDirectory(path_, &base_cache_path);
662   // Always create the cache directory asynchronously.
663   CreateProfileDirectory(io_task_runner_.get(), base_cache_path, false);
664 
665   // Initialize components that depend on the current value.
666   UpdateSupervisedUserIdInStorage();
667   UpdateIsEphemeralInStorage();
668   GAIAInfoUpdateServiceFactory::GetForProfile(this);
669 
670 #if BUILDFLAG(ENABLE_BACKGROUND_MODE)
671   // Initialize the BackgroundModeManager - this has to be done here before
672   // InitExtensions() is called because it relies on receiving notifications
673   // when extensions are loaded. BackgroundModeManager is not needed under
674   // ChromeOS because Chrome is always running, no need for special keep-alive
675   // or launch-on-startup support unless kKeepAliveForTest is set.
676   bool init_background_mode_manager = true;
677 #if defined(OS_CHROMEOS)
678   if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
679           switches::kKeepAliveForTest))
680     init_background_mode_manager = false;
681 #endif
682   if (init_background_mode_manager) {
683     if (g_browser_process->background_mode_manager())
684       g_browser_process->background_mode_manager()->RegisterProfile(this);
685   }
686 #endif  // BUILDFLAG(ENABLE_BACKGROUND_MODE)
687 
688 #if BUILDFLAG(ENABLE_PLUGINS)
689   ChromePluginServiceFilter::GetInstance()->RegisterProfile(this);
690 #endif
691 
692   auto* db_provider =
693       GetDefaultStoragePartition(this)->GetProtoDatabaseProvider();
694   key_->SetProtoDatabaseProvider(db_provider);
695 
696   // The DomDistillerViewerSource is not a normal WebUI so it must be registered
697   // as a URLDataSource early.
698   dom_distiller::RegisterViewerSource(this);
699 
700 #if defined(OS_CHROMEOS)
701   MigrateSigninScopedDeviceId(this);
702 
703   if (chromeos::UserSessionManager::GetInstance()
704           ->RestartToApplyPerSessionFlagsIfNeed(this, true)) {
705     return;
706   }
707 #endif
708 
709 #if !defined(OS_CHROMEOS)
710   // Listen for bookmark model load, to bootstrap the sync service.
711   // On CrOS sync service will be initialized after sign in.
712   BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(this);
713   model->AddObserver(new BookmarkModelLoadedObserver(this));
714 #endif
715 
716   HeavyAdServiceFactory::GetForBrowserContext(this)->Initialize(GetPath());
717 
718   PushMessagingServiceImpl::InitializeForProfile(this);
719 
720 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
721   signin_ui_util::InitializePrefsForProfile(this);
722 #endif
723 
724   site_isolation::SiteIsolationPolicy::ApplyPersistedIsolatedOrigins(this);
725 
726   InitializeDataReductionProxy();
727 
728   content::URLDataSource::Add(this,
729                               std::make_unique<PrefsInternalsSource>(this));
730 
731   if (delegate_) {
732     TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated");
733     // Fails if the browser is shutting down. This is done to avoid
734     // launching new UI, finalising profile creation, etc. which
735     // would trigger a crash down the line. See ...
736     const bool shutting_down = g_browser_process->IsShuttingDown();
737     delegate_->OnProfileCreated(this, !shutting_down, IsNewProfile());
738     // The current Profile may be immediately deleted as part of
739     // the call to OnProfileCreated(...) if the initialisation is
740     // reported as a failure, thus no code should be executed past
741     // that point.
742     if (shutting_down)
743       return;
744   }
745   // Ensure that the SharingService is initialized now that io_data_ is
746   // initialized. https://crbug.com/171406
747   SharingServiceFactory::GetForBrowserContext(this);
748 
749   // The creation of FlocIdProvider should align with the start of a browser
750   // profile session, so initialize it here.
751   federated_learning::FlocIdProviderFactory::GetForProfile(this);
752 
753   content::NotificationService::current()->Notify(
754       chrome::NOTIFICATION_PROFILE_CREATED, content::Source<Profile>(this),
755       content::NotificationService::NoDetails());
756 
757   AnnouncementNotificationServiceFactory::GetForProfile(this)
758       ->MaybeShowNotification();
759 }
760 
last_selected_directory()761 base::FilePath ProfileImpl::last_selected_directory() {
762   return GetPrefs()->GetFilePath(prefs::kSelectFileLastDirectory);
763 }
764 
set_last_selected_directory(const base::FilePath & path)765 void ProfileImpl::set_last_selected_directory(const base::FilePath& path) {
766   GetPrefs()->SetFilePath(prefs::kSelectFileLastDirectory, path);
767 }
768 
~ProfileImpl()769 ProfileImpl::~ProfileImpl() {
770   MaybeSendDestroyedNotification();
771 
772   bool prefs_loaded = prefs_->GetInitializationStatus() !=
773                       PrefService::INITIALIZATION_STATUS_WAITING;
774 
775 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
776   StopCreateSessionServiceTimer();
777 #endif
778 
779   // Remove pref observers
780   pref_change_registrar_.RemoveAll();
781 
782 #if BUILDFLAG(ENABLE_PLUGINS)
783   ChromePluginServiceFilter::GetInstance()->UnregisterProfile(this);
784 #endif
785 
786   // Destroy all OTR profiles and their profile services first.
787   std::vector<Profile*> raw_otr_profiles;
788   bool primary_otr_available = false;
789 
790   // Get a list of existing OTR profiles since |off_the_record_profile_| might
791   // be modified after the call to |DestroyProfileNow|.
792   for (auto& otr_profile : otr_profiles_) {
793     raw_otr_profiles.push_back(otr_profile.second.get());
794     primary_otr_available |= (otr_profile.first == OTRProfileID::PrimaryID());
795   }
796 
797   for (Profile* otr_profile : raw_otr_profiles)
798     ProfileDestroyer::DestroyOffTheRecordProfileNow(otr_profile);
799 
800 #if BUILDFLAG(ENABLE_EXTENSIONS)
801   if (!primary_otr_available) {
802     ExtensionPrefValueMapFactory::GetForBrowserContext(this)
803         ->ClearAllIncognitoSessionOnlyPreferences();
804   }
805 #endif
806 
807   FullBrowserTransitionManager::Get()->OnProfileDestroyed(this);
808 
809   // The SimpleDependencyManager should always be passed after the
810   // BrowserContextDependencyManager. This is because the KeyedService instances
811   // in the BrowserContextDependencyManager's dependency graph can depend on the
812   // ones in the SimpleDependencyManager's graph.
813   DependencyManager::PerformInterlockedTwoPhaseShutdown(
814       BrowserContextDependencyManager::GetInstance(), this,
815       SimpleDependencyManager::GetInstance(), key_.get());
816 
817   SimpleKeyMap::GetInstance()->Dissociate(this);
818 
819   profile_policy_connector_->Shutdown();
820   if (configuration_policy_provider())
821     configuration_policy_provider()->Shutdown();
822 
823   // This causes the Preferences file to be written to disk.
824   if (prefs_loaded)
825     SetExitType(EXIT_NORMAL);
826 
827   // This must be called before ProfileIOData::ShutdownOnUIThread but after
828   // other profile-related destroy notifications are dispatched.
829   ShutdownStoragePartitions();
830 }
831 
GetProfileUserName() const832 std::string ProfileImpl::GetProfileUserName() const {
833   const signin::IdentityManager* identity_manager =
834       IdentityManagerFactory::GetForProfileIfExists(this);
835   if (identity_manager)
836     return identity_manager->GetPrimaryAccountInfo().email;
837 
838   return std::string();
839 }
840 
841 #if !defined(OS_ANDROID)
842 std::unique_ptr<content::ZoomLevelDelegate>
CreateZoomLevelDelegate(const base::FilePath & partition_path)843 ProfileImpl::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
844   return std::make_unique<ChromeZoomLevelPrefs>(
845       GetPrefs(), GetPath(), partition_path,
846       zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr());
847 }
848 #endif  // !defined(OS_ANDROID)
849 
GetPath()850 base::FilePath ProfileImpl::GetPath() {
851   return path_;
852 }
853 
GetPath() const854 base::FilePath ProfileImpl::GetPath() const {
855   return path_;
856 }
857 
GetCreationTime() const858 base::Time ProfileImpl::GetCreationTime() const {
859   return prefs_->GetTime(prefs::kProfileCreationTime);
860 }
861 
GetIOTaskRunner()862 scoped_refptr<base::SequencedTaskRunner> ProfileImpl::GetIOTaskRunner() {
863   return io_task_runner_;
864 }
865 
IsOffTheRecord()866 bool ProfileImpl::IsOffTheRecord() {
867   return false;
868 }
869 
IsOffTheRecord() const870 bool ProfileImpl::IsOffTheRecord() const {
871   return false;
872 }
873 
GetOTRProfileID() const874 const Profile::OTRProfileID& ProfileImpl::GetOTRProfileID() const {
875   NOTREACHED();
876   static base::NoDestructor<OTRProfileID> otr_profile_id(
877       "ProfileImp::NoOTRProfileID");
878   return *otr_profile_id;
879 }
880 
GetOffTheRecordProfile(const OTRProfileID & otr_profile_id)881 Profile* ProfileImpl::GetOffTheRecordProfile(
882     const OTRProfileID& otr_profile_id) {
883   if (HasOffTheRecordProfile(otr_profile_id))
884     return otr_profiles_[otr_profile_id].get();
885 
886   // Create a new OffTheRecordProfile
887   std::unique_ptr<Profile> otr_profile =
888       Profile::CreateOffTheRecordProfile(this, otr_profile_id);
889   Profile* raw_otr_profile = otr_profile.get();
890 
891   otr_profiles_[otr_profile_id] = std::move(otr_profile);
892 
893   NotifyOffTheRecordProfileCreated(raw_otr_profile);
894 
895   content::NotificationService::current()->Notify(
896       chrome::NOTIFICATION_PROFILE_CREATED,
897       content::Source<Profile>(raw_otr_profile),
898       content::NotificationService::NoDetails());
899 
900   return raw_otr_profile;
901 }
902 
GetAllOffTheRecordProfiles()903 std::vector<Profile*> ProfileImpl::GetAllOffTheRecordProfiles() {
904   std::vector<Profile*> raw_otr_profiles;
905   for (auto& otr : otr_profiles_)
906     raw_otr_profiles.push_back(otr.second.get());
907   return raw_otr_profiles;
908 }
909 
DestroyOffTheRecordProfile(Profile * otr_profile)910 void ProfileImpl::DestroyOffTheRecordProfile(Profile* otr_profile) {
911   CHECK(otr_profile);
912   OTRProfileID profile_id = otr_profile->GetOTRProfileID();
913   DCHECK(HasOffTheRecordProfile(profile_id));
914   otr_profiles_.erase(profile_id);
915 #if BUILDFLAG(ENABLE_EXTENSIONS)
916   // Extensions are only supported on primary OTR profile.
917   if (profile_id == OTRProfileID::PrimaryID()) {
918     ExtensionPrefValueMapFactory::GetForBrowserContext(this)
919         ->ClearAllIncognitoSessionOnlyPreferences();
920   }
921 #endif
922 }
923 
HasOffTheRecordProfile(const OTRProfileID & otr_profile_id)924 bool ProfileImpl::HasOffTheRecordProfile(const OTRProfileID& otr_profile_id) {
925   return base::Contains(otr_profiles_, otr_profile_id);
926 }
927 
HasAnyOffTheRecordProfile()928 bool ProfileImpl::HasAnyOffTheRecordProfile() {
929   return !otr_profiles_.empty();
930 }
931 
GetOriginalProfile()932 Profile* ProfileImpl::GetOriginalProfile() {
933   return this;
934 }
935 
GetOriginalProfile() const936 const Profile* ProfileImpl::GetOriginalProfile() const {
937   return this;
938 }
939 
IsSupervised() const940 bool ProfileImpl::IsSupervised() const {
941   return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
942 }
943 
IsChild() const944 bool ProfileImpl::IsChild() const {
945 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
946   return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
947          supervised_users::kChildAccountSUID;
948 #else
949   return false;
950 #endif
951 }
952 
IsLegacySupervised() const953 bool ProfileImpl::IsLegacySupervised() const {
954   return IsSupervised() && !IsChild();
955 }
956 
AllowsBrowserWindows() const957 bool ProfileImpl::AllowsBrowserWindows() const {
958 #if defined(OS_CHROMEOS)
959   if (chromeos::ProfileHelper::IsSigninProfile(this) ||
960       chromeos::ProfileHelper::IsLockScreenAppProfile(this)) {
961     return false;
962   }
963 #endif
964   return !IsSystemProfile();
965 }
966 
GetExtensionSpecialStoragePolicy()967 ExtensionSpecialStoragePolicy* ProfileImpl::GetExtensionSpecialStoragePolicy() {
968 #if BUILDFLAG(ENABLE_EXTENSIONS)
969   if (!extension_special_storage_policy_.get()) {
970     TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
971     extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
972         CookieSettingsFactory::GetForProfile(this).get());
973   }
974   return extension_special_storage_policy_.get();
975 #else
976   return NULL;
977 #endif
978 }
979 
OnLocaleReady()980 void ProfileImpl::OnLocaleReady() {
981   TRACE_EVENT0("browser", "ProfileImpl::OnLocaleReady");
982 
983   // Migrate obsolete prefs.
984   MigrateObsoleteProfilePrefs(this);
985 #if BUILDFLAG(ENABLE_EXTENSIONS)
986   // Note: Extension preferences can be keyed off the extension ID, so need to
987   // be handled specially (rather than directly as part of
988   // MigrateObsoleteProfilePrefs()).
989   extensions::ExtensionPrefs::Get(this)->MigrateObsoleteExtensionPrefs();
990 #endif
991 
992 #if defined(OS_CHROMEOS)
993   // If this is a kiosk profile, reset some of its prefs which should not
994   // persist between sessions.
995   if (chrome::IsRunningInForcedAppMode()) {
996     chromeos::ResetEphemeralKioskPreferences(prefs_.get());
997   }
998 #endif
999 
1000   // |kSessionExitType| was added after |kSessionExitedCleanly|. If the pref
1001   // value is empty fallback to checking for |kSessionExitedCleanly|.
1002   const std::string exit_type_pref_value(
1003       prefs_->GetString(prefs::kSessionExitType));
1004   if (exit_type_pref_value.empty()) {
1005     last_session_exit_type_ = prefs_->GetBoolean(prefs::kSessionExitedCleanly)
1006                                   ? EXIT_NORMAL
1007                                   : EXIT_CRASHED;
1008   } else {
1009     last_session_exit_type_ =
1010         SessionTypePrefValueToExitType(exit_type_pref_value);
1011   }
1012   // Mark the session as open.
1013   prefs_->SetString(prefs::kSessionExitType, kPrefExitTypeCrashed);
1014   // Force this to true in case we fallback and use it.
1015   // TODO(sky): remove this in a couple of releases (m28ish).
1016   prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
1017 
1018   g_browser_process->profile_manager()->InitProfileUserPrefs(this);
1019 
1020 #if defined(OS_CHROMEOS)
1021   arc::ArcServiceLauncher::Get()->MaybeSetProfile(this);
1022 #endif
1023 
1024   FullBrowserTransitionManager::Get()->OnProfileCreated(this);
1025 
1026   BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
1027       this);
1028 
1029   ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
1030   DoFinalInit();
1031 }
1032 
OnPrefsLoaded(CreateMode create_mode,bool success)1033 void ProfileImpl::OnPrefsLoaded(CreateMode create_mode, bool success) {
1034   TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded");
1035   if (!success) {
1036     if (delegate_)
1037       delegate_->OnProfileCreated(this, false, false);
1038     return;
1039   }
1040 
1041   // Fail fast if the browser is shutting down. We want to avoid launching new
1042   // UI, finalising profile creation, etc. which would trigger a crash down the
1043   // the line. See crbug.com/625646
1044   if (g_browser_process->IsShuttingDown()) {
1045     if (delegate_)
1046       delegate_->OnProfileCreated(this, false, false);
1047     return;
1048   }
1049 
1050 #if defined(OS_CHROMEOS)
1051   if (create_mode == CREATE_MODE_SYNCHRONOUS) {
1052     // Synchronous create mode implies that either it is restart after crash,
1053     // or we are in tests. In both cases the first loaded locale is correct.
1054     OnLocaleReady();
1055   } else {
1056     chromeos::UserSessionManager::GetInstance()->RespectLocalePreferenceWrapper(
1057         this, base::Bind(&ProfileImpl::OnLocaleReady, base::Unretained(this)));
1058   }
1059 #else
1060   OnLocaleReady();
1061 #endif
1062 }
1063 
WasCreatedByVersionOrLater(const std::string & version)1064 bool ProfileImpl::WasCreatedByVersionOrLater(const std::string& version) {
1065   base::Version profile_version(ChromeVersionService::GetVersion(prefs_.get()));
1066   base::Version arg_version(version);
1067   return (profile_version.CompareTo(arg_version) >= 0);
1068 }
1069 
SetExitType(ExitType exit_type)1070 void ProfileImpl::SetExitType(ExitType exit_type) {
1071 #if defined(OS_CHROMEOS)
1072   if (chromeos::ProfileHelper::IsSigninProfile(this))
1073     return;
1074 #endif
1075   if (!prefs_)
1076     return;
1077   ExitType current_exit_type = SessionTypePrefValueToExitType(
1078       prefs_->GetString(prefs::kSessionExitType));
1079   // This may be invoked multiple times during shutdown. Only persist the value
1080   // first passed in (unless it's a reset to the crash state, which happens when
1081   // foregrounding the app on mobile).
1082   if (exit_type == EXIT_CRASHED || current_exit_type == EXIT_CRASHED) {
1083     prefs_->SetString(prefs::kSessionExitType,
1084                       ExitTypeToSessionTypePrefValue(exit_type));
1085   }
1086 }
1087 
GetLastSessionExitType() const1088 Profile::ExitType ProfileImpl::GetLastSessionExitType() const {
1089   // last_session_exited_cleanly_ is set when the preferences are loaded. Force
1090   // it to be set by asking for the prefs.
1091   GetPrefs();
1092   return last_session_exit_type_;
1093 }
1094 
ShouldRestoreOldSessionCookies() const1095 bool ProfileImpl::ShouldRestoreOldSessionCookies() const {
1096 #if defined(OS_ANDROID)
1097   SessionStartupPref::Type startup_pref_type =
1098       SessionStartupPref::GetDefaultStartupType();
1099 #else
1100   SessionStartupPref::Type startup_pref_type =
1101       StartupBrowserCreator::GetSessionStartupPref(
1102           *base::CommandLine::ForCurrentProcess(), this)
1103           .type;
1104 #endif
1105   return GetLastSessionExitType() == Profile::EXIT_CRASHED ||
1106          startup_pref_type == SessionStartupPref::LAST;
1107 }
1108 
ShouldPersistSessionCookies() const1109 bool ProfileImpl::ShouldPersistSessionCookies() const {
1110   return true;
1111 }
1112 
GetPrefs()1113 PrefService* ProfileImpl::GetPrefs() {
1114   return const_cast<PrefService*>(
1115       static_cast<const ProfileImpl*>(this)->GetPrefs());
1116 }
1117 
GetPrefs() const1118 const PrefService* ProfileImpl::GetPrefs() const {
1119   DCHECK(prefs_);  // Should explicitly be initialized.
1120   return prefs_.get();
1121 }
1122 
1123 #if !defined(OS_ANDROID)
GetZoomLevelPrefs()1124 ChromeZoomLevelPrefs* ProfileImpl::GetZoomLevelPrefs() {
1125   return static_cast<ChromeZoomLevelPrefs*>(
1126       GetDefaultStoragePartition(this)->GetZoomLevelDelegate());
1127 }
1128 #endif  // !defined(OS_ANDROID)
1129 
GetOffTheRecordPrefs()1130 PrefService* ProfileImpl::GetOffTheRecordPrefs() {
1131   if (HasPrimaryOTRProfile()) {
1132     return GetPrimaryOTRProfile()->GetPrefs();
1133   } else {
1134     // The extensions preference API and many tests call this method even when
1135     // there's no OTR profile, in order to figure out what a pref value would
1136     // have been returned if an OTR profile existed. To support that case we
1137     // return a dummy PrefService here.
1138     //
1139     // TODO(crbug.com/734484): Don't call this method when there's no OTR
1140     // profile (and return null for such calls).
1141     return GetReadOnlyOffTheRecordPrefs();
1142   }
1143 }
1144 
GetReadOnlyOffTheRecordPrefs()1145 PrefService* ProfileImpl::GetReadOnlyOffTheRecordPrefs() {
1146   if (!dummy_otr_prefs_) {
1147     dummy_otr_prefs_ = CreateIncognitoPrefServiceSyncable(
1148         prefs_.get(), CreateExtensionPrefStore(this, true));
1149   }
1150   return dummy_otr_prefs_.get();
1151 }
1152 
GetPolicySchemaRegistryService()1153 policy::SchemaRegistryService* ProfileImpl::GetPolicySchemaRegistryService() {
1154   return schema_registry_service_.get();
1155 }
1156 
1157 #if defined(OS_CHROMEOS)
1158 policy::UserCloudPolicyManagerChromeOS*
GetUserCloudPolicyManagerChromeOS()1159 ProfileImpl::GetUserCloudPolicyManagerChromeOS() {
1160   return user_cloud_policy_manager_chromeos_.get();
1161 }
1162 
1163 policy::ActiveDirectoryPolicyManager*
GetActiveDirectoryPolicyManager()1164 ProfileImpl::GetActiveDirectoryPolicyManager() {
1165   return active_directory_policy_manager_.get();
1166 }
1167 #else
GetUserCloudPolicyManager()1168 policy::UserCloudPolicyManager* ProfileImpl::GetUserCloudPolicyManager() {
1169   return user_cloud_policy_manager_.get();
1170 }
1171 #endif  // defined(OS_CHROMEOS)
1172 
1173 policy::ConfigurationPolicyProvider*
configuration_policy_provider()1174 ProfileImpl::configuration_policy_provider() {
1175 #if defined(OS_CHROMEOS)
1176   if (user_cloud_policy_manager_chromeos_)
1177     return user_cloud_policy_manager_chromeos_.get();
1178   if (active_directory_policy_manager_)
1179     return active_directory_policy_manager_.get();
1180   return nullptr;
1181 #else
1182   return user_cloud_policy_manager_.get();
1183 #endif
1184 }
1185 
GetProfilePolicyConnector()1186 policy::ProfilePolicyConnector* ProfileImpl::GetProfilePolicyConnector() {
1187   return profile_policy_connector_.get();
1188 }
1189 
GetProfilePolicyConnector() const1190 const policy::ProfilePolicyConnector* ProfileImpl::GetProfilePolicyConnector()
1191     const {
1192   return profile_policy_connector_.get();
1193 }
1194 
GetResourceContext()1195 content::ResourceContext* ProfileImpl::GetResourceContext() {
1196   return io_data_.GetResourceContext();
1197 }
1198 
1199 scoped_refptr<network::SharedURLLoaderFactory>
GetURLLoaderFactory()1200 ProfileImpl::GetURLLoaderFactory() {
1201   return GetDefaultStoragePartition(this)
1202       ->GetURLLoaderFactoryForBrowserProcess();
1203 }
1204 
GetGuestManager()1205 content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
1206 #if BUILDFLAG(ENABLE_EXTENSIONS)
1207   return guest_view::GuestViewManager::FromBrowserContext(this);
1208 #else
1209   return NULL;
1210 #endif
1211 }
1212 
GetDownloadManagerDelegate()1213 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
1214   return DownloadCoreServiceFactory::GetForBrowserContext(this)
1215       ->GetDownloadManagerDelegate();
1216 }
1217 
GetSpecialStoragePolicy()1218 storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
1219 #if BUILDFLAG(ENABLE_EXTENSIONS)
1220   return GetExtensionSpecialStoragePolicy();
1221 #else
1222   return NULL;
1223 #endif
1224 }
1225 
GetPushMessagingService()1226 content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
1227   return PushMessagingServiceFactory::GetForProfile(this);
1228 }
1229 
1230 content::StorageNotificationService*
GetStorageNotificationService()1231 ProfileImpl::GetStorageNotificationService() {
1232 #if defined(OS_ANDROID)
1233   return nullptr;
1234 #else
1235   return StorageNotificationServiceFactory::GetForBrowserContext(this);
1236 #endif
1237 }
1238 
GetSSLHostStateDelegate()1239 content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
1240   return StatefulSSLHostStateDelegateFactory::GetForProfile(this);
1241 }
1242 
1243 content::BrowsingDataRemoverDelegate*
GetBrowsingDataRemoverDelegate()1244 ProfileImpl::GetBrowsingDataRemoverDelegate() {
1245   return ChromeBrowsingDataRemoverDelegateFactory::GetForProfile(this);
1246 }
1247 
1248 // TODO(mlamouri): we should all these BrowserContext implementation to Profile
1249 // instead of repeating them inside all Profile implementations.
1250 content::PermissionControllerDelegate*
GetPermissionControllerDelegate()1251 ProfileImpl::GetPermissionControllerDelegate() {
1252   return PermissionManagerFactory::GetForProfile(this);
1253 }
1254 
1255 content::ClientHintsControllerDelegate*
GetClientHintsControllerDelegate()1256 ProfileImpl::GetClientHintsControllerDelegate() {
1257   return ClientHintsFactory::GetForBrowserContext(this);
1258 }
1259 
GetBackgroundFetchDelegate()1260 content::BackgroundFetchDelegate* ProfileImpl::GetBackgroundFetchDelegate() {
1261   return BackgroundFetchDelegateFactory::GetForProfile(this);
1262 }
1263 
GetBackgroundSyncController()1264 content::BackgroundSyncController* ProfileImpl::GetBackgroundSyncController() {
1265   return BackgroundSyncControllerFactory::GetForProfile(this);
1266 }
1267 
GetContentIndexProvider()1268 content::ContentIndexProvider* ProfileImpl::GetContentIndexProvider() {
1269   return ContentIndexProviderFactory::GetForProfile(this);
1270 }
1271 
SetCorsOriginAccessListForOrigin(const url::Origin & source_origin,std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,base::OnceClosure closure)1272 void ProfileImpl::SetCorsOriginAccessListForOrigin(
1273     const url::Origin& source_origin,
1274     std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,
1275     std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,
1276     base::OnceClosure closure) {
1277   auto barrier_closure = BarrierClosure(3, std::move(closure));
1278 
1279   // Keep profile storage partitions' NetworkContexts synchronized.
1280   auto profile_setter = base::MakeRefCounted<CorsOriginPatternSetter>(
1281       source_origin, CorsOriginPatternSetter::ClonePatterns(allow_patterns),
1282       CorsOriginPatternSetter::ClonePatterns(block_patterns), barrier_closure);
1283   ForEachStoragePartition(
1284       this, base::BindRepeating(&CorsOriginPatternSetter::SetLists,
1285                                 base::RetainedRef(profile_setter.get())));
1286 
1287   // Keep incognito storage partitions' NetworkContexts synchronized.
1288   if (HasPrimaryOTRProfile()) {
1289     auto off_the_record_setter = base::MakeRefCounted<CorsOriginPatternSetter>(
1290         source_origin, CorsOriginPatternSetter::ClonePatterns(allow_patterns),
1291         CorsOriginPatternSetter::ClonePatterns(block_patterns),
1292         barrier_closure);
1293     ForEachStoragePartition(
1294         GetPrimaryOTRProfile(),
1295         base::BindRepeating(&CorsOriginPatternSetter::SetLists,
1296                             base::RetainedRef(off_the_record_setter.get())));
1297   } else {
1298     // Release unused closure reference.
1299     barrier_closure.Run();
1300   }
1301 
1302   // Keep the per-profile access list up to date so that we can use this to
1303   // restore NetworkContext settings at anytime, e.g. on restarting the
1304   // network service.
1305   shared_cors_origin_access_list_->SetForOrigin(
1306       source_origin, std::move(allow_patterns), std::move(block_patterns),
1307       barrier_closure);
1308 }
1309 
1310 content::SharedCorsOriginAccessList*
GetSharedCorsOriginAccessList()1311 ProfileImpl::GetSharedCorsOriginAccessList() {
1312   return shared_cors_origin_access_list_.get();
1313 }
1314 
GetMediaDeviceIDSalt()1315 std::string ProfileImpl::GetMediaDeviceIDSalt() {
1316   return media_device_id_salt_->GetSalt();
1317 }
1318 
1319 download::InProgressDownloadManager*
RetriveInProgressDownloadManager()1320 ProfileImpl::RetriveInProgressDownloadManager() {
1321   return DownloadManagerUtils::RetrieveInProgressDownloadManager(this);
1322 }
1323 
1324 content::NativeFileSystemPermissionContext*
GetNativeFileSystemPermissionContext()1325 ProfileImpl::GetNativeFileSystemPermissionContext() {
1326   return NativeFileSystemPermissionContextFactory::GetForProfile(this);
1327 }
1328 
IsSameOrParent(Profile * profile)1329 bool ProfileImpl::IsSameOrParent(Profile* profile) {
1330   return profile && profile->GetOriginalProfile() == this;
1331 }
1332 
GetStartTime() const1333 base::Time ProfileImpl::GetStartTime() const {
1334   return start_time_;
1335 }
1336 
GetProfileKey() const1337 ProfileKey* ProfileImpl::GetProfileKey() const {
1338   DCHECK(key_);
1339   return key_.get();
1340 }
1341 
1342 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
StopCreateSessionServiceTimer()1343 void ProfileImpl::StopCreateSessionServiceTimer() {
1344   create_session_service_timer_.Stop();
1345 }
1346 
EnsureSessionServiceCreated()1347 void ProfileImpl::EnsureSessionServiceCreated() {
1348   SessionServiceFactory::GetForProfile(this);
1349 }
1350 #endif
1351 
1352 #if defined(OS_CHROMEOS)
ChangeAppLocale(const std::string & new_locale,AppLocaleChangedVia via)1353 void ProfileImpl::ChangeAppLocale(const std::string& new_locale,
1354                                   AppLocaleChangedVia via) {
1355   if (new_locale.empty()) {
1356     NOTREACHED();
1357     return;
1358   }
1359   PrefService* local_state = g_browser_process->local_state();
1360   DCHECK(local_state);
1361   if (local_state->IsManagedPreference(language::prefs::kApplicationLocale))
1362     return;
1363   std::string pref_locale =
1364       GetPrefs()->GetString(language::prefs::kApplicationLocale);
1365   language::ConvertToActualUILocale(&pref_locale);
1366   bool do_update_pref = true;
1367   switch (via) {
1368     case APP_LOCALE_CHANGED_VIA_SETTINGS:
1369     case APP_LOCALE_CHANGED_VIA_REVERT: {
1370       // We keep kApplicationLocaleBackup value as a reference.  In case value
1371       // of kApplicationLocale preference would change due to sync from other
1372       // device then kApplicationLocaleBackup value will trigger and allow us to
1373       // show notification about automatic locale change in LocaleChangeGuard.
1374       GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1375       GetPrefs()->ClearPref(prefs::kApplicationLocaleAccepted);
1376       // We maintain kApplicationLocale property in both a global storage
1377       // and user's profile.  Global property determines locale of login screen,
1378       // while user's profile determines their personal locale preference.
1379       break;
1380     }
1381     case APP_LOCALE_CHANGED_VIA_LOGIN:
1382     case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
1383       if (!pref_locale.empty()) {
1384         DCHECK(LocaleNotChanged(pref_locale, new_locale));
1385 
1386         if (!locale_change_guard_) {
1387           locale_change_guard_ =
1388               std::make_unique<chromeos::LocaleChangeGuard>(this);
1389         }
1390         locale_change_guard_->set_locale_changed_during_login(true);
1391 
1392         std::string accepted_locale =
1393             GetPrefs()->GetString(prefs::kApplicationLocaleAccepted);
1394         if (accepted_locale == new_locale) {
1395           // If locale is accepted then we do not want to show LocaleChange
1396           // notification.  This notification is triggered by different values
1397           // of kApplicationLocaleBackup and kApplicationLocale preferences,
1398           // so make them identical.
1399           GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1400         } else {
1401           // Back up locale of login screen.
1402           std::string cur_locale = g_browser_process->GetApplicationLocale();
1403           GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1404           locale_change_guard_->PrepareChangingLocale(cur_locale, new_locale);
1405         }
1406       } else {
1407         std::string cur_locale = g_browser_process->GetApplicationLocale();
1408         std::string backup_locale =
1409             GetPrefs()->GetString(prefs::kApplicationLocaleBackup);
1410         // Profile synchronization takes time and is not completed at that
1411         // moment at first login.  So we initialize locale preference in steps:
1412         // (1) first save it to temporary backup;
1413         // (2) on next login we assume that synchronization is already completed
1414         //     and we may finalize initialization.
1415         GetPrefs()->SetString(prefs::kApplicationLocaleBackup, cur_locale);
1416         if (!new_locale.empty())
1417           GetPrefs()->SetString(language::prefs::kApplicationLocale,
1418                                 new_locale);
1419         else if (!backup_locale.empty())
1420           GetPrefs()->SetString(language::prefs::kApplicationLocale,
1421                                 backup_locale);
1422         do_update_pref = false;
1423       }
1424       break;
1425     }
1426     case APP_LOCALE_CHANGED_VIA_POLICY: {
1427       // If the locale change has been triggered by policy, the original locale
1428       // is not allowed and can't be switched back to.
1429       GetPrefs()->SetString(prefs::kApplicationLocaleBackup, new_locale);
1430       break;
1431     }
1432     case APP_LOCALE_CHANGED_VIA_UNKNOWN:
1433     default: {
1434       NOTREACHED();
1435       break;
1436     }
1437   }
1438   if (do_update_pref)
1439     GetPrefs()->SetString(language::prefs::kApplicationLocale, new_locale);
1440   if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
1441     local_state->SetString(language::prefs::kApplicationLocale, new_locale);
1442 
1443   if (user_manager::UserManager::Get()->GetOwnerAccountId() ==
1444       chromeos::ProfileHelper::Get()->GetUserByProfile(this)->GetAccountId())
1445     local_state->SetString(prefs::kOwnerLocale, new_locale);
1446 }
1447 
OnLogin()1448 void ProfileImpl::OnLogin() {
1449   if (!locale_change_guard_)
1450     locale_change_guard_ = std::make_unique<chromeos::LocaleChangeGuard>(this);
1451   locale_change_guard_->OnLogin();
1452 }
1453 
InitChromeOSPreferences()1454 void ProfileImpl::InitChromeOSPreferences() {
1455   chromeos_preferences_.reset(new chromeos::Preferences());
1456   chromeos_preferences_->Init(
1457       this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
1458 }
1459 
1460 #endif  // defined(OS_CHROMEOS)
1461 
SetCreationTimeForTesting(base::Time creation_time)1462 void ProfileImpl::SetCreationTimeForTesting(base::Time creation_time) {
1463   prefs_->SetTime(prefs::kProfileCreationTime, creation_time);
1464 }
1465 
GetHomePage()1466 GURL ProfileImpl::GetHomePage() {
1467   // --homepage overrides any preferences.
1468   const base::CommandLine& command_line =
1469       *base::CommandLine::ForCurrentProcess();
1470   if (command_line.HasSwitch(switches::kHomePage)) {
1471     // TODO(evanm): clean up usage of DIR_CURRENT.
1472     //   http://code.google.com/p/chromium/issues/detail?id=60630
1473     // For now, allow this code to call getcwd().
1474     base::ThreadRestrictions::ScopedAllowIO allow_io;
1475 
1476     base::FilePath browser_directory;
1477     base::PathService::Get(base::DIR_CURRENT, &browser_directory);
1478     GURL home_page(url_formatter::FixupRelativeFile(
1479         browser_directory,
1480         command_line.GetSwitchValuePath(switches::kHomePage)));
1481     if (home_page.is_valid())
1482       return home_page;
1483   }
1484 
1485   if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
1486     return GURL(chrome::kChromeUINewTabURL);
1487   GURL home_page(url_formatter::FixupURL(
1488       GetPrefs()->GetString(prefs::kHomePage), std::string()));
1489   if (!home_page.is_valid())
1490     return GURL(chrome::kChromeUINewTabURL);
1491   return home_page;
1492 }
1493 
UpdateSupervisedUserIdInStorage()1494 void ProfileImpl::UpdateSupervisedUserIdInStorage() {
1495   ProfileManager* profile_manager = g_browser_process->profile_manager();
1496   ProfileAttributesEntry* entry;
1497   bool has_entry = profile_manager->GetProfileAttributesStorage()
1498                        .GetProfileAttributesWithPath(GetPath(), &entry);
1499   if (has_entry)
1500     entry->SetSupervisedUserId(GetPrefs()->GetString(prefs::kSupervisedUserId));
1501 }
1502 
UpdateNameInStorage()1503 void ProfileImpl::UpdateNameInStorage() {
1504   ProfileAttributesEntry* entry;
1505   bool has_entry = g_browser_process->profile_manager()
1506                        ->GetProfileAttributesStorage()
1507                        .GetProfileAttributesWithPath(GetPath(), &entry);
1508   if (has_entry) {
1509     entry->SetLocalProfileName(
1510         base::UTF8ToUTF16(GetPrefs()->GetString(prefs::kProfileName)));
1511     entry->SetIsUsingDefaultName(
1512         GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName));
1513   }
1514 }
1515 
UpdateAvatarInStorage()1516 void ProfileImpl::UpdateAvatarInStorage() {
1517   ProfileAttributesEntry* entry;
1518   bool has_entry = g_browser_process->profile_manager()
1519                        ->GetProfileAttributesStorage()
1520                        .GetProfileAttributesWithPath(GetPath(), &entry);
1521   if (has_entry) {
1522     entry->SetAvatarIconIndex(
1523         GetPrefs()->GetInteger(prefs::kProfileAvatarIndex));
1524     entry->SetIsUsingDefaultAvatar(
1525         GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar));
1526     entry->SetIsUsingGAIAPicture(
1527         GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar));
1528   }
1529 }
1530 
UpdateIsEphemeralInStorage()1531 void ProfileImpl::UpdateIsEphemeralInStorage() {
1532   ProfileAttributesEntry* entry;
1533   bool has_entry = g_browser_process->profile_manager()
1534                        ->GetProfileAttributesStorage()
1535                        .GetProfileAttributesWithPath(GetPath(), &entry);
1536   if (has_entry) {
1537     entry->SetIsEphemeral(
1538         GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles));
1539   }
1540 }
1541 
InitializeDataReductionProxy()1542 void ProfileImpl::InitializeDataReductionProxy() {
1543   scoped_refptr<base::SequencedTaskRunner> db_task_runner =
1544       base::ThreadPool::CreateSequencedTaskRunner(
1545           {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1546            base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
1547   std::unique_ptr<data_reduction_proxy::DataStore> store(
1548       new data_reduction_proxy::DataStoreImpl(GetPath()));
1549   DataReductionProxyChromeSettingsFactory::GetForBrowserContext(this)
1550       ->InitDataReductionProxySettings(this, std::move(store), db_task_runner);
1551 }
1552