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_manager.h"
6 
7 #include <stdint.h>
8 
9 #include <map>
10 #include <set>
11 #include <string>
12 #include <utility>
13 
14 #include "base/bind.h"
15 #include "base/callback_helpers.h"
16 #include "base/command_line.h"
17 #include "base/deferred_sequenced_task_runner.h"
18 #include "base/feature_list.h"
19 #include "base/files/file_enumerator.h"
20 #include "base/files/file_path.h"
21 #include "base/files/file_util.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/metrics/user_metrics.h"
24 #include "base/no_destructor.h"
25 #include "base/stl_util.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/task/thread_pool.h"
30 #include "base/threading/scoped_blocking_call.h"
31 #include "base/trace_event/trace_event.h"
32 #include "base/util/values/values_util.h"
33 #include "build/build_config.h"
34 #include "chrome/browser/accessibility/accessibility_labels_service.h"
35 #include "chrome/browser/accessibility/accessibility_labels_service_factory.h"
36 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
37 #include "chrome/browser/browser_features.h"
38 #include "chrome/browser/browser_process.h"
39 #include "chrome/browser/chrome_notification_types.h"
40 #include "chrome/browser/chromeos/account_manager/child_account_type_changed_user_data.h"
41 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
42 #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h"
43 #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h"
44 #include "chrome/browser/download/download_core_service.h"
45 #include "chrome/browser/download/download_core_service_factory.h"
46 #include "chrome/browser/lite_video/lite_video_keyed_service.h"
47 #include "chrome/browser/lite_video/lite_video_keyed_service_factory.h"
48 #include "chrome/browser/navigation_predictor/navigation_predictor_keyed_service_factory.h"
49 #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
50 #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
51 #include "chrome/browser/password_manager/password_store_factory.h"
52 #include "chrome/browser/permissions/adaptive_quiet_notification_permission_ui_enabler.h"
53 #include "chrome/browser/prefs/incognito_mode_prefs.h"
54 #include "chrome/browser/previews/previews_service.h"
55 #include "chrome/browser/previews/previews_service_factory.h"
56 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
57 #include "chrome/browser/profiles/profile_attributes_entry.h"
58 #include "chrome/browser/profiles/profile_attributes_storage.h"
59 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
60 #include "chrome/browser/profiles/profile_destroyer.h"
61 #include "chrome/browser/profiles/profile_info_cache.h"
62 #include "chrome/browser/profiles/profile_key.h"
63 #include "chrome/browser/profiles/profile_manager_observer.h"
64 #include "chrome/browser/profiles/profile_metrics.h"
65 #include "chrome/browser/profiles/profiles_state.h"
66 #include "chrome/browser/signin/account_reconcilor_factory.h"
67 #include "chrome/browser/signin/identity_manager_factory.h"
68 #include "chrome/browser/signin/signin_util.h"
69 #include "chrome/browser/sync/profile_sync_service_factory.h"
70 #include "chrome/browser/ui/startup/startup_browser_creator.h"
71 #include "chrome/browser/ui/sync/sync_promo_ui.h"
72 #include "chrome/browser/unified_consent/unified_consent_service_factory.h"
73 #include "chrome/common/buildflags.h"
74 #include "chrome/common/chrome_constants.h"
75 #include "chrome/common/chrome_paths_internal.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/logging_chrome.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/grit/generated_resources.h"
81 #include "components/account_id/account_id.h"
82 #include "components/bookmarks/browser/bookmark_model.h"
83 #include "components/bookmarks/common/bookmark_pref_names.h"
84 #include "components/content_settings/core/browser/host_content_settings_map.h"
85 #include "components/password_manager/core/browser/password_store.h"
86 #include "components/prefs/pref_service.h"
87 #include "components/prefs/scoped_user_pref_update.h"
88 #include "components/search_engines/default_search_manager.h"
89 #include "components/signin/public/base/signin_buildflags.h"
90 #include "components/signin/public/base/signin_metrics.h"
91 #include "components/signin/public/base/signin_pref_names.h"
92 #include "components/signin/public/identity_manager/consent_level.h"
93 #include "components/signin/public/identity_manager/identity_manager.h"
94 #include "components/signin/public/identity_manager/primary_account_mutator.h"
95 #include "components/sync/base/stop_source.h"
96 #include "components/sync/driver/sync_service.h"
97 #include "content/public/browser/browser_task_traits.h"
98 #include "content/public/browser/browser_thread.h"
99 #include "content/public/browser/notification_service.h"
100 #include "content/public/browser/storage_partition.h"
101 #include "content/public/common/content_switches.h"
102 #include "extensions/buildflags/buildflags.h"
103 #include "ui/base/l10n/l10n_util.h"
104 
105 #if BUILDFLAG(ENABLE_EXTENSIONS)
106 #include "chrome/browser/extensions/extension_service.h"
107 #include "extensions/browser/extension_registry.h"
108 #include "extensions/browser/extension_system.h"
109 #include "extensions/common/extension_set.h"
110 #include "extensions/common/manifest.h"
111 #endif
112 
113 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
114 #include "chrome/browser/sessions/session_service_factory.h"
115 #endif
116 
117 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
118 #include "chrome/browser/supervised_user/child_accounts/child_account_service.h"
119 #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h"
120 #include "chrome/browser/supervised_user/supervised_user_constants.h"
121 #include "chrome/browser/supervised_user/supervised_user_service.h"
122 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
123 #endif
124 
125 #if defined(OS_ANDROID)
126 #include "chrome/browser/android/metrics/android_profile_session_durations_service_factory.h"
127 #else
128 #include "chrome/browser/accessibility/caption_controller.h"
129 #include "chrome/browser/accessibility/caption_controller_factory.h"
130 #include "chrome/browser/first_run/first_run.h"
131 #include "chrome/browser/ui/browser.h"
132 #include "chrome/browser/ui/browser_finder.h"
133 #include "chrome/browser/ui/browser_list.h"
134 #endif
135 
136 #if defined(OS_CHROMEOS)
137 #include "chrome/browser/browser_process_platform_part_chromeos.h"
138 #include "chrome/browser/chromeos/account_manager/account_manager_policy_controller_factory.h"
139 #include "chrome/browser/chromeos/profiles/profile_helper.h"
140 #include "chromeos/constants/chromeos_switches.h"
141 #include "chromeos/dbus/cryptohome/cryptohome_client.h"
142 #include "chromeos/dbus/dbus_thread_manager.h"
143 #include "components/arc/arc_features.h"
144 #include "components/arc/arc_prefs.h"
145 #include "components/arc/session/arc_supervision_transition.h"
146 #include "components/user_manager/user.h"
147 #include "components/user_manager/user_manager.h"
148 #include "components/user_manager/user_type.h"
149 #endif
150 
151 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
152 #include "chrome/browser/profiles/profile_statistics.h"
153 #include "chrome/browser/profiles/profile_statistics_factory.h"
154 #endif
155 
156 #if defined(OS_WIN) && BUILDFLAG(ENABLE_DICE_SUPPORT)
157 #include "chrome/browser/signin/signin_util_win.h"
158 #endif  // defined(OS_WIN) && BUILDFLAG(ENABLE_DICE_SUPPORT)
159 
160 using base::UserMetricsAction;
161 using content::BrowserThread;
162 
163 namespace {
164 
165 // Profile deletion can pass through two stages:
166 enum class ProfileDeletionStage {
167   // At SCHEDULING stage some actions are made before profile deletion,
168   // where one of them is the closure of browser windows. Deletion is cancelled
169   // if the user choose explicitly not to close any of the tabs.
170   SCHEDULING,
171   // At MARKED stage profile can be safely removed from disk.
172   MARKED
173 };
174 using ProfileDeletionMap = std::map<base::FilePath, ProfileDeletionStage>;
ProfilesToDelete()175 ProfileDeletionMap& ProfilesToDelete() {
176   static base::NoDestructor<ProfileDeletionMap> profiles_to_delete;
177   return *profiles_to_delete;
178 }
179 
ComputeFilesSize(const base::FilePath & directory,const base::FilePath::StringType & pattern)180 int64_t ComputeFilesSize(const base::FilePath& directory,
181                          const base::FilePath::StringType& pattern) {
182   int64_t running_size = 0;
183   base::FileEnumerator iter(directory, false, base::FileEnumerator::FILES,
184                             pattern);
185   while (!iter.Next().empty())
186     running_size += iter.GetInfo().GetSize();
187   return running_size;
188 }
189 
190 // Simple task to log the size of the current profile.
ProfileSizeTask(const base::FilePath & path,int enabled_app_count)191 void ProfileSizeTask(const base::FilePath& path, int enabled_app_count) {
192   base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
193                                                 base::BlockingType::MAY_BLOCK);
194   const int64_t kBytesInOneMB = 1024 * 1024;
195 
196   int64_t size = ComputeFilesSize(path, FILE_PATH_LITERAL("*"));
197   int size_MB = static_cast<int>(size / kBytesInOneMB);
198   UMA_HISTOGRAM_COUNTS_10000("Profile.TotalSize", size_MB);
199 
200   size = ComputeFilesSize(path, FILE_PATH_LITERAL("History"));
201   size_MB = static_cast<int>(size / kBytesInOneMB);
202   UMA_HISTOGRAM_COUNTS_10000("Profile.HistorySize", size_MB);
203 
204   size = ComputeFilesSize(path, FILE_PATH_LITERAL("History*"));
205   size_MB = static_cast<int>(size / kBytesInOneMB);
206   UMA_HISTOGRAM_COUNTS_10000("Profile.TotalHistorySize", size_MB);
207 
208   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Cookies"));
209   size_MB = static_cast<int>(size / kBytesInOneMB);
210   UMA_HISTOGRAM_COUNTS_10000("Profile.CookiesSize", size_MB);
211 
212   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Bookmarks"));
213   size_MB = static_cast<int>(size / kBytesInOneMB);
214   UMA_HISTOGRAM_COUNTS_10000("Profile.BookmarksSize", size_MB);
215 
216   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Favicons"));
217   size_MB = static_cast<int>(size / kBytesInOneMB);
218   UMA_HISTOGRAM_COUNTS_10000("Profile.FaviconsSize", size_MB);
219 
220   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Top Sites"));
221   size_MB = static_cast<int>(size / kBytesInOneMB);
222   UMA_HISTOGRAM_COUNTS_10000("Profile.TopSitesSize", size_MB);
223 
224   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Visited Links"));
225   size_MB = static_cast<int>(size / kBytesInOneMB);
226   UMA_HISTOGRAM_COUNTS_10000("Profile.VisitedLinksSize", size_MB);
227 
228   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Web Data"));
229   size_MB = static_cast<int>(size / kBytesInOneMB);
230   UMA_HISTOGRAM_COUNTS_10000("Profile.WebDataSize", size_MB);
231 
232   size = ComputeFilesSize(path, FILE_PATH_LITERAL("Extension*"));
233   size_MB = static_cast<int>(size / kBytesInOneMB);
234   UMA_HISTOGRAM_COUNTS_10000("Profile.ExtensionSize", size_MB);
235 
236   // Count number of enabled apps in this profile, if we know.
237   if (enabled_app_count != -1)
238     UMA_HISTOGRAM_COUNTS_10000("Profile.AppCount", enabled_app_count);
239 }
240 
241 #if !defined(OS_ANDROID)
242 // Schedule a profile for deletion if it isn't already scheduled.
243 // Returns whether the profile has been newly scheduled.
ScheduleProfileDirectoryForDeletion(const base::FilePath & path)244 bool ScheduleProfileDirectoryForDeletion(const base::FilePath& path) {
245   if (base::Contains(ProfilesToDelete(), path))
246     return false;
247   ProfilesToDelete()[path] = ProfileDeletionStage::SCHEDULING;
248   return true;
249 }
250 
MarkProfileDirectoryForDeletion(const base::FilePath & path)251 void MarkProfileDirectoryForDeletion(const base::FilePath& path) {
252   DCHECK(!base::Contains(ProfilesToDelete(), path) ||
253          ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING);
254   ProfilesToDelete()[path] = ProfileDeletionStage::MARKED;
255   // Remember that this profile was deleted and files should have been deleted
256   // on shutdown. In case of a crash remaining files are removed on next start.
257   ListPrefUpdate deleted_profiles(g_browser_process->local_state(),
258                                   prefs::kProfilesDeleted);
259   deleted_profiles->Append(util::FilePathToValue(path));
260 }
261 
262 // Cancel a scheduling deletion, so ScheduleProfileDirectoryForDeletion can be
263 // called again successfully.
CancelProfileDeletion(const base::FilePath & path)264 void CancelProfileDeletion(const base::FilePath& path) {
265   DCHECK(!base::Contains(ProfilesToDelete(), path) ||
266          ProfilesToDelete()[path] == ProfileDeletionStage::SCHEDULING);
267   ProfilesToDelete().erase(path);
268   ProfileMetrics::LogProfileDeleteUser(ProfileMetrics::DELETE_PROFILE_ABORTED);
269 }
270 #endif
271 
272 // Physically remove deleted profile directories from disk.
NukeProfileFromDisk(const base::FilePath & profile_path)273 void NukeProfileFromDisk(const base::FilePath& profile_path) {
274   // Delete both the profile directory and its corresponding cache.
275   base::FilePath cache_path;
276   chrome::GetUserCacheDirectory(profile_path, &cache_path);
277   base::DeletePathRecursively(profile_path);
278   base::DeletePathRecursively(cache_path);
279 }
280 
281 // Called after a deleted profile was checked and cleaned up.
ProfileCleanedUp(const base::Value * profile_path_value)282 void ProfileCleanedUp(const base::Value* profile_path_value) {
283   ListPrefUpdate deleted_profiles(g_browser_process->local_state(),
284                                   prefs::kProfilesDeleted);
285   deleted_profiles->Remove(*profile_path_value, nullptr);
286 }
287 
288 #if BUILDFLAG(ENABLE_EXTENSIONS)
289 
290 // Returns the number of installed (and enabled) apps, excluding any component
291 // apps.
GetEnabledAppCount(Profile * profile)292 size_t GetEnabledAppCount(Profile* profile) {
293   size_t installed_apps = 0u;
294   const extensions::ExtensionSet& extensions =
295       extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
296   for (extensions::ExtensionSet::const_iterator iter = extensions.begin();
297        iter != extensions.end();
298        ++iter) {
299     if ((*iter)->is_app() &&
300         (*iter)->location() != extensions::Manifest::COMPONENT) {
301       ++installed_apps;
302     }
303   }
304   return installed_apps;
305 }
306 
307 #endif  // ENABLE_EXTENSIONS
308 
309 // Once a profile is loaded through LoadProfile this method is executed.
310 // It will then run |client_callback| with the right profile or null if it was
311 // unable to load it.
312 // It might get called more than once with different values of
313 // |status| but only once the profile is fully initialized will
314 // |client_callback| be run.
OnProfileLoaded(ProfileManager::ProfileLoadedCallback client_callback,bool incognito,Profile * profile,Profile::CreateStatus status)315 void OnProfileLoaded(ProfileManager::ProfileLoadedCallback client_callback,
316                      bool incognito,
317                      Profile* profile,
318                      Profile::CreateStatus status) {
319   if (status == Profile::CREATE_STATUS_CREATED) {
320     // This is an intermediate state where the profile has been created, but is
321     // not yet initialized. Ignore this and wait for the next state change.
322     return;
323   }
324   if (status != Profile::CREATE_STATUS_INITIALIZED) {
325     LOG(WARNING) << "Profile not loaded correctly";
326     std::move(client_callback).Run(nullptr);
327     return;
328   }
329   DCHECK(profile);
330   std::move(client_callback)
331       .Run(incognito ? profile->GetPrimaryOTRProfile() : profile);
332 }
333 
334 #if !defined(OS_ANDROID)
335 // Helper function for ScheduleForcedEphemeralProfileForDeletion.
IsRegisteredAsEphemeral(ProfileAttributesStorage * storage,const base::FilePath & profile_dir)336 bool IsRegisteredAsEphemeral(ProfileAttributesStorage* storage,
337                              const base::FilePath& profile_dir) {
338   ProfileAttributesEntry* entry = nullptr;
339   return storage->GetProfileAttributesWithPath(profile_dir, &entry) &&
340          entry->IsEphemeral();
341 }
342 #endif
343 
344 // Helper function that deletes entries from the kProfilesLastActive pref list.
345 // It is called when every ephemeral profile is handled.
RemoveFromLastActiveProfilesPrefList(base::FilePath path)346 void RemoveFromLastActiveProfilesPrefList(base::FilePath path) {
347   PrefService* local_state = g_browser_process->local_state();
348   DCHECK(local_state);
349   ListPrefUpdate update(local_state, prefs::kProfilesLastActive);
350   base::ListValue* profile_list = update.Get();
351   base::Value entry_value = base::Value(path.BaseName().MaybeAsASCII());
352   profile_list->EraseListValue(entry_value);
353 }
354 
355 #if defined(OS_CHROMEOS)
IsLoggedIn()356 bool IsLoggedIn() {
357   return user_manager::UserManager::IsInitialized() &&
358          user_manager::UserManager::Get()->IsUserLoggedIn();
359 }
360 #endif
361 
362 }  // namespace
363 
ProfileManager(const base::FilePath & user_data_dir)364 ProfileManager::ProfileManager(const base::FilePath& user_data_dir)
365     : user_data_dir_(user_data_dir) {
366   registrar_.Add(this, chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
367                  content::NotificationService::AllSources());
368   registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED,
369                  content::NotificationService::AllSources());
370 
371   if (ProfileShortcutManager::IsFeatureEnabled() && !user_data_dir_.empty())
372     profile_shortcut_manager_ = ProfileShortcutManager::Create(this);
373 }
374 
~ProfileManager()375 ProfileManager::~ProfileManager() {
376   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
377 }
378 
379 // static
IsProfileDirectoryMarkedForDeletion(const base::FilePath & profile_path)380 bool ProfileManager::IsProfileDirectoryMarkedForDeletion(
381     const base::FilePath& profile_path) {
382   const auto it = ProfilesToDelete().find(profile_path);
383   return it != ProfilesToDelete().end() &&
384          it->second == ProfileDeletionStage::MARKED;
385 }
386 
387 #if BUILDFLAG(ENABLE_SESSION_SERVICE)
388 // static
ShutdownSessionServices()389 void ProfileManager::ShutdownSessionServices() {
390   ProfileManager* pm = g_browser_process->profile_manager();
391   if (!pm)  // Is nullptr when running unit tests.
392     return;
393   std::vector<Profile*> profiles(pm->GetLoadedProfiles());
394   for (size_t i = 0; i < profiles.size(); ++i)
395     SessionServiceFactory::ShutdownForProfile(profiles[i]);
396 }
397 #endif
398 
399 // static
NukeDeletedProfilesFromDisk()400 void ProfileManager::NukeDeletedProfilesFromDisk() {
401   for (const auto& item : ProfilesToDelete()) {
402     if (item.second == ProfileDeletionStage::MARKED)
403       NukeProfileFromDisk(item.first);
404   }
405   ProfilesToDelete().clear();
406 }
407 
408 // static
GetLastUsedProfile()409 Profile* ProfileManager::GetLastUsedProfile() {
410   ProfileManager* profile_manager = g_browser_process->profile_manager();
411   return profile_manager->GetLastUsedProfile(profile_manager->user_data_dir_);
412 }
413 
414 // static
GetLastUsedProfileAllowedByPolicy()415 Profile* ProfileManager::GetLastUsedProfileAllowedByPolicy() {
416   Profile* profile = GetLastUsedProfile();
417   if (!profile)
418     return nullptr;
419   if (IsOffTheRecordModeForced(profile))
420     return profile->GetPrimaryOTRProfile();
421   return profile;
422 }
423 
424 // static
IsOffTheRecordModeForced(Profile * profile)425 bool ProfileManager::IsOffTheRecordModeForced(Profile* profile) {
426   return profile->IsGuestSession() ||
427          profile->IsSystemProfile() ||
428          IncognitoModePrefs::GetAvailability(profile->GetPrefs()) ==
429              IncognitoModePrefs::FORCED;
430 }
431 
432 // static
GetLastOpenedProfiles()433 std::vector<Profile*> ProfileManager::GetLastOpenedProfiles() {
434   ProfileManager* profile_manager = g_browser_process->profile_manager();
435   return profile_manager->GetLastOpenedProfiles(
436       profile_manager->user_data_dir_);
437 }
438 
439 // static
GetPrimaryUserProfile()440 Profile* ProfileManager::GetPrimaryUserProfile() {
441   ProfileManager* profile_manager = g_browser_process->profile_manager();
442   if (!profile_manager)  // Can be null in unit tests.
443     return nullptr;
444 #if defined(OS_CHROMEOS)
445   if (!IsLoggedIn()) {
446     return profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
447         profile_manager->user_data_dir());
448   }
449 
450   user_manager::UserManager* manager = user_manager::UserManager::Get();
451   const user_manager::User* user = manager->GetPrimaryUser();
452   if (!user)  // Can be null in unit tests.
453     return nullptr;
454 
455   // Note: The ProfileHelper will take care of guest profiles.
456   return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
457 #else
458   return profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
459       profile_manager->user_data_dir());
460 #endif
461 }
462 
463 // static
GetActiveUserProfile()464 Profile* ProfileManager::GetActiveUserProfile() {
465   ProfileManager* profile_manager = g_browser_process->profile_manager();
466 #if defined(OS_CHROMEOS)
467   if (!profile_manager)
468     return nullptr;
469 
470   if (IsLoggedIn()) {
471     user_manager::UserManager* manager = user_manager::UserManager::Get();
472     const user_manager::User* user = manager->GetActiveUser();
473     // To avoid an endless loop (crbug.com/334098) we have to additionally check
474     // if the profile of the user was already created. If the profile was not
475     // yet created we load the profile using the profile directly.
476     // TODO: This should be cleaned up with the new profile manager.
477     if (user && user->is_profile_created())
478       return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
479   }
480 #endif
481   Profile* profile =
482       profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
483           profile_manager->user_data_dir());
484   // |profile| could be null if the user doesn't have a profile yet and the path
485   // is on a read-only volume (preventing Chrome from making a new one).
486   // However, most callers of this function immediately dereference the result
487   // which would lead to crashes in a variety of call sites. Assert here to
488   // figure out how common this is. http://crbug.com/383019
489   CHECK(profile) << profile_manager->user_data_dir().AsUTF8Unsafe();
490   return profile;
491 }
492 
493 // static
CreateInitialProfile()494 Profile* ProfileManager::CreateInitialProfile() {
495   ProfileManager* const profile_manager = g_browser_process->profile_manager();
496   Profile* profile =
497       profile_manager->GetProfile(profile_manager->user_data_dir().Append(
498           profile_manager->GetInitialProfileDir()));
499 
500   if (profile_manager->ShouldGoOffTheRecord(profile))
501     return profile->GetPrimaryOTRProfile();
502   return profile;
503 }
504 
AddObserver(ProfileManagerObserver * observer)505 void ProfileManager::AddObserver(ProfileManagerObserver* observer) {
506   observers_.AddObserver(observer);
507 }
508 
RemoveObserver(ProfileManagerObserver * observer)509 void ProfileManager::RemoveObserver(ProfileManagerObserver* observer) {
510   observers_.RemoveObserver(observer);
511 }
512 
GetProfile(const base::FilePath & profile_dir)513 Profile* ProfileManager::GetProfile(const base::FilePath& profile_dir) {
514   TRACE_EVENT0("browser", "ProfileManager::GetProfile");
515 
516   // If the profile is already loaded (e.g., chrome.exe launched twice), just
517   // return it.
518   Profile* profile = GetProfileByPath(profile_dir);
519   if (profile)
520     return profile;
521   return CreateAndInitializeProfile(profile_dir);
522 }
523 
GetNumberOfProfiles()524 size_t ProfileManager::GetNumberOfProfiles() {
525   return GetProfileAttributesStorage().GetNumberOfProfiles();
526 }
527 
LoadProfile(const std::string & profile_name,bool incognito,ProfileLoadedCallback callback)528 bool ProfileManager::LoadProfile(const std::string& profile_name,
529                                  bool incognito,
530                                  ProfileLoadedCallback callback) {
531   const base::FilePath profile_path = user_data_dir().AppendASCII(profile_name);
532   return LoadProfileByPath(profile_path, incognito, std::move(callback));
533 }
534 
LoadProfileByPath(const base::FilePath & profile_path,bool incognito,ProfileLoadedCallback callback)535 bool ProfileManager::LoadProfileByPath(const base::FilePath& profile_path,
536                                        bool incognito,
537                                        ProfileLoadedCallback callback) {
538   ProfileAttributesEntry* entry = nullptr;
539   if (!GetProfileAttributesStorage().GetProfileAttributesWithPath(profile_path,
540                                                                   &entry)) {
541     std::move(callback).Run(nullptr);
542     LOG(ERROR) << "Loading a profile path that does not exist";
543     return false;
544   }
545   CreateProfileAsync(
546       profile_path,
547       base::BindRepeating(&OnProfileLoaded,
548                           // OnProfileLoaded may be called multiple times, but
549                           // |callback| will be called only once.
550                           base::AdaptCallbackForRepeating(std::move(callback)),
551                           incognito),
552       base::string16() /* name */, std::string() /* icon_url */);
553   return true;
554 }
555 
CreateProfileAsync(const base::FilePath & profile_path,const CreateCallback & callback,const base::string16 & name,const std::string & icon_url)556 void ProfileManager::CreateProfileAsync(const base::FilePath& profile_path,
557                                         const CreateCallback& callback,
558                                         const base::string16& name,
559                                         const std::string& icon_url) {
560   DCHECK_CURRENTLY_ON(BrowserThread::UI);
561   TRACE_EVENT1("browser,startup",
562                "ProfileManager::CreateProfileAsync",
563                "profile_path",
564                profile_path.AsUTF8Unsafe());
565 
566   bool is_allowed_path = IsAllowedProfilePath(profile_path) ||
567                          base::CommandLine::ForCurrentProcess()->HasSwitch(
568                              switches::kAllowProfilesOutsideUserDir);
569 
570   // Make sure the path is correct and this profile is not pending deletion.
571   if (!is_allowed_path || IsProfileDirectoryMarkedForDeletion(profile_path)) {
572     if (!is_allowed_path) {
573       LOG(ERROR) << "Cannot create profile at path "
574                  << profile_path.AsUTF8Unsafe();
575     }
576     if (!callback.is_null())
577       callback.Run(nullptr, Profile::CREATE_STATUS_LOCAL_FAIL);
578     return;
579   }
580 
581   // Create the profile if needed and collect its ProfileInfo.
582   auto iter = profiles_info_.find(profile_path);
583   ProfileInfo* info = nullptr;
584 
585   if (iter != profiles_info_.end()) {
586     info = iter->second.get();
587   } else {
588     // Initiate asynchronous creation process.
589     info = RegisterProfile(CreateProfileAsyncHelper(profile_path, this), false);
590     size_t icon_index;
591     DCHECK(base::IsStringASCII(icon_url));
592     if (profiles::IsDefaultAvatarIconUrl(icon_url, &icon_index)) {
593       // add profile to cache with user selected name and avatar
594       GetProfileAttributesStorage().AddProfile(
595           profile_path, name, std::string(), base::string16(),
596           /*is_consented_primary_account=*/false, icon_index,
597           /*supervised_user_id=*/std::string(), EmptyAccountId());
598     }
599   }
600 
601   // Call or enqueue the callback.
602   if (!callback.is_null()) {
603     if (iter != profiles_info_.end() && info->created) {
604       Profile* profile = info->profile.get();
605       // If this was the non-ephemeral Guest profile, apply settings and go
606       // OffTheRecord.
607       // The system profile also needs characteristics of being off the record,
608       // such as having no extensions, not writing to disk, etc.
609       if (profile->IsGuestSession() || profile->IsEphemeralGuestProfile() ||
610           profile->IsSystemProfile()) {
611         SetNonPersonalProfilePrefs(profile);
612       }
613       if (profile->IsGuestSession() || profile->IsSystemProfile())
614         profile = profile->GetPrimaryOTRProfile();
615 
616       // Profile has already been created. Run callback immediately.
617       callback.Run(profile, Profile::CREATE_STATUS_INITIALIZED);
618     } else {
619       // Profile is either already in the process of being created, or new.
620       // Add callback to the list.
621       info->callbacks.push_back(callback);
622     }
623   }
624 }
625 
IsValidProfile(const void * profile)626 bool ProfileManager::IsValidProfile(const void* profile) {
627   for (auto iter = profiles_info_.begin(); iter != profiles_info_.end();
628        ++iter) {
629     if (iter->second->created) {
630       Profile* candidate = iter->second->profile.get();
631       if (candidate == profile)
632         return true;
633       std::vector<Profile*> otr_profiles =
634           candidate->GetAllOffTheRecordProfiles();
635       if (base::Contains(otr_profiles, profile))
636         return true;
637     }
638   }
639   return false;
640 }
641 
GetInitialProfileDir()642 base::FilePath ProfileManager::GetInitialProfileDir() {
643 #if defined(OS_CHROMEOS)
644   if (IsLoggedIn())
645     return chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
646 #endif
647   base::FilePath relative_profile_dir;
648   // TODO(mirandac): should not automatically be default profile.
649   return relative_profile_dir.AppendASCII(chrome::kInitialProfile);
650 }
651 
GetLastUsedProfile(const base::FilePath & user_data_dir)652 Profile* ProfileManager::GetLastUsedProfile(
653     const base::FilePath& user_data_dir) {
654 #if defined(OS_CHROMEOS)
655   // Use default login profile if user has not logged in yet.
656   if (!IsLoggedIn())
657     return GetActiveUserOrOffTheRecordProfileFromPath(user_data_dir);
658 
659   // CrOS multi-profiles implementation is different so GetLastUsedProfile
660   // has custom implementation too.
661   base::FilePath profile_dir;
662   // In case of multi-profiles we ignore "last used profile" preference
663   // since it may refer to profile that has been in use in previous session.
664   // That profile dir may not be mounted in this session so instead return
665   // active profile from current session.
666   profile_dir = chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
667 
668   base::FilePath profile_path(user_data_dir);
669   Profile* profile = GetProfileByPath(profile_path.Append(profile_dir));
670 
671   // Accessing a user profile before it is loaded may lead to policy exploit.
672   // See http://crbug.com/689206.
673   LOG_IF(FATAL, !profile) << "Calling GetLastUsedProfile() before profile "
674                           << "initialization is completed.";
675 
676   return profile->IsGuestSession() ? profile->GetPrimaryOTRProfile() : profile;
677 #else
678   return GetProfile(GetLastUsedProfileDir(user_data_dir));
679 #endif
680 }
681 
GetLastUsedProfileDir(const base::FilePath & user_data_dir)682 base::FilePath ProfileManager::GetLastUsedProfileDir(
683     const base::FilePath& user_data_dir) {
684   return user_data_dir.AppendASCII(GetLastUsedProfileName());
685 }
686 
GetLastUsedProfileName()687 std::string ProfileManager::GetLastUsedProfileName() {
688   PrefService* local_state = g_browser_process->local_state();
689   DCHECK(local_state);
690   const std::string last_used_profile_name =
691       local_state->GetString(prefs::kProfileLastUsed);
692   // Make sure the system profile can't be the one marked as the last one used
693   // since it shouldn't get a browser.
694   if (!last_used_profile_name.empty() &&
695       last_used_profile_name !=
696           base::FilePath(chrome::kSystemProfileDir).AsUTF8Unsafe()) {
697     return last_used_profile_name;
698   }
699 
700   return chrome::kInitialProfile;
701 }
702 
GetLastOpenedProfiles(const base::FilePath & user_data_dir)703 std::vector<Profile*> ProfileManager::GetLastOpenedProfiles(
704     const base::FilePath& user_data_dir) {
705   PrefService* local_state = g_browser_process->local_state();
706   DCHECK(local_state);
707 
708   std::vector<Profile*> to_return;
709   if (local_state->HasPrefPath(prefs::kProfilesLastActive) &&
710       local_state->GetList(prefs::kProfilesLastActive)) {
711     // Make a copy because the list might change in the calls to GetProfile.
712     std::unique_ptr<base::ListValue> profile_list(
713         local_state->GetList(prefs::kProfilesLastActive)->DeepCopy());
714     base::ListValue::const_iterator it;
715     for (it = profile_list->begin(); it != profile_list->end(); ++it) {
716       std::string profile_path;
717       if (!it->GetAsString(&profile_path) || profile_path.empty() ||
718           profile_path ==
719               base::FilePath(chrome::kSystemProfileDir).AsUTF8Unsafe()) {
720         LOG(WARNING) << "Invalid entry in " << prefs::kProfilesLastActive;
721         continue;
722       }
723       Profile* profile = GetProfile(user_data_dir.AppendASCII(profile_path));
724       if (profile) {
725         // crbug.com/823338 -> CHECK that the profiles aren't guest or
726         // incognito, causing a crash during session restore.
727         CHECK(!profile->IsGuestSession() && !profile->IsEphemeralGuestProfile())
728             << "Guest profiles shouldn't have been saved as active profiles";
729         CHECK(!profile->IsOffTheRecord())
730             << "OTR profiles shouldn't have been saved as active profiles";
731         to_return.push_back(profile);
732       }
733     }
734   }
735   return to_return;
736 }
737 
GetLoadedProfiles() const738 std::vector<Profile*> ProfileManager::GetLoadedProfiles() const {
739   std::vector<Profile*> profiles;
740   for (auto iter = profiles_info_.begin(); iter != profiles_info_.end();
741        ++iter) {
742     if (iter->second->created)
743       profiles.push_back(iter->second->profile.get());
744   }
745   return profiles;
746 }
747 
GetProfileByPathInternal(const base::FilePath & path) const748 Profile* ProfileManager::GetProfileByPathInternal(
749     const base::FilePath& path) const {
750   TRACE_EVENT0("browser", "ProfileManager::GetProfileByPathInternal");
751   ProfileInfo* profile_info = GetProfileInfoByPath(path);
752   return profile_info ? profile_info->profile.get() : nullptr;
753 }
754 
IsAllowedProfilePath(const base::FilePath & path) const755 bool ProfileManager::IsAllowedProfilePath(const base::FilePath& path) const {
756   return path.DirName() == user_data_dir();
757 }
758 
GetProfileByPath(const base::FilePath & path) const759 Profile* ProfileManager::GetProfileByPath(const base::FilePath& path) const {
760   TRACE_EVENT0("browser", "ProfileManager::GetProfileByPath");
761   ProfileInfo* profile_info = GetProfileInfoByPath(path);
762   return (profile_info && profile_info->created) ? profile_info->profile.get()
763                                                  : nullptr;
764 }
765 
766 // static
GetProfileFromProfileKey(ProfileKey * profile_key)767 Profile* ProfileManager::GetProfileFromProfileKey(ProfileKey* profile_key) {
768   Profile* profile = g_browser_process->profile_manager()->GetProfileByPath(
769       profile_key->GetPath());
770   if (profile->GetProfileKey() == profile_key)
771     return profile;
772 
773   for (Profile* otr : profile->GetAllOffTheRecordProfiles()) {
774     if (otr->GetProfileKey() == profile_key)
775       return otr;
776   }
777 
778   NOTREACHED() << "An invalid profile key is passed.";
779   return nullptr;
780 }
781 
782 // static
CreateMultiProfileAsync(const base::string16 & name,const std::string & icon_url,const CreateCallback & callback)783 base::FilePath ProfileManager::CreateMultiProfileAsync(
784     const base::string16& name,
785     const std::string& icon_url,
786     const CreateCallback& callback) {
787   DCHECK_CURRENTLY_ON(BrowserThread::UI);
788 
789   ProfileManager* profile_manager = g_browser_process->profile_manager();
790 
791   base::FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
792 
793   profile_manager->CreateProfileAsync(new_path, callback, name, icon_url);
794   return new_path;
795 }
796 
797 // static
GetGuestProfilePath()798 base::FilePath ProfileManager::GetGuestProfilePath() {
799   DCHECK_CURRENTLY_ON(BrowserThread::UI);
800 
801   ProfileManager* profile_manager = g_browser_process->profile_manager();
802 
803   if (profile_manager->guest_profile_path_.empty()) {
804     if (Profile::IsEphemeralGuestProfileEnabled()) {
805       PrefService* local_state = g_browser_process->local_state();
806       DCHECK(local_state);
807 
808       // Create the next Guest profile in the next available directory slot.
809       int next_directory =
810           local_state->GetInteger(prefs::kGuestProfilesNumCreated);
811       std::string profile_name = chrome::kEphemeralGuestProfileDirPrefix;
812       profile_name.append(base::NumberToString(next_directory));
813       base::FilePath new_path = profile_manager->user_data_dir();
814 #if defined(OS_WIN)
815       new_path = new_path.Append(base::ASCIIToUTF16(profile_name));
816 #else
817       new_path = new_path.Append(profile_name);
818 #endif
819       local_state->SetInteger(prefs::kGuestProfilesNumCreated,
820                               ++next_directory);
821       profile_manager->guest_profile_path_ = new_path;
822     } else {
823       profile_manager->guest_profile_path_ =
824           profile_manager->user_data_dir().Append(chrome::kGuestProfileDir);
825     }
826   }
827 
828   return profile_manager->guest_profile_path_;
829 }
830 
831 // static
GetSystemProfilePath()832 base::FilePath ProfileManager::GetSystemProfilePath() {
833   DCHECK_CURRENTLY_ON(BrowserThread::UI);
834 
835   ProfileManager* profile_manager = g_browser_process->profile_manager();
836 
837   base::FilePath system_path = profile_manager->user_data_dir();
838   return system_path.Append(chrome::kSystemProfileDir);
839 }
840 
GenerateNextProfileDirectoryPath()841 base::FilePath ProfileManager::GenerateNextProfileDirectoryPath() {
842   PrefService* local_state = g_browser_process->local_state();
843   DCHECK(local_state);
844 
845   DCHECK(profiles::IsMultipleProfilesEnabled());
846 
847   // Create the next profile in the next available directory slot.
848   int next_directory = local_state->GetInteger(prefs::kProfilesNumCreated);
849   std::string profile_name = chrome::kMultiProfileDirPrefix;
850   profile_name.append(base::NumberToString(next_directory));
851   base::FilePath new_path = user_data_dir_;
852 #if defined(OS_WIN)
853   new_path = new_path.Append(base::ASCIIToUTF16(profile_name));
854 #else
855   new_path = new_path.Append(profile_name);
856 #endif
857   local_state->SetInteger(prefs::kProfilesNumCreated, ++next_directory);
858   return new_path;
859 }
860 
GetProfileInfoCache()861 ProfileInfoCache& ProfileManager::GetProfileInfoCache() {
862   TRACE_EVENT0("browser", "ProfileManager::GetProfileInfoCache");
863   if (!profile_info_cache_) {
864     profile_info_cache_.reset(new ProfileInfoCache(
865         g_browser_process->local_state(), user_data_dir_));
866   }
867   return *profile_info_cache_.get();
868 }
869 
GetProfileAttributesStorage()870 ProfileAttributesStorage& ProfileManager::GetProfileAttributesStorage() {
871   return GetProfileInfoCache();
872 }
873 
profile_shortcut_manager()874 ProfileShortcutManager* ProfileManager::profile_shortcut_manager() {
875   return profile_shortcut_manager_.get();
876 }
877 
878 #if !defined(OS_ANDROID)
MaybeScheduleProfileForDeletion(const base::FilePath & profile_dir,ProfileLoadedCallback callback,ProfileMetrics::ProfileDelete deletion_source)879 void ProfileManager::MaybeScheduleProfileForDeletion(
880     const base::FilePath& profile_dir,
881     ProfileLoadedCallback callback,
882     ProfileMetrics::ProfileDelete deletion_source) {
883   if (!ScheduleProfileDirectoryForDeletion(profile_dir))
884     return;
885 
886   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
887   ProfileAttributesEntry* entry;
888   if (storage.GetProfileAttributesWithPath(profile_dir, &entry)) {
889     storage.RecordDeletedProfileState(entry);
890   }
891   ProfileMetrics::LogProfileDeleteUser(deletion_source);
892 
893   ScheduleProfileForDeletion(profile_dir, std::move(callback));
894 }
895 
ScheduleProfileForDeletion(const base::FilePath & profile_dir,ProfileLoadedCallback callback)896 void ProfileManager::ScheduleProfileForDeletion(
897     const base::FilePath& profile_dir,
898     ProfileLoadedCallback callback) {
899   DCHECK(profiles::IsMultipleProfilesEnabled());
900   DCHECK(!IsProfileDirectoryMarkedForDeletion(profile_dir));
901 
902   Profile* profile = GetProfileByPath(profile_dir);
903   if (profile) {
904     // Cancel all in-progress downloads before deleting the profile to prevent a
905     // "Do you want to exit Google Chrome and cancel the downloads?" prompt
906     // (crbug.com/336725).
907     DownloadCoreService* service =
908         DownloadCoreServiceFactory::GetForBrowserContext(profile);
909     service->CancelDownloads();
910     DCHECK_EQ(0, service->NonMaliciousDownloadCount());
911 
912     // Close all browser windows before deleting the profile. If the user
913     // cancels the closing of any tab in an OnBeforeUnload event, profile
914     // deletion is also cancelled. (crbug.com/289390)
915     BrowserList::CloseAllBrowsersWithProfile(
916         profile,
917         base::Bind(&ProfileManager::EnsureActiveProfileExistsBeforeDeletion,
918                    base::Unretained(this), base::Passed(std::move(callback))),
919         base::Bind(&CancelProfileDeletion), false);
920   } else {
921     EnsureActiveProfileExistsBeforeDeletion(std::move(callback), profile_dir);
922   }
923 }
924 #endif  // !defined(OS_ANDROID)
925 
AutoloadProfiles()926 void ProfileManager::AutoloadProfiles() {
927   // If running in the background is disabled for the browser, do not autoload
928   // any profiles.
929   PrefService* local_state = g_browser_process->local_state();
930   DCHECK(local_state);
931   if (!local_state->HasPrefPath(prefs::kBackgroundModeEnabled) ||
932       !local_state->GetBoolean(prefs::kBackgroundModeEnabled)) {
933     return;
934   }
935 
936   std::vector<ProfileAttributesEntry*> entries =
937       GetProfileAttributesStorage().GetAllProfilesAttributes();
938   for (ProfileAttributesEntry* entry : entries) {
939     if (entry->GetBackgroundStatus()) {
940       // If status is true, that profile is running background apps. By calling
941       // GetProfile, we automatically cause the profile to be loaded which will
942       // register it with the BackgroundModeManager.
943       GetProfile(entry->GetPath());
944     }
945   }
946 }
947 
CleanUpEphemeralProfiles()948 void ProfileManager::CleanUpEphemeralProfiles() {
949   const std::string last_used_profile = GetLastUsedProfileName();
950   bool last_active_profile_deleted = false;
951   base::FilePath new_profile_path;
952   std::vector<base::FilePath> profiles_to_delete;
953   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
954   std::vector<ProfileAttributesEntry*> entries =
955       storage.GetAllProfilesAttributes();
956   for (ProfileAttributesEntry* entry : entries) {
957     base::FilePath profile_path = entry->GetPath();
958     if (entry->IsEphemeral()) {
959       profiles_to_delete.push_back(profile_path);
960       RemoveFromLastActiveProfilesPrefList(profile_path);
961       if (profile_path.BaseName().MaybeAsASCII() == last_used_profile)
962         last_active_profile_deleted = true;
963     } else if (new_profile_path.empty()) {
964       new_profile_path = profile_path;
965     }
966   }
967 
968   // If the last active profile was ephemeral or all profiles are deleted due to
969   // ephemeral, set a new one.
970   if (last_active_profile_deleted ||
971       (entries.size() == profiles_to_delete.size() &&
972        !profiles_to_delete.empty())) {
973     if (new_profile_path.empty())
974       new_profile_path = GenerateNextProfileDirectoryPath();
975 
976     profiles::SetLastUsedProfile(new_profile_path.BaseName().MaybeAsASCII());
977   }
978 
979   // This uses a separate loop, because deleting the profile from the
980   // ProfileInfoCache will modify indices.
981   for (const base::FilePath& profile_path : profiles_to_delete) {
982     base::ThreadPool::PostTask(
983         FROM_HERE,
984         {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
985          base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
986         base::BindOnce(&NukeProfileFromDisk, profile_path));
987 
988     storage.RemoveProfile(profile_path);
989   }
990 }
991 
CleanUpDeletedProfiles()992 void ProfileManager::CleanUpDeletedProfiles() {
993   PrefService* local_state = g_browser_process->local_state();
994   DCHECK(local_state);
995   const base::ListValue* deleted_profiles =
996       local_state->GetList(prefs::kProfilesDeleted);
997   DCHECK(deleted_profiles);
998 
999   for (const base::Value& value : *deleted_profiles) {
1000     base::Optional<base::FilePath> profile_path = util::ValueToFilePath(value);
1001     // Although it should never happen, make sure this is a valid path in the
1002     // user_data_dir, so we don't accidentally delete something else.
1003     if (profile_path && IsAllowedProfilePath(*profile_path)) {
1004       if (base::PathExists(*profile_path)) {
1005         LOG(WARNING) << "Files of a deleted profile still exist after restart. "
1006                         "Cleaning up now.";
1007         base::ThreadPool::PostTaskAndReply(
1008             FROM_HERE,
1009             {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1010              base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
1011             base::BindOnce(&NukeProfileFromDisk, *profile_path),
1012             base::BindOnce(&ProfileCleanedUp, &value));
1013       } else {
1014         // Everything is fine, the profile was removed on shutdown.
1015         content::GetUIThreadTaskRunner({})->PostTask(
1016             FROM_HERE, base::BindOnce(&ProfileCleanedUp, &value));
1017       }
1018     } else {
1019       LOG(ERROR) << "Found invalid profile path in deleted_profiles: "
1020                  << profile_path->AsUTF8Unsafe();
1021       NOTREACHED();
1022     }
1023   }
1024 }
1025 
InitProfileUserPrefs(Profile * profile)1026 void ProfileManager::InitProfileUserPrefs(Profile* profile) {
1027   TRACE_EVENT0("browser", "ProfileManager::InitProfileUserPrefs");
1028   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1029 
1030   if (!IsAllowedProfilePath(profile->GetPath())) {
1031     LOG(WARNING) << "Failed to initialize prefs for a profile at invalid path: "
1032                  << profile->GetPath().AsUTF8Unsafe();
1033     return;
1034   }
1035 
1036 #if defined(OS_CHROMEOS)
1037   // User object may already have changed user type, so we apply that
1038   // type to profile.
1039   // If profile type has changed, remove ProfileInfoCache entry for it to
1040   // make sure it is fully re-initialized later.
1041   const user_manager::User* user =
1042       chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
1043   if (user) {
1044     const bool user_is_child =
1045         (user->GetType() == user_manager::USER_TYPE_CHILD);
1046     const bool profile_is_child = profile->IsChild();
1047     const bool profile_is_new = profile->IsNewProfile();
1048     if (!profile_is_new && profile_is_child != user_is_child) {
1049       ProfileAttributesEntry* entry;
1050       if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry)) {
1051         LOG(WARNING) << "Profile child status has changed.";
1052         storage.RemoveProfile(profile->GetPath());
1053       }
1054       arc::ArcSupervisionTransition supervisionTransition;
1055       if (!profile->GetPrefs()->GetBoolean(arc::prefs::kArcSignedIn)) {
1056         // No transition is necessary if user never enabled ARC.
1057         supervisionTransition = arc::ArcSupervisionTransition::NO_TRANSITION;
1058       } else {
1059         // Notify ARC about user type change via prefs if user enabled ARC.
1060         supervisionTransition =
1061             user_is_child ? arc::ArcSupervisionTransition::REGULAR_TO_CHILD
1062                           : arc::ArcSupervisionTransition::CHILD_TO_REGULAR;
1063       }
1064       profile->GetPrefs()->SetInteger(arc::prefs::kArcSupervisionTransition,
1065                                       static_cast<int>(supervisionTransition));
1066       chromeos::ChildAccountTypeChangedUserData::GetForProfile(profile)
1067           ->SetValue(true);
1068     } else {
1069       chromeos::ChildAccountTypeChangedUserData::GetForProfile(profile)
1070           ->SetValue(false);
1071     }
1072 
1073     if (user_is_child) {
1074       profile->GetPrefs()->SetString(prefs::kSupervisedUserId,
1075                                      supervised_users::kChildAccountSUID);
1076     } else {
1077       profile->GetPrefs()->ClearPref(prefs::kSupervisedUserId);
1078     }
1079   }
1080 #endif
1081 
1082   size_t avatar_index;
1083   std::string profile_name;
1084   std::string supervised_user_id;
1085   if (profile->IsGuestSession() || profile->IsEphemeralGuestProfile()) {
1086     profile_name = l10n_util::GetStringUTF8(IDS_PROFILES_GUEST_PROFILE_NAME);
1087     avatar_index = 0;
1088   } else {
1089     ProfileAttributesEntry* entry;
1090     bool has_entry = storage.GetProfileAttributesWithPath(profile->GetPath(),
1091                                                           &entry);
1092     // If the profile attributes storage has an entry for this profile, use the
1093     // data in the profile attributes storage.
1094     if (has_entry) {
1095       avatar_index = entry->GetAvatarIconIndex();
1096       profile_name = base::UTF16ToUTF8(entry->GetLocalProfileName());
1097       supervised_user_id = entry->GetSupervisedUserId();
1098     } else if (profile->GetPath() ==
1099                    profiles::GetDefaultProfileDir(user_data_dir())) {
1100       avatar_index = profiles::GetPlaceholderAvatarIndex();
1101 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
1102       profile_name =
1103           base::UTF16ToUTF8(storage.ChooseNameForNewProfile(avatar_index));
1104 #else
1105       profile_name = l10n_util::GetStringUTF8(IDS_DEFAULT_PROFILE_NAME);
1106 #endif
1107     } else {
1108       avatar_index = storage.ChooseAvatarIconIndexForNewProfile();
1109       profile_name =
1110           base::UTF16ToUTF8(storage.ChooseNameForNewProfile(avatar_index));
1111     }
1112   }
1113 
1114   if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileAvatarIndex))
1115     profile->GetPrefs()->SetInteger(prefs::kProfileAvatarIndex, avatar_index);
1116 
1117   if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileName)) {
1118     profile->GetPrefs()->SetString(prefs::kProfileName, profile_name);
1119   }
1120 
1121   base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1122   bool force_supervised_user_id =
1123 #if defined(OS_CHROMEOS)
1124       g_browser_process->platform_part()
1125               ->profile_helper()
1126               ->GetSigninProfileDir() != profile->GetPath() &&
1127       g_browser_process->platform_part()
1128               ->profile_helper()
1129               ->GetLockScreenAppProfilePath() != profile->GetPath() &&
1130 #endif
1131       command_line->HasSwitch(switches::kSupervisedUserId);
1132 
1133   if (force_supervised_user_id) {
1134     supervised_user_id =
1135         command_line->GetSwitchValueASCII(switches::kSupervisedUserId);
1136   }
1137   if (force_supervised_user_id ||
1138       !profile->GetPrefs()->HasPrefPath(prefs::kSupervisedUserId)) {
1139     profile->GetPrefs()->SetString(prefs::kSupervisedUserId,
1140                                    supervised_user_id);
1141   }
1142 #if !defined(OS_ANDROID)
1143   // TODO(pmonette): Fix IsNewProfile() to handle the case where the profile is
1144   // new even if the "Preferences" file already existed. (For example: The
1145   // master_preferences file is dumped into the default profile on first run,
1146   // before profile creation.)
1147   if (profile->IsNewProfile() || first_run::IsChromeFirstRun()) {
1148     profile->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage, false);
1149   }
1150 #endif  // !defined(OS_ANDROID)
1151 }
1152 
RegisterTestingProfile(std::unique_ptr<Profile> profile,bool add_to_storage)1153 void ProfileManager::RegisterTestingProfile(std::unique_ptr<Profile> profile,
1154                                             bool add_to_storage) {
1155   Profile* profile_ptr = profile.get();
1156   RegisterProfile(std::move(profile), true);
1157   if (add_to_storage) {
1158     InitProfileUserPrefs(profile_ptr);
1159     AddProfileToStorage(profile_ptr);
1160   }
1161 }
1162 
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)1163 void ProfileManager::Observe(int type,
1164                              const content::NotificationSource& source,
1165                              const content::NotificationDetails& details) {
1166   bool save_active_profiles = false;
1167   switch (type) {
1168     case chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST: {
1169       // Ignore any browsers closing from now on.
1170       closing_all_browsers_ = true;
1171       save_active_profiles = true;
1172       break;
1173     }
1174     case chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED: {
1175       // This will cancel the shutdown process, so the active profiles are
1176       // tracked again. Also, as the active profiles may have changed (i.e. if
1177       // some windows were closed) we save the current list of active profiles
1178       // again.
1179       closing_all_browsers_ = false;
1180       save_active_profiles = true;
1181       break;
1182     }
1183     default: {
1184       NOTREACHED();
1185       break;
1186     }
1187   }
1188 
1189   if (save_active_profiles)
1190     SaveActiveProfiles();
1191 }
1192 
OnProfileCreated(Profile * profile,bool success,bool is_new_profile)1193 void ProfileManager::OnProfileCreated(Profile* profile,
1194                                       bool success,
1195                                       bool is_new_profile) {
1196   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1197 
1198   auto iter = profiles_info_.find(profile->GetPath());
1199   DCHECK(iter != profiles_info_.end());
1200   ProfileInfo* info = iter->second.get();
1201 
1202   std::vector<CreateCallback> callbacks;
1203   info->callbacks.swap(callbacks);
1204 
1205   // Invoke CREATED callback for normal profiles.
1206   bool go_off_the_record = ShouldGoOffTheRecord(profile);
1207   if (success && !go_off_the_record)
1208     RunCallbacks(callbacks, profile, Profile::CREATE_STATUS_CREATED);
1209 
1210   // Perform initialization.
1211   if (success) {
1212     DoFinalInit(info, go_off_the_record);
1213     if (go_off_the_record)
1214       profile = profile->GetPrimaryOTRProfile();
1215   } else {
1216     profile = nullptr;
1217     profiles_info_.erase(iter);
1218   }
1219 
1220   if (profile) {
1221     // If this was the guest or system profile, finish setting its special
1222     // status.
1223     if (profile->IsGuestSession() || profile->IsSystemProfile() ||
1224         profile->IsEphemeralGuestProfile()) {
1225       SetNonPersonalProfilePrefs(profile);
1226     }
1227 
1228     // Invoke CREATED callback for incognito profiles.
1229     if (go_off_the_record)
1230       RunCallbacks(callbacks, profile, Profile::CREATE_STATUS_CREATED);
1231   }
1232 
1233   // Invoke INITIALIZED or FAIL for all profiles.
1234   RunCallbacks(callbacks, profile,
1235                profile ? Profile::CREATE_STATUS_INITIALIZED :
1236                          Profile::CREATE_STATUS_LOCAL_FAIL);
1237 }
1238 
CreateProfileHelper(const base::FilePath & path)1239 std::unique_ptr<Profile> ProfileManager::CreateProfileHelper(
1240     const base::FilePath& path) {
1241   TRACE_EVENT0("browser", "ProfileManager::CreateProfileHelper");
1242 
1243   return Profile::CreateProfile(path, nullptr,
1244                                 Profile::CREATE_MODE_SYNCHRONOUS);
1245 }
1246 
CreateProfileAsyncHelper(const base::FilePath & path,Delegate * delegate)1247 std::unique_ptr<Profile> ProfileManager::CreateProfileAsyncHelper(
1248     const base::FilePath& path,
1249     Delegate* delegate) {
1250   return Profile::CreateProfile(path, delegate,
1251                                 Profile::CREATE_MODE_ASYNCHRONOUS);
1252 }
1253 
DoFinalInit(ProfileInfo * profile_info,bool go_off_the_record)1254 void ProfileManager::DoFinalInit(ProfileInfo* profile_info,
1255                                  bool go_off_the_record) {
1256   TRACE_EVENT0("browser", "ProfileManager::DoFinalInit");
1257 
1258   Profile* profile = profile_info->profile.get();
1259   DoFinalInitForServices(profile, go_off_the_record);
1260   AddProfileToStorage(profile);
1261   DoFinalInitLogging(profile);
1262 
1263   // Set the |created| flag now so that PROFILE_ADDED handlers can use
1264   // GetProfileByPath().
1265   profile_info->created = true;
1266 
1267   for (auto& observer : observers_)
1268     observer.OnProfileAdded(profile);
1269 
1270   content::NotificationService::current()->Notify(
1271       chrome::NOTIFICATION_PROFILE_ADDED,
1272       content::Source<Profile>(profile),
1273       content::NotificationService::NoDetails());
1274 
1275   // At this point, the user policy service and the child account service
1276   // had enough time to initialize and should have updated the user signout
1277   // flag attached to the profile.
1278   signin_util::EnsureUserSignoutAllowedIsInitializedForProfile(profile);
1279   signin_util::EnsurePrimaryAccountAllowedForProfile(profile);
1280 
1281 #if !defined(OS_ANDROID)
1282   // The caret browsing command-line switch toggles caret browsing on
1283   // initially, but the user can still toggle it from there.
1284   if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1285           switches::kEnableCaretBrowsing))
1286     profile->GetPrefs()->SetBoolean(prefs::kCaretBrowsingEnabled, true);
1287 #endif
1288 }
1289 
DoFinalInitForServices(Profile * profile,bool go_off_the_record)1290 void ProfileManager::DoFinalInitForServices(Profile* profile,
1291                                             bool go_off_the_record) {
1292   if (!do_final_services_init_)
1293     return;
1294 
1295   TRACE_EVENT0("browser", "ProfileManager::DoFinalInitForServices");
1296 
1297 #if BUILDFLAG(ENABLE_EXTENSIONS)
1298   bool extensions_enabled = !go_off_the_record;
1299 #if defined(OS_CHROMEOS)
1300   if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1301           switches::kDisableLoginScreenApps) &&
1302       chromeos::ProfileHelper::IsSigninProfile(profile)) {
1303     extensions_enabled = true;
1304   }
1305   if (chromeos::ProfileHelper::IsLockScreenAppProfile(profile))
1306     extensions_enabled = true;
1307 #endif
1308   extensions::ExtensionSystem::Get(profile)->InitForRegularProfile(
1309       extensions_enabled);
1310 
1311   // Set the block extensions bit on the ExtensionService. There likely are no
1312   // blockable extensions to block.
1313   ProfileAttributesEntry* entry;
1314   bool has_entry = GetProfileAttributesStorage().
1315                        GetProfileAttributesWithPath(profile->GetPath(), &entry);
1316   if (has_entry && entry->IsSigninRequired()) {
1317     extensions::ExtensionSystem::Get(profile)
1318         ->extension_service()
1319         ->BlockAllExtensions();
1320   }
1321 
1322 #endif
1323 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
1324   // Initialization needs to happen after extension system initialization (for
1325   // extension::ManagementPolicy) and InitProfileUserPrefs (for setting the
1326   // initializing the supervised flag if necessary).
1327   ChildAccountServiceFactory::GetForProfile(profile)->Init();
1328   SupervisedUserServiceFactory::GetForProfile(profile)->Init();
1329 #endif
1330 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1331   // If the lock enabled algorithm changed, update this profile's lock status.
1332   // This depends on services which shouldn't be initialized until
1333   // DoFinalInitForServices.
1334   profiles::UpdateIsProfileLockEnabledIfNeeded(profile);
1335 #endif
1336 
1337   // Activate data reduction proxy. This creates a request context and makes a
1338   // URL request to check if the data reduction proxy server is reachable.
1339   DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile)->
1340       MaybeActivateDataReductionProxy(true);
1341 
1342   auto* proto_db_provider =
1343       content::BrowserContext::GetDefaultStoragePartition(profile)
1344           ->GetProtoDatabaseProvider();
1345 
1346   // Creates the Optimization Guide Keyed Service and begins loading the
1347   // hint cache from persistent memory.
1348   auto* optimization_guide_keyed_service =
1349       OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
1350   if (optimization_guide_keyed_service) {
1351     optimization_guide_keyed_service->Initialize(
1352         g_browser_process->optimization_guide_service(), proto_db_provider,
1353         profile->GetPath());
1354   }
1355 
1356   // Create the Previews Service and begin loading opt out history from
1357   // persistent memory.
1358   PreviewsServiceFactory::GetForProfile(profile)->Initialize(
1359       content::GetUIThreadTaskRunner({}), profile->GetPath());
1360 
1361   // Ensure NavigationPredictorKeyedService is started.
1362   NavigationPredictorKeyedServiceFactory::GetForProfile(profile);
1363 
1364   IdentityManagerFactory::GetForProfile(profile)->OnNetworkInitialized();
1365   AccountReconcilorFactory::GetForProfile(profile);
1366 
1367   // Initialization needs to happen after the browser context is available
1368   // because ProfileSyncService needs the URL context getter.
1369   UnifiedConsentServiceFactory::GetForProfile(profile);
1370 
1371 #if defined(OS_ANDROID)
1372   AndroidProfileSessionDurationsServiceFactory::GetForProfile(profile);
1373 #else
1374   captions::CaptionControllerFactory::GetForProfile(profile)->Init();
1375 #endif
1376 
1377 #if defined(OS_WIN) && BUILDFLAG(ENABLE_DICE_SUPPORT)
1378   signin_util::SigninWithCredentialProviderIfPossible(profile);
1379 #endif
1380 
1381   AccessibilityLabelsServiceFactory::GetForProfile(profile)->Init();
1382 
1383 #if defined(OS_CHROMEOS)
1384   chromeos::AccountManagerPolicyControllerFactory::GetForBrowserContext(
1385       profile);
1386 #endif
1387 
1388   // Creates the LiteVideo Keyed Service and begins loading the
1389   // hint cache and user blocklist.
1390   auto* lite_video_keyed_service =
1391       LiteVideoKeyedServiceFactory::GetForProfile(profile);
1392   if (lite_video_keyed_service)
1393     lite_video_keyed_service->Initialize(profile->GetPath());
1394 
1395   // TODO(crbug.com/1031477): Remove once getting this created with the browser
1396   // context does not change dependency initialization order to cause crashes.
1397   AdaptiveQuietNotificationPermissionUiEnabler::GetForProfile(profile);
1398 }
1399 
DoFinalInitLogging(Profile * profile)1400 void ProfileManager::DoFinalInitLogging(Profile* profile) {
1401   if (!do_final_services_init_)
1402     return;
1403 
1404   TRACE_EVENT0("browser", "ProfileManager::DoFinalInitLogging");
1405   // Count number of extensions in this profile.
1406   int enabled_app_count = -1;
1407 #if BUILDFLAG(ENABLE_EXTENSIONS)
1408   enabled_app_count = GetEnabledAppCount(profile);
1409 #endif
1410 
1411   // Log the profile size after a reasonable startup delay.
1412   base::ThreadPool::PostDelayedTask(
1413       FROM_HERE,
1414       {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1415        base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
1416       base::BindOnce(&ProfileSizeTask, profile->GetPath(), enabled_app_count),
1417       base::TimeDelta::FromSeconds(112));
1418 }
1419 
ProfileInfo(std::unique_ptr<Profile> profile,bool created)1420 ProfileManager::ProfileInfo::ProfileInfo(std::unique_ptr<Profile> profile,
1421                                          bool created)
1422     : profile(std::move(profile)), created(created) {}
1423 
~ProfileInfo()1424 ProfileManager::ProfileInfo::~ProfileInfo() {
1425   ProfileDestroyer::DestroyProfileWhenAppropriate(profile.release());
1426 }
1427 
GetActiveUserOrOffTheRecordProfileFromPath(const base::FilePath & user_data_dir)1428 Profile* ProfileManager::GetActiveUserOrOffTheRecordProfileFromPath(
1429     const base::FilePath& user_data_dir) {
1430 #if defined(OS_CHROMEOS)
1431   base::FilePath default_profile_dir(user_data_dir);
1432   if (!IsLoggedIn()) {
1433     default_profile_dir = profiles::GetDefaultProfileDir(user_data_dir);
1434     Profile* profile = GetProfile(default_profile_dir);
1435     // For cros, return the OTR profile so we never accidentally keep
1436     // user data in an unencrypted profile. But doing this makes
1437     // many of the browser and ui tests fail. We do return the OTR profile
1438     // if the login-profile switch is passed so that we can test this.
1439     if (ShouldGoOffTheRecord(profile))
1440       return profile->GetPrimaryOTRProfile();
1441     DCHECK(!user_manager::UserManager::Get()->IsLoggedInAsGuest());
1442     return profile;
1443   }
1444 
1445   default_profile_dir = default_profile_dir.Append(GetInitialProfileDir());
1446   ProfileInfo* profile_info = GetProfileInfoByPath(default_profile_dir);
1447   // Fallback to default off-the-record profile, if user profile has not started
1448   // loading or has not fully loaded yet.
1449   if (!profile_info || !profile_info->created)
1450     default_profile_dir = profiles::GetDefaultProfileDir(user_data_dir);
1451 
1452   Profile* profile = GetProfile(default_profile_dir);
1453   // Some unit tests didn't initialize the UserManager.
1454   if (user_manager::UserManager::IsInitialized() &&
1455       user_manager::UserManager::Get()->IsLoggedInAsGuest())
1456     return profile->GetPrimaryOTRProfile();
1457   return profile;
1458 #else
1459   base::FilePath default_profile_dir(user_data_dir);
1460   default_profile_dir = default_profile_dir.Append(GetInitialProfileDir());
1461   return GetProfile(default_profile_dir);
1462 #endif
1463 }
1464 
AddProfile(std::unique_ptr<Profile> profile)1465 bool ProfileManager::AddProfile(std::unique_ptr<Profile> profile) {
1466   TRACE_EVENT0("browser", "ProfileManager::AddProfile");
1467 
1468   DCHECK(profile);
1469 
1470   // Make sure that we're not loading a profile with the same ID as a profile
1471   // that's already loaded.
1472   if (GetProfileByPathInternal(profile->GetPath())) {
1473     NOTREACHED() << "Attempted to add profile with the same path ("
1474                  << profile->GetPath().value()
1475                  << ") as an already-loaded profile.";
1476     return false;
1477   }
1478 
1479   ProfileInfo* profile_info = RegisterProfile(std::move(profile), true);
1480   InitProfileUserPrefs(profile_info->profile.get());
1481   DoFinalInit(profile_info, ShouldGoOffTheRecord(profile_info->profile.get()));
1482   return true;
1483 }
1484 
1485 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
RemoveProfile(const base::FilePath & profile_dir)1486 void ProfileManager::RemoveProfile(const base::FilePath& profile_dir) {
1487   TRACE_EVENT0("browser", "ProfileManager::RemoveProfile");
1488 
1489   DCHECK(base::Contains(profiles_info_, profile_dir));
1490 
1491   Profile* profile = GetProfileByPath(profile_dir);
1492   bool ephemeral =
1493       profile->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1494 
1495   // Remove from |profiles_info_|, eventually causing the Profile object's
1496   // destruction.
1497   profiles_info_.erase(profile_dir);
1498 
1499   if (!ephemeral)
1500     return;
1501 
1502   // If the profile is ephemeral, also do some cleanup.
1503 
1504   // Set a new active profile.
1505   base::Optional<base::FilePath> new_active_profile_dir =
1506       FindLastActiveProfile(base::BindRepeating(
1507           [](const base::FilePath& profile_dir, ProfileAttributesEntry* entry) {
1508             return entry->GetPath() != profile_dir;
1509           },
1510           profile_dir));
1511   if (!new_active_profile_dir.has_value())
1512     new_active_profile_dir = GenerateNextProfileDirectoryPath();
1513   DCHECK(!new_active_profile_dir->empty());
1514   RemoveFromLastActiveProfilesPrefList(profile_dir);
1515   profiles::SetLastUsedProfile(
1516       new_active_profile_dir->BaseName().MaybeAsASCII());
1517 
1518   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1519   storage.RemoveProfile(profile_dir);
1520 
1521   // TODO(crbug.com/88586): There could still be pending tasks that write to
1522   // disk, and don't need the Profile. If they run after
1523   // NukeProfileFromDisk(), they may still leave files behind.
1524   base::ThreadPool::PostTask(FROM_HERE,
1525                              {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1526                               base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
1527                              base::BindOnce(&NukeProfileFromDisk, profile_dir));
1528 }
1529 #endif  // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1530 
CreateAndInitializeProfile(const base::FilePath & profile_dir)1531 Profile* ProfileManager::CreateAndInitializeProfile(
1532     const base::FilePath& profile_dir) {
1533   TRACE_EVENT0("browser", "ProfileManager::CreateAndInitializeProfile");
1534 
1535   if (!IsAllowedProfilePath(profile_dir) &&
1536       !base::CommandLine::ForCurrentProcess()->HasSwitch(
1537           switches::kAllowProfilesOutsideUserDir)) {
1538     LOG(ERROR) << "Cannot create profile at path "
1539                << profile_dir.AsUTF8Unsafe();
1540     return nullptr;
1541   }
1542 
1543   // CHECK that we are not trying to load the same profile twice, to prevent
1544   // profile corruption. Note that this check also covers the case when we have
1545   // already started loading the profile but it is not fully initialized yet,
1546   // which would make Bad Things happen if we returned it.
1547   CHECK(!GetProfileByPathInternal(profile_dir));
1548   std::unique_ptr<Profile> profile = CreateProfileHelper(profile_dir);
1549   if (!profile)
1550     return nullptr;
1551 
1552   Profile* profile_ptr = profile.get();
1553   bool result = AddProfile(std::move(profile));
1554   DCHECK(result);
1555   return profile_ptr;
1556 }
1557 
1558 #if !defined(OS_ANDROID)
EnsureActiveProfileExistsBeforeDeletion(ProfileLoadedCallback callback,const base::FilePath & profile_dir)1559 void ProfileManager::EnsureActiveProfileExistsBeforeDeletion(
1560     ProfileLoadedCallback callback,
1561     const base::FilePath& profile_dir) {
1562   // In case we delete non-active profile and current profile is valid, proceed.
1563   const base::FilePath last_used_profile_path =
1564       GetLastUsedProfileDir(user_data_dir_);
1565   const base::FilePath guest_profile_path = GetGuestProfilePath();
1566   Profile* last_used_profile = GetProfileByPath(last_used_profile_path);
1567   if (last_used_profile_path != profile_dir &&
1568       last_used_profile_path != guest_profile_path && last_used_profile &&
1569       !last_used_profile->IsLegacySupervised()) {
1570     FinishDeletingProfile(profile_dir, last_used_profile_path);
1571     return;
1572   }
1573 
1574   // Search for an active browser and use its profile as active if possible.
1575   for (Browser* browser : *BrowserList::GetInstance()) {
1576     Profile* profile = browser->profile();
1577     base::FilePath cur_path = profile->GetPath();
1578     if (cur_path != profile_dir &&
1579         cur_path != guest_profile_path &&
1580         !profile->IsLegacySupervised() &&
1581         !IsProfileDirectoryMarkedForDeletion(cur_path)) {
1582       OnNewActiveProfileLoaded(profile_dir, cur_path, std::move(callback),
1583                                profile, Profile::CREATE_STATUS_INITIALIZED);
1584       return;
1585     }
1586   }
1587 
1588   // There no valid browsers to fallback, search for any existing valid profile.
1589   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1590   base::FilePath fallback_profile_path;
1591   std::vector<ProfileAttributesEntry*> entries =
1592       storage.GetAllProfilesAttributes();
1593   for (ProfileAttributesEntry* entry : entries) {
1594     base::FilePath cur_path = entry->GetPath();
1595     // Make sure that this profile is not pending deletion, and is not
1596     // legacy-supervised.
1597     if (cur_path != profile_dir &&
1598         cur_path != guest_profile_path &&
1599         !entry->IsLegacySupervised() &&
1600         !IsProfileDirectoryMarkedForDeletion(cur_path)) {
1601       fallback_profile_path = cur_path;
1602       break;
1603     }
1604   }
1605 
1606   // If we're deleting the last (non-legacy-supervised) profile, then create a
1607   // new profile in its place. Load existing profile otherwise.
1608   std::string new_avatar_url;
1609   base::string16 new_profile_name;
1610   if (fallback_profile_path.empty()) {
1611     fallback_profile_path = GenerateNextProfileDirectoryPath();
1612 #if !defined(OS_CHROMEOS)
1613     int avatar_index = profiles::GetPlaceholderAvatarIndex();
1614     new_avatar_url = profiles::GetDefaultAvatarIconUrl(avatar_index);
1615     new_profile_name = storage.ChooseNameForNewProfile(avatar_index);
1616 #endif
1617     // A new profile about to be created.
1618     ProfileMetrics::LogProfileAddNewUser(
1619         ProfileMetrics::ADD_NEW_USER_LAST_DELETED);
1620   }
1621 
1622   // Create and/or load fallback profile.
1623   CreateProfileAsync(
1624       fallback_profile_path,
1625       base::BindRepeating(
1626           &ProfileManager::OnNewActiveProfileLoaded, base::Unretained(this),
1627           profile_dir, fallback_profile_path,
1628           // OnNewActiveProfileLoaded may be called several times, but
1629           // only once with CREATE_STATUS_INITIALIZED.
1630           base::AdaptCallbackForRepeating(std::move(callback))),
1631       new_profile_name, new_avatar_url);
1632 }
1633 
OnLoadProfileForProfileDeletion(const base::FilePath & profile_dir,Profile * profile)1634 void ProfileManager::OnLoadProfileForProfileDeletion(
1635     const base::FilePath& profile_dir,
1636     Profile* profile) {
1637   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1638   // TODO(sail): Due to bug 88586 we don't delete the profile instance. Once we
1639   // start deleting the profile instance we need to close background apps too.
1640   if (profile) {
1641     // TODO(estade): Migrate additional code in this block to observe
1642     // ProfileManager instead of handling shutdown here.
1643     for (auto& observer : observers_)
1644       observer.OnProfileMarkedForPermanentDeletion(profile);
1645 
1646     // Disable sync for doomed profile.
1647     if (ProfileSyncServiceFactory::HasSyncService(profile)) {
1648       syncer::SyncService* sync_service =
1649           ProfileSyncServiceFactory::GetForProfile(profile);
1650       // Ensure data is cleared even if sync was already off.
1651       sync_service->StopAndClear();
1652     }
1653 
1654     ProfileAttributesEntry* entry;
1655     bool has_entry = storage.GetProfileAttributesWithPath(profile_dir, &entry);
1656     DCHECK(has_entry);
1657     ProfileMetrics::LogProfileDelete(entry->IsAuthenticated());
1658     // Some platforms store passwords in keychains. They should be removed.
1659     scoped_refptr<password_manager::PasswordStore> password_store =
1660         PasswordStoreFactory::GetForProfile(profile,
1661                                             ServiceAccessType::EXPLICIT_ACCESS)
1662             .get();
1663     if (password_store.get()) {
1664       password_store->RemoveLoginsCreatedBetween(
1665           base::Time(), base::Time::Max(), base::Closure());
1666     }
1667 
1668     // The Profile Data doesn't get wiped until Chrome closes. Since we promised
1669     // that the user's data would be removed, do so immediately.
1670     profiles::RemoveBrowsingDataForProfile(profile_dir);
1671 
1672     // Clean-up pref data that won't be cleaned up by deleting the profile dir.
1673     profile->GetPrefs()->OnStoreDeletionFromDisk();
1674   } else {
1675     // We failed to load the profile, but it's safe to delete a not yet loaded
1676     // Profile from disk.
1677     base::ThreadPool::PostTask(
1678         FROM_HERE,
1679         {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
1680          base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
1681         base::BindOnce(&NukeProfileFromDisk, profile_dir));
1682   }
1683 
1684   storage.RemoveProfile(profile_dir);
1685 }
1686 
FinishDeletingProfile(const base::FilePath & profile_dir,const base::FilePath & new_active_profile_dir)1687 void ProfileManager::FinishDeletingProfile(
1688     const base::FilePath& profile_dir,
1689     const base::FilePath& new_active_profile_dir) {
1690   // Update the last used profile pref before closing browser windows. This
1691   // way the correct last used profile is set for any notification observers.
1692   profiles::SetLastUsedProfile(
1693       new_active_profile_dir.BaseName().MaybeAsASCII());
1694 
1695   // Attempt to load the profile before deleting it to properly clean up
1696   // profile-specific data stored outside the profile directory.
1697   LoadProfileByPath(
1698       profile_dir, false,
1699       base::BindOnce(&ProfileManager::OnLoadProfileForProfileDeletion,
1700                      base::Unretained(this), profile_dir));
1701 
1702   // Prevents CreateProfileAsync from re-creating the profile.
1703   MarkProfileDirectoryForDeletion(profile_dir);
1704 }
1705 
FindLastActiveProfile(base::RepeatingCallback<bool (ProfileAttributesEntry *)> predicate)1706 base::Optional<base::FilePath> ProfileManager::FindLastActiveProfile(
1707     base::RepeatingCallback<bool(ProfileAttributesEntry*)> predicate) {
1708   bool found_entry_loaded = false;
1709   ProfileAttributesEntry* found_entry = nullptr;
1710   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1711   for (ProfileAttributesEntry* entry : storage.GetAllProfilesAttributes()) {
1712     // Skip all profiles forbidden to rollback.
1713     base::FilePath entry_path = entry->GetPath();
1714     if (!predicate.Run(entry) || entry_path == GetGuestProfilePath() ||
1715         entry->IsLegacySupervised() ||
1716         IsProfileDirectoryMarkedForDeletion(entry_path))
1717       continue;
1718     // Check if |entry| preferable over |found_entry|.
1719     bool entry_loaded = !!GetProfileByPath(entry_path);
1720     if (!found_entry || (!found_entry_loaded && entry_loaded) ||
1721         found_entry->GetActiveTime() < entry->GetActiveTime()) {
1722       found_entry = entry;
1723       found_entry_loaded = entry_loaded;
1724     }
1725   }
1726   return found_entry ? base::Optional<base::FilePath>(found_entry->GetPath())
1727                      : base::nullopt;
1728 }
1729 
1730 // static
CleanUpGuestProfile()1731 void ProfileManager::CleanUpGuestProfile() {
1732 // ChromeOS handles guest data independently.
1733 #if !defined(OS_CHROMEOS)
1734   ProfileManager* profile_manager = g_browser_process->profile_manager();
1735 
1736   Profile* profile =
1737       profile_manager->GetProfileByPath(profile_manager->GetGuestProfilePath());
1738   if (profile) {
1739     // Clear all browsing data once a Guest Session completes. The Guest
1740     // profile has BrowserContextKeyedServices that the ProfileDestroyer
1741     // can't delete it properly.
1742     // TODO(https://crbug.com/88586): Delete the guest when regular profiles
1743     // become deletable when not needed.
1744     profiles::RemoveBrowsingDataForProfile(GetGuestProfilePath());
1745   }
1746   profile_manager->guest_profile_path_.clear();
1747 #endif  //! defined(OS_CHROMEOS)
1748 }
1749 
1750 #endif  // !defined(OS_ANDROID)
1751 
RegisterProfile(std::unique_ptr<Profile> profile,bool created)1752 ProfileManager::ProfileInfo* ProfileManager::RegisterProfile(
1753     std::unique_ptr<Profile> profile,
1754     bool created) {
1755   TRACE_EVENT0("browser", "ProfileManager::RegisterProfile");
1756   base::FilePath path = profile->GetPath();
1757   auto info = std::make_unique<ProfileInfo>(std::move(profile), created);
1758   ProfileInfo* info_raw = info.get();
1759   profiles_info_.insert(std::make_pair(path, std::move(info)));
1760   return info_raw;
1761 }
1762 
GetProfileInfoByPath(const base::FilePath & path) const1763 ProfileManager::ProfileInfo* ProfileManager::GetProfileInfoByPath(
1764     const base::FilePath& path) const {
1765   auto it = profiles_info_.find(path);
1766   return it != profiles_info_.end() ? it->second.get() : nullptr;
1767 }
1768 
AddProfileToStorage(Profile * profile)1769 void ProfileManager::AddProfileToStorage(Profile* profile) {
1770   TRACE_EVENT0("browser", "ProfileManager::AddProfileToCache");
1771   if (profile->IsGuestSession() || profile->IsSystemProfile())
1772     return;
1773   if (!IsAllowedProfilePath(profile->GetPath())) {
1774     LOG(WARNING) << "Failed to add to storage a profile at invalid path: "
1775                  << profile->GetPath().AsUTF8Unsafe();
1776     return;
1777   }
1778 
1779   signin::IdentityManager* identity_manager =
1780       IdentityManagerFactory::GetForProfile(profile);
1781   bool is_consented_primary_account = identity_manager->HasPrimaryAccount();
1782   CoreAccountInfo account_info = identity_manager->GetPrimaryAccountInfo(
1783       signin::ConsentLevel::kNotRequired);
1784 
1785   base::string16 username = base::UTF8ToUTF16(account_info.email);
1786 
1787   ProfileAttributesStorage& storage = GetProfileAttributesStorage();
1788   // |entry| and |has_entry| below are put inside a pair of brackets for
1789   // scoping, to avoid potential clashes of variable names.
1790   {
1791     ProfileAttributesEntry* entry;
1792     bool has_entry = storage.GetProfileAttributesWithPath(profile->GetPath(),
1793                                                           &entry);
1794     if (has_entry) {
1795 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1796       bool was_authenticated_status = entry->IsAuthenticated();
1797 #endif
1798       // The ProfileAttributesStorage's info must match the Identity Manager.
1799       entry->SetAuthInfo(account_info.gaia, username,
1800                          is_consented_primary_account);
1801 
1802       entry->SetSignedInWithCredentialProvider(profile->GetPrefs()->GetBoolean(
1803           prefs::kSignedInWithCredentialProvider));
1804 
1805 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
1806       // Sign out if force-sign-in policy is enabled and profile is not signed
1807       // in.
1808       VLOG(1) << "ForceSigninCheck: " << signin_util::IsForceSigninEnabled()
1809               << ", " << was_authenticated_status << ", "
1810               << !entry->IsAuthenticated();
1811       if (signin_util::IsForceSigninEnabled() && was_authenticated_status &&
1812           !entry->IsAuthenticated()) {
1813         auto* account_mutator = identity_manager->GetPrimaryAccountMutator();
1814 
1815         // GetPrimaryAccountMutator() returns nullptr on ChromeOS only.
1816         DCHECK(account_mutator);
1817         content::GetUIThreadTaskRunner({})->PostTask(
1818             FROM_HERE,
1819             base::BindOnce(
1820                 base::IgnoreResult(
1821                     &signin::PrimaryAccountMutator::ClearPrimaryAccount),
1822                 base::Unretained(account_mutator),
1823                 signin::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll,
1824                 signin_metrics::AUTHENTICATION_FAILED_WITH_FORCE_SIGNIN,
1825                 signin_metrics::SignoutDelete::IGNORE_METRIC));
1826       }
1827 #endif
1828       return;
1829     }
1830   }
1831 
1832   // Profile name and avatar are set by InitProfileUserPrefs and stored in the
1833   // profile. Use those values to setup the entry in profile attributes storage.
1834   base::string16 profile_name =
1835       base::UTF8ToUTF16(profile->GetPrefs()->GetString(prefs::kProfileName));
1836 
1837   size_t icon_index =
1838       profile->GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
1839 
1840   std::string supervised_user_id =
1841       profile->GetPrefs()->GetString(prefs::kSupervisedUserId);
1842 
1843   AccountId account_id(EmptyAccountId());
1844 #if defined(OS_CHROMEOS)
1845   user_manager::User* user =
1846       chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
1847   if (user)
1848     account_id = user->GetAccountId();
1849 #endif
1850 
1851   storage.AddProfile(profile->GetPath(), profile_name, account_info.gaia,
1852                      username, is_consented_primary_account, icon_index,
1853                      supervised_user_id, account_id);
1854 
1855   ProfileAttributesEntry* entry;
1856   bool has_entry =
1857       storage.GetProfileAttributesWithPath(profile->GetPath(), &entry);
1858   DCHECK(has_entry);
1859 
1860   if (profile->IsEphemeralGuestProfile())
1861     profile->GetPrefs()->SetBoolean(prefs::kForceEphemeralProfiles, true);
1862 
1863   if (profile->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles))
1864     entry->SetIsEphemeral(true);
1865 
1866   entry->SetSignedInWithCredentialProvider(
1867       profile->GetPrefs()->GetBoolean(prefs::kSignedInWithCredentialProvider));
1868 }
1869 
SetNonPersonalProfilePrefs(Profile * profile)1870 void ProfileManager::SetNonPersonalProfilePrefs(Profile* profile) {
1871   PrefService* prefs = profile->GetPrefs();
1872   prefs->SetBoolean(prefs::kSigninAllowed, false);
1873   prefs->SetBoolean(bookmarks::prefs::kEditBookmarksEnabled, false);
1874   prefs->SetBoolean(bookmarks::prefs::kShowBookmarkBar, false);
1875   prefs->ClearPref(DefaultSearchManager::kDefaultSearchProviderDataPrefName);
1876 }
1877 
ShouldGoOffTheRecord(Profile * profile)1878 bool ProfileManager::ShouldGoOffTheRecord(Profile* profile) {
1879 #if defined(OS_CHROMEOS)
1880   if (chromeos::ProfileHelper::IsSigninProfile(profile) ||
1881       chromeos::ProfileHelper::IsLockScreenAppProfile(profile)) {
1882     return true;
1883   }
1884 #endif
1885   return profile->IsGuestSession() || profile->IsSystemProfile();
1886 }
1887 
RunCallbacks(const std::vector<CreateCallback> & callbacks,Profile * profile,Profile::CreateStatus status)1888 void ProfileManager::RunCallbacks(const std::vector<CreateCallback>& callbacks,
1889                                   Profile* profile,
1890                                   Profile::CreateStatus status) {
1891   for (size_t i = 0; i < callbacks.size(); ++i)
1892     callbacks[i].Run(profile, status);
1893 }
1894 
SaveActiveProfiles()1895 void ProfileManager::SaveActiveProfiles() {
1896   PrefService* local_state = g_browser_process->local_state();
1897   DCHECK(local_state);
1898   ListPrefUpdate update(local_state, prefs::kProfilesLastActive);
1899   base::ListValue* profile_list = update.Get();
1900 
1901   profile_list->Clear();
1902 
1903   // crbug.com/120112 -> several non-off-the-record profiles might have the same
1904   // GetPath().BaseName(). In that case, we cannot restore both
1905   // profiles. Include each base name only once in the last active profile
1906   // list.
1907   std::set<std::string> profile_paths;
1908   std::vector<Profile*>::const_iterator it;
1909   for (it = active_profiles_.begin(); it != active_profiles_.end(); ++it) {
1910     // crbug.com/823338 -> CHECK that the profiles aren't guest or incognito,
1911     // causing a crash during session restore.
1912     CHECK((!(*it)->IsGuestSession()) && (!(*it)->IsEphemeralGuestProfile()))
1913         << "Guest profiles shouldn't be saved as active profiles";
1914     CHECK(!(*it)->IsOffTheRecord())
1915         << "OTR profiles shouldn't be saved as active profiles";
1916     std::string profile_path = (*it)->GetPath().BaseName().MaybeAsASCII();
1917     // Some profiles might become ephemeral after they are created.
1918     // Don't persist the System Profile as one of the last actives, it should
1919     // never get a browser.
1920     if (!(*it)->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles) &&
1921         profile_paths.find(profile_path) == profile_paths.end() &&
1922         profile_path !=
1923             base::FilePath(chrome::kSystemProfileDir).AsUTF8Unsafe()) {
1924       profile_paths.insert(profile_path);
1925       profile_list->AppendString(profile_path);
1926     }
1927   }
1928 }
1929 
1930 #if !defined(OS_ANDROID)
OnBrowserOpened(Browser * browser)1931 void ProfileManager::OnBrowserOpened(Browser* browser) {
1932   DCHECK(browser);
1933   Profile* profile = browser->profile();
1934   DCHECK(profile);
1935   bool is_ephemeral =
1936       profile->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
1937   if (!profile->IsOffTheRecord() && !is_ephemeral &&
1938       ++browser_counts_[profile] == 1) {
1939     active_profiles_.push_back(profile);
1940     SaveActiveProfiles();
1941   }
1942   // If browsers are opening, we can't be closing all the browsers. This
1943   // can happen if the application was exited, but background mode or
1944   // packaged apps prevented the process from shutting down, and then
1945   // a new browser window was opened.
1946   closing_all_browsers_ = false;
1947 }
1948 
OnBrowserClosed(Browser * browser)1949 void ProfileManager::OnBrowserClosed(Browser* browser) {
1950   Profile* profile = browser->profile();
1951   DCHECK(profile);
1952   if (!profile->IsOffTheRecord() && --browser_counts_[profile] == 0) {
1953     active_profiles_.erase(
1954         std::find(active_profiles_.begin(), active_profiles_.end(), profile));
1955     if (!closing_all_browsers_)
1956       SaveActiveProfiles();
1957   }
1958 
1959   Profile* original_profile = profile->GetOriginalProfile();
1960   // Do nothing if the closed window is not the last window of the same profile.
1961   for (auto* browser_iter : *BrowserList::GetInstance()) {
1962     if (browser_iter->profile()->GetOriginalProfile() == original_profile)
1963       return;
1964   }
1965 
1966   if (profile->IsGuestSession() || profile->IsEphemeralGuestProfile())
1967     CleanUpGuestProfile();
1968 
1969 #if !defined(OS_CHROMEOS)
1970   ProfileAttributesEntry* entry;
1971   bool background_mode =
1972       GetProfileAttributesStorage().GetProfileAttributesWithPath(
1973           profile->GetPath(), &entry) &&
1974       entry->GetBackgroundStatus();
1975   if (base::FeatureList::IsEnabled(features::kDestroyProfileOnBrowserClose) &&
1976       !profile->IsOffTheRecord() &&
1977       !background_mode) {
1978     // Post this to a task, so other OnBrowserClosed() hooks and the destructor
1979     // for Browser have time to run before we destroy the Profile.
1980     content::GetUIThreadTaskRunner({})->PostTask(
1981         FROM_HERE, base::BindOnce(&ProfileManager::RemoveProfile,
1982                                   base::Unretained(this), profile->GetPath()));
1983     return;
1984   }
1985 #endif
1986 
1987   base::FilePath path = profile->GetPath();
1988   if (IsProfileDirectoryMarkedForDeletion(path)) {
1989     // Do nothing if the profile is already being deleted.
1990   } else if (profile->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles)) {
1991     // Avoid scheduling deletion if it's a testing profile that is not
1992     // registered with profile manager.
1993     if (profile->AsTestingProfile() &&
1994         !IsRegisteredAsEphemeral(&GetProfileAttributesStorage(), path)) {
1995       return;
1996     }
1997     // Delete if the profile is an ephemeral profile.
1998     ScheduleForcedEphemeralProfileForDeletion(path);
1999   }
2000 }
2001 
UpdateLastUser(Profile * last_active)2002 void ProfileManager::UpdateLastUser(Profile* last_active) {
2003   // The profile may incorrectly become "active" during its destruction, caused
2004   // by the UI teardown. See https://crbug.com/1073451
2005   if (IsProfileDirectoryMarkedForDeletion(last_active->GetPath()))
2006     return;
2007 
2008   PrefService* local_state = g_browser_process->local_state();
2009   DCHECK(local_state);
2010   // Only keep track of profiles that we are managing; tests may create others.
2011   // Also never consider the SystemProfile as "active".
2012   if (profiles_info_.find(last_active->GetPath()) != profiles_info_.end() &&
2013       !last_active->IsSystemProfile()) {
2014     std::string profile_path_base =
2015         last_active->GetPath().BaseName().MaybeAsASCII();
2016     if (profile_path_base != GetLastUsedProfileName())
2017       profiles::SetLastUsedProfile(profile_path_base);
2018 
2019     ProfileAttributesEntry* entry;
2020     if (GetProfileAttributesStorage().
2021             GetProfileAttributesWithPath(last_active->GetPath(), &entry)) {
2022       entry->SetActiveTimeToNow();
2023     }
2024   }
2025 }
2026 
BrowserListObserver(ProfileManager * manager)2027 ProfileManager::BrowserListObserver::BrowserListObserver(
2028     ProfileManager* manager)
2029     : profile_manager_(manager) {
2030   BrowserList::AddObserver(this);
2031 }
2032 
~BrowserListObserver()2033 ProfileManager::BrowserListObserver::~BrowserListObserver() {
2034   BrowserList::RemoveObserver(this);
2035 }
2036 
OnBrowserAdded(Browser * browser)2037 void ProfileManager::BrowserListObserver::OnBrowserAdded(Browser* browser) {
2038   profile_manager_->OnBrowserOpened(browser);
2039 }
2040 
OnBrowserRemoved(Browser * browser)2041 void ProfileManager::BrowserListObserver::OnBrowserRemoved(
2042     Browser* browser) {
2043   profile_manager_->OnBrowserClosed(browser);
2044 }
2045 
OnBrowserSetLastActive(Browser * browser)2046 void ProfileManager::BrowserListObserver::OnBrowserSetLastActive(
2047     Browser* browser) {
2048   // If all browsers are being closed (e.g. the user is in the process of
2049   // shutting down), this event will be fired after each browser is
2050   // closed. This does not represent a user intention to change the active
2051   // browser so is not handled here.
2052   if (profile_manager_->closing_all_browsers_)
2053     return;
2054 
2055   Profile* last_active = browser->profile();
2056 
2057   // Don't remember ephemeral profiles as last because they are not going to
2058   // persist after restart.
2059   if (last_active->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles))
2060     return;
2061 
2062   profile_manager_->UpdateLastUser(last_active);
2063 }
2064 
OnNewActiveProfileLoaded(const base::FilePath & profile_to_delete_path,const base::FilePath & new_active_profile_path,ProfileLoadedCallback callback,Profile * loaded_profile,Profile::CreateStatus status)2065 void ProfileManager::OnNewActiveProfileLoaded(
2066     const base::FilePath& profile_to_delete_path,
2067     const base::FilePath& new_active_profile_path,
2068     ProfileLoadedCallback callback,
2069     Profile* loaded_profile,
2070     Profile::CreateStatus status) {
2071   DCHECK(status != Profile::CREATE_STATUS_LOCAL_FAIL &&
2072          status != Profile::CREATE_STATUS_REMOTE_FAIL);
2073 
2074   // Only run the code if the profile initialization has finished completely.
2075   if (status != Profile::CREATE_STATUS_INITIALIZED)
2076     return;
2077 
2078   if (IsProfileDirectoryMarkedForDeletion(new_active_profile_path)) {
2079     // If the profile we tried to load as the next active profile has been
2080     // deleted, then retry deleting this profile to redo the logic to load
2081     // the next available profile.
2082     EnsureActiveProfileExistsBeforeDeletion(std::move(callback),
2083                                             profile_to_delete_path);
2084     return;
2085   }
2086 
2087   FinishDeletingProfile(profile_to_delete_path, new_active_profile_path);
2088   std::move(callback).Run(loaded_profile);
2089 }
2090 
ScheduleForcedEphemeralProfileForDeletion(const base::FilePath & profile_dir)2091 void ProfileManager::ScheduleForcedEphemeralProfileForDeletion(
2092     const base::FilePath& profile_dir) {
2093   DCHECK_EQ(0u, chrome::GetBrowserCount(GetProfileByPath(profile_dir)));
2094   DCHECK(IsRegisteredAsEphemeral(&GetProfileAttributesStorage(), profile_dir));
2095 
2096   base::Optional<base::FilePath> new_active_profile_dir =
2097       FindLastActiveProfile(base::BindRepeating(
2098           [](const base::FilePath& profile_dir, ProfileAttributesEntry* entry) {
2099             return entry->GetPath() != profile_dir;
2100           },
2101           profile_dir));
2102   if (!new_active_profile_dir.has_value())
2103     new_active_profile_dir = GenerateNextProfileDirectoryPath();
2104   DCHECK(!new_active_profile_dir->empty());
2105   RemoveFromLastActiveProfilesPrefList(profile_dir);
2106 
2107   FinishDeletingProfile(profile_dir, new_active_profile_dir.value());
2108 }
2109 #endif  // !defined(OS_ANDROID)
2110 
ProfileManagerWithoutInit(const base::FilePath & user_data_dir)2111 ProfileManagerWithoutInit::ProfileManagerWithoutInit(
2112     const base::FilePath& user_data_dir) : ProfileManager(user_data_dir) {
2113   set_do_final_services_init(false);
2114 }
2115