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 // This class keeps track of the currently-active profiles in the runtime. 6 7 #ifndef CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_ 8 #define CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_ 9 10 #include <stddef.h> 11 12 #include <list> 13 #include <map> 14 #include <memory> 15 #include <string> 16 #include <vector> 17 18 #include "base/files/file_path.h" 19 #include "base/gtest_prod_util.h" 20 #include "base/observer_list.h" 21 #include "base/threading/thread_checker.h" 22 #include "build/build_config.h" 23 #include "chrome/browser/profiles/profile.h" 24 #include "chrome/browser/profiles/profile_metrics.h" 25 #include "chrome/browser/profiles/profile_shortcut_manager.h" 26 #include "chrome/common/buildflags.h" 27 #include "content/public/browser/notification_observer.h" 28 #include "content/public/browser/notification_registrar.h" 29 30 #if !defined(OS_ANDROID) 31 #include "chrome/browser/ui/browser_list_observer.h" 32 #endif // !defined(OS_ANDROID) 33 34 class ProfileAttributesStorage; 35 class ProfileInfoCache; 36 class ProfileManagerObserver; 37 38 // Manages the lifecycle of Profile objects. 39 // 40 // Note that the Profile objects may be destroyed when their last browser window 41 // is closed. The DestroyProfileOnBrowserClose flag controls this behavior. 42 class ProfileManager : public content::NotificationObserver, 43 public Profile::Delegate { 44 public: 45 using CreateCallback = 46 base::RepeatingCallback<void(Profile*, Profile::CreateStatus)>; 47 using ProfileLoadedCallback = base::OnceCallback<void(Profile*)>; 48 49 explicit ProfileManager(const base::FilePath& user_data_dir); 50 ProfileManager(const ProfileManager&) = delete; 51 ProfileManager& operator=(const ProfileManager&) = delete; 52 ~ProfileManager() override; 53 54 #if BUILDFLAG(ENABLE_SESSION_SERVICE) 55 // Invokes SessionServiceFactory::ShutdownForProfile() for all profiles. 56 static void ShutdownSessionServices(); 57 #endif 58 59 // Physically remove deleted profile directories from disk. 60 static void NukeDeletedProfilesFromDisk(); 61 62 // Same as instance method but provides the default user_data_dir as well. 63 // If the Profile is going to be used to open a new window then consider using 64 // GetLastUsedProfileAllowedByPolicy() instead. 65 // Except in ChromeOS guest sessions, the returned profile is always a regular 66 // profile (non-OffTheRecord). 67 static Profile* GetLastUsedProfile(); 68 69 // Same as GetLastUsedProfile() but returns the incognito Profile if 70 // incognito mode is forced. This should be used if the last used Profile 71 // will be used to open new browser windows. 72 static Profile* GetLastUsedProfileAllowedByPolicy(); 73 74 // Helper function that returns true if OffTheRecord mode is forced for 75 // |profile| (normal mode is not available for browsing). 76 static bool IsOffTheRecordModeForced(Profile* profile); 77 78 // Same as instance method but provides the default user_data_dir as well. 79 static std::vector<Profile*> GetLastOpenedProfiles(); 80 81 // Get the profile for the user which created the current session. 82 // Note that in case of a guest account this will return a 'suitable' profile. 83 static Profile* GetPrimaryUserProfile(); 84 85 // Get the profile for the currently active user. 86 // Note that in case of a guest account this will return a 'suitable' profile. 87 static Profile* GetActiveUserProfile(); 88 89 // Load and return the initial profile for browser. On ChromeOS, this returns 90 // either the sign-in profile or the active user profile depending on whether 91 // browser is started normally or is restarted after crash. On other 92 // platforms, this returns the default profile. 93 static Profile* CreateInitialProfile(); 94 95 void AddObserver(ProfileManagerObserver* observer); 96 void RemoveObserver(ProfileManagerObserver* observer); 97 98 // Returns a profile for a specific profile directory within the user data 99 // dir. This will return an existing profile it had already been created, 100 // otherwise it will create and manage it. 101 // Because this method might synchronously create a new profile, it should 102 // only be called for the initial profile or in tests, where blocking is 103 // acceptable. Returns null if creation of the new profile fails. 104 // TODO(bauerb): Migrate calls from other code to GetProfileByPath(), then 105 // make this method private. 106 Profile* GetProfile(const base::FilePath& profile_dir); 107 108 // Returns regular or off-the-record profile given its profile key. 109 static Profile* GetProfileFromProfileKey(ProfileKey* profile_key); 110 111 // Returns total number of profiles available on this machine. 112 size_t GetNumberOfProfiles(); 113 114 // Asynchronously loads an existing profile given its |profile_name| within 115 // the user data directory, optionally in |incognito| mode. The |callback| 116 // will be called with the Profile when it has been loaded, or with a nullptr 117 // otherwise. Should be called on the UI thread. 118 // Unlike CreateProfileAsync this will not create a profile if one doesn't 119 // already exist on disk 120 // Returns true if the profile exists, but the final loaded profile will come 121 // as part of the callback. 122 bool LoadProfile(const std::string& profile_name, 123 bool incognito, 124 ProfileLoadedCallback callback); 125 bool LoadProfileByPath(const base::FilePath& profile_path, 126 bool incognito, 127 ProfileLoadedCallback callback); 128 129 // Explicit asynchronous creation of a profile located at |profile_path|. 130 // If the profile has already been created then callback is called 131 // immediately. Should be called on the UI thread. 132 void CreateProfileAsync(const base::FilePath& profile_path, 133 const CreateCallback& callback, 134 const base::string16& name, 135 const std::string& icon_url); 136 137 // Returns true if the profile pointer is known to point to an existing 138 // profile. 139 bool IsValidProfile(const void* profile); 140 141 // Returns the directory where the first created profile is stored, 142 // relative to the user data directory currently in use. 143 base::FilePath GetInitialProfileDir(); 144 145 // Get the Profile last used (the Profile to which owns the most recently 146 // focused window) with this Chrome build. If no signed profile has been 147 // stored in Local State, hand back the Default profile. 148 Profile* GetLastUsedProfile(const base::FilePath& user_data_dir); 149 150 // Get the path of the last used profile, or if that's undefined, the default 151 // profile. 152 base::FilePath GetLastUsedProfileDir(const base::FilePath& user_data_dir); 153 154 // Get the name of the last used profile, or if that's undefined, the default 155 // profile. 156 std::string GetLastUsedProfileName(); 157 158 // Get the Profiles which are currently open, i.e. have open browsers or were 159 // open the last time Chrome was running. Profiles that fail to initialize are 160 // skipped. The Profiles appear in the order they were opened. The last used 161 // profile will be on the list if it is initialized successfully, but its 162 // index on the list will depend on when it was opened (it is not necessarily 163 // the last one). 164 std::vector<Profile*> GetLastOpenedProfiles( 165 const base::FilePath& user_data_dir); 166 167 // Returns created and fully initialized profiles. Note, profiles order is NOT 168 // guaranteed to be related with the creation order. 169 std::vector<Profile*> GetLoadedProfiles() const; 170 171 // If a profile with the given path is currently managed by this object and 172 // fully initialized, return a pointer to the corresponding Profile object; 173 // otherwise return null. 174 Profile* GetProfileByPath(const base::FilePath& path) const; 175 176 // Creates a new profile in the next available multiprofile directory. 177 // Directories are named "profile_1", "profile_2", etc., in sequence of 178 // creation. (Because directories can be removed, however, it may be the case 179 // that at some point the list of numbered profiles is not continuous.) 180 // |callback| may be invoked multiple times (for CREATE_STATUS_INITIALIZED 181 // and CREATE_STATUS_CREATED) so binding parameters with bind::Passed() is 182 // prohibited. Returns the file path to the profile that will be created 183 // asynchronously. 184 static base::FilePath CreateMultiProfileAsync(const base::string16& name, 185 const std::string& icon_url, 186 const CreateCallback& callback); 187 188 // Returns the full path to be used for guest profiles. 189 static base::FilePath GetGuestProfilePath(); 190 191 // Returns the full path to be used for system profiles. 192 static base::FilePath GetSystemProfilePath(); 193 194 // Get the path of the next profile directory and increment the internal 195 // count. 196 // Lack of side effects: 197 // This function doesn't actually create the directory or touch the file 198 // system. 199 base::FilePath GenerateNextProfileDirectoryPath(); 200 201 // Returns a ProfileAttributesStorage object which can be used to get 202 // information about profiles without having to load them from disk. 203 ProfileAttributesStorage& GetProfileAttributesStorage(); 204 205 // Returns a ProfileShortcut Manager that enables the caller to create 206 // profile specfic desktop shortcuts. 207 ProfileShortcutManager* profile_shortcut_manager(); 208 209 #if !defined(OS_ANDROID) 210 // Less strict version of ScheduleProfileForDeletion(), silently exits if 211 // profile is either scheduling or marked for deletion. 212 void MaybeScheduleProfileForDeletion( 213 const base::FilePath& profile_dir, 214 ProfileLoadedCallback callback, 215 ProfileMetrics::ProfileDelete deletion_source); 216 217 // Schedules the profile at the given path to be deleted on shutdown. If we're 218 // deleting the last profile, a new one will be created in its place, and in 219 // that case the callback will be called when profile creation is complete. 220 void ScheduleProfileForDeletion(const base::FilePath& profile_dir, 221 ProfileLoadedCallback callback); 222 223 // Deletes Guest profile's browsing data. 224 static void CleanUpGuestProfile(); 225 #endif 226 227 // Returns if profile is marked for deletion. 228 static bool IsProfileDirectoryMarkedForDeletion( 229 const base::FilePath& profile_dir); 230 231 // Autoloads profiles if they are running background apps. 232 void AutoloadProfiles(); 233 234 // Checks if any ephemeral profiles are left behind (e.g. because of a browser 235 // crash) and schedule them for deletion. 236 void CleanUpEphemeralProfiles(); 237 238 // Checks if files of deleted profiles are left behind (e.g. because of a 239 // browser crash) and delete them in case they still exist. 240 void CleanUpDeletedProfiles(); 241 242 // Initializes user prefs of |profile|. This includes profile name and 243 // avatar values. 244 void InitProfileUserPrefs(Profile* profile); 245 246 // Register and add testing profile to the ProfileManager. Use ONLY in tests. 247 // This allows the creation of Profiles outside of the standard creation path 248 // for testing. If |addToStorage|, adds to ProfileAttributesStorage as well. 249 // Use ONLY in tests. 250 void RegisterTestingProfile(std::unique_ptr<Profile> profile, 251 bool add_to_storage); 252 user_data_dir()253 const base::FilePath& user_data_dir() const { return user_data_dir_; } 254 255 // content::NotificationObserver implementation. 256 void Observe(int type, 257 const content::NotificationSource& source, 258 const content::NotificationDetails& details) override; 259 260 // Profile::Delegate implementation: 261 void OnProfileCreated(Profile* profile, 262 bool success, 263 bool is_new_profile) override; 264 265 protected: 266 // Creates a new profile by calling into the profile's profile creation 267 // method. Virtual so that unittests can return a TestingProfile instead 268 // of the Profile's result. Returns null if creation fails. 269 virtual std::unique_ptr<Profile> CreateProfileHelper( 270 const base::FilePath& path); 271 272 // Creates a new profile asynchronously by calling into the profile's 273 // asynchronous profile creation method. Virtual so that unittests can return 274 // a TestingProfile instead of the Profile's result. 275 virtual std::unique_ptr<Profile> CreateProfileAsyncHelper( 276 const base::FilePath& path, 277 Delegate* delegate); 278 set_do_final_services_init(bool do_final_services_init)279 void set_do_final_services_init(bool do_final_services_init) { 280 do_final_services_init_ = do_final_services_init; 281 } 282 283 private: 284 friend class TestingProfileManager; 285 FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, DeleteAllProfiles); 286 FRIEND_TEST_ALL_PREFIXES(ProfileManagerBrowserTest, SwitchToProfile); 287 288 // This struct contains information about profiles which are being loaded or 289 // were loaded. 290 struct ProfileInfo { 291 ProfileInfo(std::unique_ptr<Profile> profile, bool created); 292 ProfileInfo(const ProfileInfo&) = delete; 293 ProfileInfo& operator=(const ProfileInfo&) = delete; 294 ~ProfileInfo(); 295 296 std::unique_ptr<Profile> profile; 297 // Whether profile has been fully loaded (created and initialized). 298 bool created; 299 // List of callbacks to run when profile initialization is done. Note, when 300 // profile is fully loaded this vector will be empty. 301 std::vector<CreateCallback> callbacks; 302 }; 303 304 // Does final initial actions. 305 void DoFinalInit(ProfileInfo* profile_info, bool go_off_the_record); 306 void DoFinalInitForServices(Profile* profile, bool go_off_the_record); 307 void DoFinalInitLogging(Profile* profile); 308 309 // Returns the profile of the active user and / or the off the record profile 310 // if needed. This adds the profile to the ProfileManager if it doesn't 311 // already exist. The method will return NULL if the profile doesn't exist 312 // and we can't create it. 313 // The profile used can be overridden by using --login-profile on cros. 314 Profile* GetActiveUserOrOffTheRecordProfileFromPath( 315 const base::FilePath& user_data_dir); 316 317 // Adds a pre-existing Profile object to the set managed by this 318 // ProfileManager. 319 // The Profile should not already be managed by this ProfileManager. 320 // Returns true if the profile was added, false otherwise. 321 bool AddProfile(std::unique_ptr<Profile> profile); 322 323 #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) 324 // Removes the Profile at |profile_dir| from the manager and destroys it. If 325 // it's an ephemeral profile, also nuke the |profile_dir| directory from disk 326 // afterwards. 327 void RemoveProfile(const base::FilePath& profile_dir); 328 #endif 329 330 // Synchronously creates and returns a profile. This handles both the full 331 // creation and adds it to the set managed by this ProfileManager. Returns 332 // null if creation fails. 333 Profile* CreateAndInitializeProfile(const base::FilePath& profile_dir); 334 335 #if !defined(OS_ANDROID) 336 // Continues the scheduled profile deletion after closing all the profile's 337 // browsers tabs. Creates a new profile if the profile to be deleted is the 338 // last non-supervised profile. In the Mac, loads the next non-supervised 339 // profile if the profile to be deleted is the active profile. 340 void EnsureActiveProfileExistsBeforeDeletion( 341 ProfileLoadedCallback callback, 342 const base::FilePath& profile_dir); 343 344 // Schedules the profile at the given path to be deleted on shutdown, 345 // and marks the new profile as active. 346 void FinishDeletingProfile(const base::FilePath& profile_dir, 347 const base::FilePath& new_active_profile_dir); 348 void OnLoadProfileForProfileDeletion(const base::FilePath& profile_dir, 349 Profile* profile); 350 351 // Searches for the latest active profile that respects |predicate|, already 352 // loaded preferably. Returns nullopt if no existing profile respects all the 353 // conditions. 354 base::Optional<base::FilePath> FindLastActiveProfile( 355 base::RepeatingCallback<bool(ProfileAttributesEntry*)> predicate); 356 #endif 357 358 // Registers profile with given info. Returns pointer to created ProfileInfo 359 // entry. 360 ProfileInfo* RegisterProfile(std::unique_ptr<Profile> profile, bool created); 361 362 // Returns ProfileInfo associated with given |path|, registered earlier with 363 // RegisterProfile. 364 ProfileInfo* GetProfileInfoByPath(const base::FilePath& path) const; 365 366 // Returns a registered profile. In contrast to GetProfileByPath(), this will 367 // also return a profile that is not fully initialized yet, so this method 368 // should be used carefully. 369 Profile* GetProfileByPathInternal(const base::FilePath& path) const; 370 371 // Returns whether |path| is allowed for profile creation. 372 bool IsAllowedProfilePath(const base::FilePath& path) const; 373 374 // Returns a ProfileInfoCache object which can be used to get information 375 // about profiles without having to load them from disk. 376 // Deprecated, use GetProfileAttributesStorage() instead. 377 ProfileInfoCache& GetProfileInfoCache(); 378 379 // Adds |profile| to the profile attributes storage if it hasn't been added 380 // yet. 381 void AddProfileToStorage(Profile* profile); 382 383 // Apply settings for profiles created by the system rather than users: The 384 // (desktop) Guest User profile and (desktop) System Profile. 385 void SetNonPersonalProfilePrefs(Profile* profile); 386 387 // Determines if profile should be OTR. 388 bool ShouldGoOffTheRecord(Profile* profile); 389 390 void RunCallbacks(const std::vector<CreateCallback>& callbacks, 391 Profile* profile, 392 Profile::CreateStatus status); 393 394 void SaveActiveProfiles(); 395 396 #if !defined(OS_ANDROID) 397 void OnBrowserOpened(Browser* browser); 398 void OnBrowserClosed(Browser* browser); 399 400 // Updates the last active user of the current session. 401 // On Chrome OS updating this user will have no effect since when browser is 402 // restored after crash there's another preference that is taken into account. 403 // See kLastActiveUser in UserManagerBase. 404 void UpdateLastUser(Profile* last_active); 405 406 class BrowserListObserver : public ::BrowserListObserver { 407 public: 408 explicit BrowserListObserver(ProfileManager* manager); 409 BrowserListObserver(const BrowserListObserver&) = delete; 410 BrowserListObserver& operator=(const BrowserListObserver&) = delete; 411 ~BrowserListObserver() override; 412 413 // ::BrowserListObserver implementation. 414 void OnBrowserAdded(Browser* browser) override; 415 void OnBrowserRemoved(Browser* browser) override; 416 void OnBrowserSetLastActive(Browser* browser) override; 417 418 private: 419 ProfileManager* profile_manager_; 420 }; 421 422 // If the |loaded_profile| has been loaded successfully (according to 423 // |status|) and isn't already scheduled for deletion, then finishes adding 424 // |profile_to_delete_dir| to the queue of profiles to be deleted, and updates 425 // the kProfileLastUsed preference based on 426 // |last_non_supervised_profile_path|. 427 void OnNewActiveProfileLoaded( 428 const base::FilePath& profile_to_delete_path, 429 const base::FilePath& last_non_supervised_profile_path, 430 ProfileLoadedCallback callback, 431 Profile* loaded_profile, 432 Profile::CreateStatus status); 433 434 // Schedules the forced ephemeral profile at the given path to be deleted on 435 // shutdown. New profiles will not be created. 436 void ScheduleForcedEphemeralProfileForDeletion( 437 const base::FilePath& profile_dir); 438 #endif // !defined(OS_ANDROID) 439 440 // Destroy after |profile_info_cache_| since Profile destruction may trigger 441 // some observers to unregister themselves. 442 base::ObserverList<ProfileManagerObserver> observers_; 443 444 // Object to cache various information about profiles. Contains information 445 // about every profile which has been created for this instance of Chrome, 446 // if it has not been explicitly deleted. It must be destroyed after 447 // |profiles_info_| because ~ProfileInfo can trigger a chain of events leading 448 // to an access to this member. 449 std::unique_ptr<ProfileInfoCache> profile_info_cache_; 450 451 content::NotificationRegistrar registrar_; 452 453 // The path to the user data directory (DIR_USER_DATA). 454 const base::FilePath user_data_dir_; 455 456 // Indicates that a user has logged in and that the profile specified 457 // in the --login-profile command line argument should be used as the 458 // default. 459 bool logged_in_ = false; 460 461 #if !defined(OS_ANDROID) 462 BrowserListObserver browser_list_observer_{this}; 463 #endif // !defined(OS_ANDROID) 464 465 // Maps profile path to ProfileInfo (if profile has been created). Use 466 // RegisterProfile() to add into this map. This map owns all loaded profile 467 // objects in a running instance of Chrome. 468 using ProfilesInfoMap = 469 std::map<base::FilePath, std::unique_ptr<ProfileInfo>>; 470 ProfilesInfoMap profiles_info_; 471 472 // Manages the process of creating, deleteing and updating Desktop shortcuts. 473 std::unique_ptr<ProfileShortcutManager> profile_shortcut_manager_; 474 475 // For keeping track of the last active profiles. 476 std::map<Profile*, int> browser_counts_; 477 // On startup we launch the active profiles in the order they became active 478 // during the last run. This is why they are kept in a list, not in a set. 479 std::vector<Profile*> active_profiles_; 480 bool closing_all_browsers_ = false; 481 482 // Controls whether to initialize some services. Only disabled for testing. 483 bool do_final_services_init_ = true; 484 485 // Path to Guest profile. Can be empty when the profile does not exist. 486 base::FilePath guest_profile_path_; 487 488 // TODO(chrome/browser/profiles/OWNERS): Usage of this in profile_manager.cc 489 // should likely be turned into DCHECK_CURRENTLY_ON(BrowserThread::UI) for 490 // consistency with surrounding code in the same file but that wasn't trivial 491 // enough to do as part of the mass refactor CL which introduced 492 // |thread_checker_|, ref. https://codereview.chromium.org/2907253003/#msg37. 493 THREAD_CHECKER(thread_checker_); 494 }; 495 496 // Same as the ProfileManager, but doesn't initialize some services of the 497 // profile. This one is useful in unittests. 498 class ProfileManagerWithoutInit : public ProfileManager { 499 public: 500 explicit ProfileManagerWithoutInit(const base::FilePath& user_data_dir); 501 ProfileManagerWithoutInit(const ProfileManagerWithoutInit&) = delete; 502 ProfileManagerWithoutInit& operator=(const ProfileManagerWithoutInit&) = 503 delete; 504 }; 505 506 #endif // CHROME_BROWSER_PROFILES_PROFILE_MANAGER_H_ 507