1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/profiles/profile_manager.h"
10 #include "base/command_line.h"
11 #include "base/deferred_sequenced_task_runner.h"
12 #include "base/files/file_enumerator.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/prefs/scoped_user_pref_update.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/trace_event/trace_event.h"
22 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/chrome_notification_types.h"
25 #include "chrome/browser/download/download_service.h"
26 #include "chrome/browser/download/download_service_factory.h"
27 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
28 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
29 #include "chrome/browser/password_manager/password_store_factory.h"
30 #include "chrome/browser/prefs/incognito_mode_prefs.h"
31 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
32 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
33 #include "chrome/browser/profiles/profile_destroyer.h"
34 #include "chrome/browser/profiles/profile_info_cache.h"
35 #include "chrome/browser/profiles/profile_metrics.h"
36 #include "chrome/browser/profiles/profiles_state.h"
37 #include "chrome/browser/profiles/startup_task_runner_service.h"
38 #include "chrome/browser/profiles/startup_task_runner_service_factory.h"
39 #include "chrome/browser/signin/account_reconcilor_factory.h"
40 #include "chrome/browser/signin/account_tracker_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/profile_sync_service.h"
43 #include "chrome/browser/sync/profile_sync_service_factory.h"
44 #include "chrome/browser/ui/browser.h"
45 #include "chrome/browser/ui/browser_iterator.h"
46 #include "chrome/browser/ui/sync/sync_promo_ui.h"
47 #include "chrome/common/chrome_constants.h"
48 #include "chrome/common/chrome_paths_internal.h"
49 #include "chrome/common/chrome_switches.h"
50 #include "chrome/common/logging_chrome.h"
51 #include "chrome/common/pref_names.h"
52 #include "chrome/common/url_constants.h"
53 #include "chrome/grit/generated_resources.h"
54 #include "components/bookmarks/browser/bookmark_model.h"
55 #include "components/content_settings/core/browser/host_content_settings_map.h"
56 #include "components/password_manager/core/browser/password_store.h"
57 #include "components/signin/core/browser/account_tracker_service.h"
58 #include "components/signin/core/browser/signin_manager.h"
59 #include "components/signin/core/common/profile_management_switches.h"
60 #include "content/public/browser/browser_thread.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/user_metrics.h"
63 #include "net/http/http_transaction_factory.h"
64 #include "net/url_request/url_request_context.h"
65 #include "net/url_request/url_request_context_getter.h"
66 #include "net/url_request/url_request_job.h"
67 #include "ui/base/l10n/l10n_util.h"
69 #if defined(ENABLE_EXTENSIONS)
70 #include "chrome/browser/extensions/extension_service.h"
71 #include "extensions/browser/extension_registry.h"
72 #include "extensions/browser/extension_system.h"
73 #include "extensions/common/extension_set.h"
74 #include "extensions/common/manifest.h"
77 #if defined(ENABLE_SUPERVISED_USERS)
78 #include "chrome/browser/supervised_user/child_accounts/child_account_service.h"
79 #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h"
80 #include "chrome/browser/supervised_user/supervised_user_service.h"
81 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
85 #include "chrome/browser/sessions/session_service_factory.h"
86 #include "chrome/browser/ui/browser_list.h"
87 #endif // !defined (OS_IOS)
90 #include "base/win/metro.h"
91 #include "chrome/installer/util/browser_distribution.h"
94 #if defined(OS_CHROMEOS)
95 #include "chrome/browser/browser_process_platform_part_chromeos.h"
96 #include "chrome/browser/chromeos/profiles/profile_helper.h"
97 #include "chromeos/chromeos_switches.h"
98 #include "chromeos/dbus/cryptohome_client.h"
99 #include "chromeos/dbus/dbus_thread_manager.h"
100 #include "components/user_manager/user.h"
101 #include "components/user_manager/user_manager.h"
104 using base::UserMetricsAction
;
105 using content::BrowserThread
;
109 // Profiles that should be deleted on shutdown.
110 std::vector
<base::FilePath
>& ProfilesToDelete() {
111 CR_DEFINE_STATIC_LOCAL(std::vector
<base::FilePath
>, profiles_to_delete
, ());
112 return profiles_to_delete
;
115 int64
ComputeFilesSize(const base::FilePath
& directory
,
116 const base::FilePath::StringType
& pattern
) {
117 int64 running_size
= 0;
118 base::FileEnumerator
iter(directory
, false, base::FileEnumerator::FILES
,
120 while (!iter
.Next().empty())
121 running_size
+= iter
.GetInfo().GetSize();
125 // Simple task to log the size of the current profile.
126 void ProfileSizeTask(const base::FilePath
& path
, int enabled_app_count
) {
127 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
128 const int64 kBytesInOneMB
= 1024 * 1024;
130 int64 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("*"));
131 int size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
132 UMA_HISTOGRAM_COUNTS_10000("Profile.TotalSize", size_MB
);
134 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("History"));
135 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
136 UMA_HISTOGRAM_COUNTS_10000("Profile.HistorySize", size_MB
);
138 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("History*"));
139 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
140 UMA_HISTOGRAM_COUNTS_10000("Profile.TotalHistorySize", size_MB
);
142 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Cookies"));
143 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
144 UMA_HISTOGRAM_COUNTS_10000("Profile.CookiesSize", size_MB
);
146 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Bookmarks"));
147 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
148 UMA_HISTOGRAM_COUNTS_10000("Profile.BookmarksSize", size_MB
);
150 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Favicons"));
151 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
152 UMA_HISTOGRAM_COUNTS_10000("Profile.FaviconsSize", size_MB
);
154 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Top Sites"));
155 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
156 UMA_HISTOGRAM_COUNTS_10000("Profile.TopSitesSize", size_MB
);
158 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Visited Links"));
159 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
160 UMA_HISTOGRAM_COUNTS_10000("Profile.VisitedLinksSize", size_MB
);
162 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Web Data"));
163 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
164 UMA_HISTOGRAM_COUNTS_10000("Profile.WebDataSize", size_MB
);
166 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Extension*"));
167 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
168 UMA_HISTOGRAM_COUNTS_10000("Profile.ExtensionSize", size_MB
);
170 size
= ComputeFilesSize(path
, FILE_PATH_LITERAL("Policy"));
171 size_MB
= static_cast<int>(size
/ kBytesInOneMB
);
172 UMA_HISTOGRAM_COUNTS_10000("Profile.PolicySize", size_MB
);
174 // Count number of enabled apps in this profile, if we know.
175 if (enabled_app_count
!= -1)
176 UMA_HISTOGRAM_COUNTS_10000("Profile.AppCount", enabled_app_count
);
179 void QueueProfileDirectoryForDeletion(const base::FilePath
& path
) {
180 ProfilesToDelete().push_back(path
);
183 bool IsProfileMarkedForDeletion(const base::FilePath
& profile_path
) {
184 return std::find(ProfilesToDelete().begin(), ProfilesToDelete().end(),
185 profile_path
) != ProfilesToDelete().end();
188 // Physically remove deleted profile directories from disk.
189 void NukeProfileFromDisk(const base::FilePath
& profile_path
) {
190 // Delete both the profile directory and its corresponding cache.
191 base::FilePath cache_path
;
192 chrome::GetUserCacheDirectory(profile_path
, &cache_path
);
193 base::DeleteFile(profile_path
, true);
194 base::DeleteFile(cache_path
, true);
197 #if defined(OS_CHROMEOS)
198 void CheckCryptohomeIsMounted(chromeos::DBusMethodCallStatus call_status
,
200 if (call_status
!= chromeos::DBUS_METHOD_CALL_SUCCESS
) {
201 LOG(ERROR
) << "IsMounted call failed.";
205 LOG(ERROR
) << "Cryptohome is not mounted.";
210 #if defined(ENABLE_EXTENSIONS)
212 // Returns the number of installed (and enabled) apps, excluding any component
214 size_t GetEnabledAppCount(Profile
* profile
) {
215 size_t installed_apps
= 0u;
216 const extensions::ExtensionSet
& extensions
=
217 extensions::ExtensionRegistry::Get(profile
)->enabled_extensions();
218 for (extensions::ExtensionSet::const_iterator iter
= extensions
.begin();
219 iter
!= extensions
.end();
221 if ((*iter
)->is_app() &&
222 (*iter
)->location() != extensions::Manifest::COMPONENT
) {
226 return installed_apps
;
229 #endif // ENABLE_EXTENSIONS
233 ProfileManager::ProfileManager(const base::FilePath
& user_data_dir
)
234 : user_data_dir_(user_data_dir
),
236 #if !defined(OS_ANDROID) && !defined(OS_IOS)
237 browser_list_observer_(this),
239 closing_all_browsers_(false) {
240 #if defined(OS_CHROMEOS)
243 chrome::NOTIFICATION_LOGIN_USER_CHANGED
,
244 content::NotificationService::AllSources());
248 chrome::NOTIFICATION_BROWSER_OPENED
,
249 content::NotificationService::AllSources());
252 chrome::NOTIFICATION_BROWSER_CLOSED
,
253 content::NotificationService::AllSources());
256 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST
,
257 content::NotificationService::AllSources());
260 chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED
,
261 content::NotificationService::AllSources());
263 if (ProfileShortcutManager::IsFeatureEnabled() && !user_data_dir_
.empty())
264 profile_shortcut_manager_
.reset(ProfileShortcutManager::Create(
268 ProfileManager::~ProfileManager() {
271 #if defined(ENABLE_SESSION_SERVICE)
273 void ProfileManager::ShutdownSessionServices() {
274 ProfileManager
* pm
= g_browser_process
->profile_manager();
275 if (!pm
) // Is NULL when running unit tests.
277 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
278 for (size_t i
= 0; i
< profiles
.size(); ++i
)
279 SessionServiceFactory::ShutdownForProfile(profiles
[i
]);
284 void ProfileManager::NukeDeletedProfilesFromDisk() {
285 for (std::vector
<base::FilePath
>::iterator it
=
286 ProfilesToDelete().begin();
287 it
!= ProfilesToDelete().end();
289 NukeProfileFromDisk(*it
);
291 ProfilesToDelete().clear();
295 Profile
* ProfileManager::GetLastUsedProfile() {
296 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
297 return profile_manager
->GetLastUsedProfile(profile_manager
->user_data_dir_
);
301 Profile
* ProfileManager::GetLastUsedProfileAllowedByPolicy() {
302 Profile
* profile
= GetLastUsedProfile();
303 if (profile
->IsGuestSession() ||
304 IncognitoModePrefs::GetAvailability(profile
->GetPrefs()) ==
305 IncognitoModePrefs::FORCED
) {
306 return profile
->GetOffTheRecordProfile();
312 std::vector
<Profile
*> ProfileManager::GetLastOpenedProfiles() {
313 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
314 return profile_manager
->GetLastOpenedProfiles(
315 profile_manager
->user_data_dir_
);
319 Profile
* ProfileManager::GetPrimaryUserProfile() {
320 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
321 #if defined(OS_CHROMEOS)
322 if (!profile_manager
->IsLoggedIn() ||
323 !user_manager::UserManager::IsInitialized())
324 return profile_manager
->GetActiveUserOrOffTheRecordProfileFromPath(
325 profile_manager
->user_data_dir());
326 user_manager::UserManager
* manager
= user_manager::UserManager::Get();
327 // Note: The ProfileHelper will take care of guest profiles.
328 return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(
329 manager
->GetPrimaryUser());
331 return profile_manager
->GetActiveUserOrOffTheRecordProfileFromPath(
332 profile_manager
->user_data_dir());
337 Profile
* ProfileManager::GetActiveUserProfile() {
338 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
339 #if defined(OS_CHROMEOS)
340 if (!profile_manager
)
343 if (!profile_manager
->IsLoggedIn() ||
344 !user_manager::UserManager::IsInitialized()) {
345 return profile_manager
->GetActiveUserOrOffTheRecordProfileFromPath(
346 profile_manager
->user_data_dir());
349 user_manager::UserManager
* manager
= user_manager::UserManager::Get();
350 const user_manager::User
* user
= manager
->GetActiveUser();
351 // To avoid an endless loop (crbug.com/334098) we have to additionally check
352 // if the profile of the user was already created. If the profile was not yet
353 // created we load the profile using the profile directly.
354 // TODO: This should be cleaned up with the new profile manager.
355 if (user
&& user
->is_profile_created())
356 return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user
);
360 profile_manager
->GetActiveUserOrOffTheRecordProfileFromPath(
361 profile_manager
->user_data_dir());
362 // |profile| could be null if the user doesn't have a profile yet and the path
363 // is on a read-only volume (preventing Chrome from making a new one).
364 // However, most callers of this function immediately dereference the result
365 // which would lead to crashes in a variety of call sites. Assert here to
366 // figure out how common this is. http://crbug.com/383019
367 CHECK(profile
) << profile_manager
->user_data_dir().AsUTF8Unsafe();
371 Profile
* ProfileManager::GetProfile(const base::FilePath
& profile_dir
) {
372 TRACE_EVENT0("browser", "ProfileManager::GetProfile");
374 // If the profile is already loaded (e.g., chrome.exe launched twice), just
376 Profile
* profile
= GetProfileByPath(profile_dir
);
379 return CreateAndInitializeProfile(profile_dir
);
382 size_t ProfileManager::GetNumberOfProfiles() {
383 return GetProfileInfoCache().GetNumberOfProfiles();
386 void ProfileManager::CreateProfileAsync(
387 const base::FilePath
& profile_path
,
388 const CreateCallback
& callback
,
389 const base::string16
& name
,
390 const base::string16
& icon_url
,
391 const std::string
& supervised_user_id
) {
392 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
393 TRACE_EVENT1("browser,startup",
394 "ProfileManager::CreateProfileAsync",
396 profile_path
.AsUTF8Unsafe());
398 // Make sure that this profile is not pending deletion.
399 if (IsProfileMarkedForDeletion(profile_path
)) {
400 if (!callback
.is_null())
401 callback
.Run(NULL
, Profile::CREATE_STATUS_LOCAL_FAIL
);
405 // Create the profile if needed and collect its ProfileInfo.
406 ProfilesInfoMap::iterator iter
= profiles_info_
.find(profile_path
);
407 ProfileInfo
* info
= NULL
;
409 if (iter
!= profiles_info_
.end()) {
410 info
= iter
->second
.get();
412 // Initiate asynchronous creation process.
413 info
= RegisterProfile(CreateProfileAsyncHelper(profile_path
, this), false);
414 ProfileInfoCache
& cache
= GetProfileInfoCache();
415 // Get the icon index from the user's icon url
417 std::string icon_url_std
= base::UTF16ToASCII(icon_url
);
418 if (profiles::IsDefaultAvatarIconUrl(icon_url_std
, &icon_index
)) {
419 // add profile to cache with user selected name and avatar
420 cache
.AddProfileToCache(profile_path
, name
, base::string16(), icon_index
,
424 if (!supervised_user_id
.empty()) {
425 content::RecordAction(
426 UserMetricsAction("ManagedMode_LocallyManagedUserCreated"));
429 ProfileMetrics::UpdateReportedProfilesStatistics(this);
432 // Call or enqueue the callback.
433 if (!callback
.is_null()) {
434 if (iter
!= profiles_info_
.end() && info
->created
) {
435 Profile
* profile
= info
->profile
.get();
436 // If this was the guest profile, apply settings and go OffTheRecord.
437 if (profile
->GetPath() == ProfileManager::GetGuestProfilePath()) {
438 SetGuestProfilePrefs(profile
);
439 profile
= profile
->GetOffTheRecordProfile();
441 // Profile has already been created. Run callback immediately.
442 callback
.Run(profile
, Profile::CREATE_STATUS_INITIALIZED
);
444 // Profile is either already in the process of being created, or new.
445 // Add callback to the list.
446 info
->callbacks
.push_back(callback
);
451 bool ProfileManager::IsValidProfile(Profile
* profile
) {
452 for (ProfilesInfoMap::iterator iter
= profiles_info_
.begin();
453 iter
!= profiles_info_
.end(); ++iter
) {
454 if (iter
->second
->created
) {
455 Profile
* candidate
= iter
->second
->profile
.get();
456 if (candidate
== profile
||
457 (candidate
->HasOffTheRecordProfile() &&
458 candidate
->GetOffTheRecordProfile() == profile
)) {
466 base::FilePath
ProfileManager::GetInitialProfileDir() {
467 #if defined(OS_CHROMEOS)
469 return chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
472 base::FilePath relative_profile_dir
;
473 // TODO(mirandac): should not automatically be default profile.
474 return relative_profile_dir
.AppendASCII(chrome::kInitialProfile
);
477 Profile
* ProfileManager::GetLastUsedProfile(
478 const base::FilePath
& user_data_dir
) {
479 #if defined(OS_CHROMEOS)
480 // Use default login profile if user has not logged in yet.
482 return GetActiveUserOrOffTheRecordProfileFromPath(user_data_dir
);
484 // CrOS multi-profiles implementation is different so GetLastUsedProfile
485 // has custom implementation too.
486 base::FilePath profile_dir
;
487 // In case of multi-profiles we ignore "last used profile" preference
488 // since it may refer to profile that has been in use in previous session.
489 // That profile dir may not be mounted in this session so instead return
490 // active profile from current session.
491 profile_dir
= chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
493 base::FilePath
profile_path(user_data_dir
);
494 Profile
* profile
= GetProfile(profile_path
.Append(profile_dir
));
495 return profile
->IsGuestSession() ? profile
->GetOffTheRecordProfile() :
500 return GetProfile(GetLastUsedProfileDir(user_data_dir
));
503 base::FilePath
ProfileManager::GetLastUsedProfileDir(
504 const base::FilePath
& user_data_dir
) {
505 base::FilePath
last_used_profile_dir(user_data_dir
);
506 PrefService
* local_state
= g_browser_process
->local_state();
509 if (local_state
->HasPrefPath(prefs::kProfileLastUsed
)) {
510 return last_used_profile_dir
.AppendASCII(
511 local_state
->GetString(prefs::kProfileLastUsed
));
514 return last_used_profile_dir
.AppendASCII(chrome::kInitialProfile
);
517 std::vector
<Profile
*> ProfileManager::GetLastOpenedProfiles(
518 const base::FilePath
& user_data_dir
) {
519 PrefService
* local_state
= g_browser_process
->local_state();
522 std::vector
<Profile
*> to_return
;
523 if (local_state
->HasPrefPath(prefs::kProfilesLastActive
) &&
524 local_state
->GetList(prefs::kProfilesLastActive
)) {
525 // Make a copy because the list might change in the calls to GetProfile.
526 scoped_ptr
<base::ListValue
> profile_list(
527 local_state
->GetList(prefs::kProfilesLastActive
)->DeepCopy());
528 base::ListValue::const_iterator it
;
530 for (it
= profile_list
->begin(); it
!= profile_list
->end(); ++it
) {
531 if (!(*it
)->GetAsString(&profile
) || profile
.empty()) {
532 LOG(WARNING
) << "Invalid entry in " << prefs::kProfilesLastActive
;
535 to_return
.push_back(GetProfile(user_data_dir
.AppendASCII(profile
)));
541 std::vector
<Profile
*> ProfileManager::GetLoadedProfiles() const {
542 std::vector
<Profile
*> profiles
;
543 for (ProfilesInfoMap::const_iterator iter
= profiles_info_
.begin();
544 iter
!= profiles_info_
.end(); ++iter
) {
545 if (iter
->second
->created
)
546 profiles
.push_back(iter
->second
->profile
.get());
551 Profile
* ProfileManager::GetProfileByPathInternal(
552 const base::FilePath
& path
) const {
553 TRACE_EVENT0("browser", "ProfileManager::GetProfileByPathInternal");
554 ProfileInfo
* profile_info
= GetProfileInfoByPath(path
);
555 return profile_info
? profile_info
->profile
.get() : nullptr;
558 Profile
* ProfileManager::GetProfileByPath(const base::FilePath
& path
) const {
559 TRACE_EVENT0("browser", "ProfileManager::GetProfileByPath");
560 ProfileInfo
* profile_info
= GetProfileInfoByPath(path
);
561 return (profile_info
&& profile_info
->created
) ? profile_info
->profile
.get()
566 base::FilePath
ProfileManager::CreateMultiProfileAsync(
567 const base::string16
& name
,
568 const base::string16
& icon_url
,
569 const CreateCallback
& callback
,
570 const std::string
& supervised_user_id
) {
571 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
573 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
575 base::FilePath new_path
= profile_manager
->GenerateNextProfileDirectoryPath();
577 profile_manager
->CreateProfileAsync(new_path
,
586 base::FilePath
ProfileManager::GetGuestProfilePath() {
587 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
589 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
591 base::FilePath guest_path
= profile_manager
->user_data_dir();
592 return guest_path
.Append(chrome::kGuestProfileDir
);
596 base::FilePath
ProfileManager::GetSystemProfilePath() {
597 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
599 ProfileManager
* profile_manager
= g_browser_process
->profile_manager();
601 base::FilePath system_path
= profile_manager
->user_data_dir();
602 return system_path
.Append(chrome::kSystemProfileDir
);
605 base::FilePath
ProfileManager::GenerateNextProfileDirectoryPath() {
606 PrefService
* local_state
= g_browser_process
->local_state();
609 DCHECK(profiles::IsMultipleProfilesEnabled());
611 // Create the next profile in the next available directory slot.
612 int next_directory
= local_state
->GetInteger(prefs::kProfilesNumCreated
);
613 std::string profile_name
= chrome::kMultiProfileDirPrefix
;
614 profile_name
.append(base::IntToString(next_directory
));
615 base::FilePath new_path
= user_data_dir_
;
617 new_path
= new_path
.Append(base::ASCIIToUTF16(profile_name
));
619 new_path
= new_path
.Append(profile_name
);
621 local_state
->SetInteger(prefs::kProfilesNumCreated
, ++next_directory
);
625 ProfileInfoCache
& ProfileManager::GetProfileInfoCache() {
626 TRACE_EVENT0("browser", "ProfileManager::GetProfileInfoCache");
627 if (!profile_info_cache_
) {
628 profile_info_cache_
.reset(new ProfileInfoCache(
629 g_browser_process
->local_state(), user_data_dir_
));
631 return *profile_info_cache_
.get();
634 ProfileShortcutManager
* ProfileManager::profile_shortcut_manager() {
635 return profile_shortcut_manager_
.get();
638 void ProfileManager::ScheduleProfileForDeletion(
639 const base::FilePath
& profile_dir
,
640 const CreateCallback
& callback
) {
641 DCHECK(profiles::IsMultipleProfilesEnabled());
643 // Cancel all in-progress downloads before deleting the profile to prevent a
644 // "Do you want to exit Google Chrome and cancel the downloads?" prompt
645 // (crbug.com/336725).
646 Profile
* profile
= GetProfileByPath(profile_dir
);
648 DownloadService
* service
=
649 DownloadServiceFactory::GetForBrowserContext(profile
);
650 service
->CancelDownloads();
653 ProfileInfoCache
& cache
= GetProfileInfoCache();
655 // If we're deleting the last (non-legacy-supervised) profile, then create a
656 // new profile in its place.
657 base::FilePath last_non_supervised_profile_path
;
658 for (size_t i
= 0; i
< cache
.GetNumberOfProfiles(); ++i
) {
659 base::FilePath cur_path
= cache
.GetPathOfProfileAtIndex(i
);
660 // Make sure that this profile is not pending deletion, and is not
661 // legacy-supervised.
662 if (cur_path
!= profile_dir
&&
663 !cache
.ProfileIsLegacySupervisedAtIndex(i
) &&
664 !IsProfileMarkedForDeletion(cur_path
)) {
665 last_non_supervised_profile_path
= cur_path
;
670 base::FilePath new_path
;
671 if (last_non_supervised_profile_path
.empty()) {
672 // If we are using --new-avatar-menu, then assign the default
673 // placeholder avatar and name. Otherwise, use random ones.
674 bool is_new_avatar_menu
= switches::IsNewAvatarMenu();
675 int avatar_index
= profiles::GetPlaceholderAvatarIndex();
676 base::string16 new_avatar_url
= is_new_avatar_menu
?
677 base::UTF8ToUTF16(profiles::GetDefaultAvatarIconUrl(avatar_index
)) :
679 base::string16 new_profile_name
= is_new_avatar_menu
?
680 cache
.ChooseNameForNewProfile(avatar_index
) : base::string16();
682 new_path
= GenerateNextProfileDirectoryPath();
683 CreateProfileAsync(new_path
,
684 base::Bind(&ProfileManager::OnNewActiveProfileLoaded
,
685 base::Unretained(this),
693 ProfileMetrics::LogProfileAddNewUser(
694 ProfileMetrics::ADD_NEW_USER_LAST_DELETED
);
698 #if defined(OS_MACOSX)
699 // On the Mac, the browser process is not killed when all browser windows are
700 // closed, so just in case we are deleting the active profile, and no other
701 // profile has been loaded, we must pre-load a next one.
702 const std::string last_used_profile
=
703 g_browser_process
->local_state()->GetString(prefs::kProfileLastUsed
);
704 if (last_used_profile
== profile_dir
.BaseName().MaybeAsASCII() ||
705 last_used_profile
== GetGuestProfilePath().BaseName().MaybeAsASCII()) {
706 CreateProfileAsync(last_non_supervised_profile_path
,
707 base::Bind(&ProfileManager::OnNewActiveProfileLoaded
,
708 base::Unretained(this),
710 last_non_supervised_profile_path
,
717 #endif // defined(OS_MACOSX)
719 FinishDeletingProfile(profile_dir
, last_non_supervised_profile_path
);
723 void ProfileManager::CleanUpStaleProfiles(
724 const std::vector
<base::FilePath
>& profile_paths
) {
725 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
727 for (std::vector
<base::FilePath
>::const_iterator it
= profile_paths
.begin();
728 it
!= profile_paths
.end(); ++it
) {
729 NukeProfileFromDisk(*it
);
733 void ProfileManager::AutoloadProfiles() {
734 // If running in the background is disabled for the browser, do not autoload
736 PrefService
* local_state
= g_browser_process
->local_state();
737 if (!local_state
->HasPrefPath(prefs::kBackgroundModeEnabled
) ||
738 !local_state
->GetBoolean(prefs::kBackgroundModeEnabled
)) {
742 ProfileInfoCache
& cache
= GetProfileInfoCache();
743 size_t number_of_profiles
= cache
.GetNumberOfProfiles();
744 for (size_t p
= 0; p
< number_of_profiles
; ++p
) {
745 if (cache
.GetBackgroundStatusOfProfileAtIndex(p
)) {
746 // If status is true, that profile is running background apps. By calling
747 // GetProfile, we automatically cause the profile to be loaded which will
748 // register it with the BackgroundModeManager.
749 GetProfile(cache
.GetPathOfProfileAtIndex(p
));
754 void ProfileManager::InitProfileUserPrefs(Profile
* profile
) {
755 TRACE_EVENT0("browser", "ProfileManager::InitProfileUserPrefs");
756 ProfileInfoCache
& cache
= GetProfileInfoCache();
758 if (profile
->GetPath().DirName() != cache
.GetUserDataDir())
762 std::string profile_name
;
763 std::string supervised_user_id
;
764 if (profile
->IsGuestSession()) {
765 profile_name
= l10n_util::GetStringUTF8(IDS_PROFILES_GUEST_PROFILE_NAME
);
768 size_t profile_cache_index
=
769 cache
.GetIndexOfProfileWithPath(profile
->GetPath());
770 // If the cache has an entry for this profile, use the cache data.
771 if (profile_cache_index
!= std::string::npos
) {
773 cache
.GetAvatarIconIndexOfProfileAtIndex(profile_cache_index
);
775 base::UTF16ToUTF8(cache
.GetNameOfProfileAtIndex(profile_cache_index
));
777 cache
.GetSupervisedUserIdOfProfileAtIndex(profile_cache_index
);
778 } else if (profile
->GetPath() ==
779 profiles::GetDefaultProfileDir(cache
.GetUserDataDir())) {
780 // The --new-avatar-menu flag no longer uses the "First User" name.
781 bool is_new_avatar_menu
= switches::IsNewAvatarMenu();
782 avatar_index
= profiles::GetPlaceholderAvatarIndex();
783 profile_name
= is_new_avatar_menu
?
784 base::UTF16ToUTF8(cache
.ChooseNameForNewProfile(avatar_index
)) :
785 l10n_util::GetStringUTF8(IDS_DEFAULT_PROFILE_NAME
);
787 avatar_index
= cache
.ChooseAvatarIconIndexForNewProfile();
789 base::UTF16ToUTF8(cache
.ChooseNameForNewProfile(avatar_index
));
793 if (!profile
->GetPrefs()->HasPrefPath(prefs::kProfileAvatarIndex
))
794 profile
->GetPrefs()->SetInteger(prefs::kProfileAvatarIndex
, avatar_index
);
796 if (!profile
->GetPrefs()->HasPrefPath(prefs::kProfileName
))
797 profile
->GetPrefs()->SetString(prefs::kProfileName
, profile_name
);
799 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
800 bool force_supervised_user_id
=
801 #if defined(OS_CHROMEOS)
802 g_browser_process
->platform_part()
804 ->GetSigninProfileDir() != profile
->GetPath() &&
806 command_line
->HasSwitch(switches::kSupervisedUserId
);
807 if (force_supervised_user_id
) {
809 command_line
->GetSwitchValueASCII(switches::kSupervisedUserId
);
811 if (force_supervised_user_id
||
812 !profile
->GetPrefs()->HasPrefPath(prefs::kSupervisedUserId
)) {
813 profile
->GetPrefs()->SetString(prefs::kSupervisedUserId
,
817 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
818 // If the lock enabled algorithm changed, update this profile's lock status.
819 if (switches::IsNewProfileManagement())
820 profiles::UpdateIsProfileLockEnabledIfNeeded(profile
);
824 void ProfileManager::RegisterTestingProfile(Profile
* profile
,
826 bool start_deferred_task_runners
) {
827 RegisterProfile(profile
, true);
829 InitProfileUserPrefs(profile
);
830 AddProfileToCache(profile
);
832 if (start_deferred_task_runners
) {
833 StartupTaskRunnerServiceFactory::GetForProfile(profile
)->
834 StartDeferredTaskRunners();
838 void ProfileManager::Observe(
840 const content::NotificationSource
& source
,
841 const content::NotificationDetails
& details
) {
842 #if defined(OS_CHROMEOS)
843 if (type
== chrome::NOTIFICATION_LOGIN_USER_CHANGED
) {
846 const base::CommandLine
& command_line
=
847 *base::CommandLine::ForCurrentProcess();
848 if (!command_line
.HasSwitch(switches::kTestType
)) {
849 // If we don't have a mounted profile directory we're in trouble.
850 // TODO(davemoore) Once we have better api this check should ensure that
851 // our profile directory is the one that's mounted, and that it's mounted
852 // as the current user.
853 chromeos::DBusThreadManager::Get()->GetCryptohomeClient()->IsMounted(
854 base::Bind(&CheckCryptohomeIsMounted
));
856 // Confirm that we hadn't loaded the new profile previously.
857 base::FilePath default_profile_dir
= user_data_dir_
.Append(
858 GetInitialProfileDir());
859 CHECK(!GetProfileByPathInternal(default_profile_dir
))
860 << "The default profile was loaded before we mounted the cryptohome.";
865 bool save_active_profiles
= false;
867 case chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST
: {
868 // Ignore any browsers closing from now on.
869 closing_all_browsers_
= true;
870 save_active_profiles
= true;
873 case chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED
: {
874 // This will cancel the shutdown process, so the active profiles are
875 // tracked again. Also, as the active profiles may have changed (i.e. if
876 // some windows were closed) we save the current list of active profiles
878 closing_all_browsers_
= false;
879 save_active_profiles
= true;
882 case chrome::NOTIFICATION_BROWSER_OPENED
: {
883 Browser
* browser
= content::Source
<Browser
>(source
).ptr();
885 Profile
* profile
= browser
->profile();
888 profile
->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles
);
889 if (!profile
->IsOffTheRecord() && !is_ephemeral
&&
890 ++browser_counts_
[profile
] == 1) {
891 active_profiles_
.push_back(profile
);
892 save_active_profiles
= true;
894 // If browsers are opening, we can't be closing all the browsers. This
895 // can happen if the application was exited, but background mode or
896 // packaged apps prevented the process from shutting down, and then
897 // a new browser window was opened.
898 closing_all_browsers_
= false;
901 case chrome::NOTIFICATION_BROWSER_CLOSED
: {
902 Browser
* browser
= content::Source
<Browser
>(source
).ptr();
904 Profile
* profile
= browser
->profile();
906 if (!profile
->IsOffTheRecord() && --browser_counts_
[profile
] == 0) {
907 active_profiles_
.erase(std::find(active_profiles_
.begin(),
908 active_profiles_
.end(), profile
));
909 save_active_profiles
= !closing_all_browsers_
;
919 if (save_active_profiles
) {
920 PrefService
* local_state
= g_browser_process
->local_state();
922 ListPrefUpdate
update(local_state
, prefs::kProfilesLastActive
);
923 base::ListValue
* profile_list
= update
.Get();
925 profile_list
->Clear();
927 // crbug.com/120112 -> several non-incognito profiles might have the same
928 // GetPath().BaseName(). In that case, we cannot restore both
929 // profiles. Include each base name only once in the last active profile
931 std::set
<std::string
> profile_paths
;
932 std::vector
<Profile
*>::const_iterator it
;
933 for (it
= active_profiles_
.begin(); it
!= active_profiles_
.end(); ++it
) {
934 std::string profile_path
= (*it
)->GetPath().BaseName().MaybeAsASCII();
935 // Some profiles might become ephemeral after they are created.
936 if (!(*it
)->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles
) &&
937 profile_paths
.find(profile_path
) == profile_paths
.end()) {
938 profile_paths
.insert(profile_path
);
939 profile_list
->Append(new base::StringValue(profile_path
));
945 void ProfileManager::OnProfileCreated(Profile
* profile
,
947 bool is_new_profile
) {
948 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
950 ProfilesInfoMap::iterator iter
= profiles_info_
.find(profile
->GetPath());
951 DCHECK(iter
!= profiles_info_
.end());
952 ProfileInfo
* info
= iter
->second
.get();
954 std::vector
<CreateCallback
> callbacks
;
955 info
->callbacks
.swap(callbacks
);
957 // Invoke CREATED callback for normal profiles.
958 bool go_off_the_record
= ShouldGoOffTheRecord(profile
);
959 if (success
&& !go_off_the_record
)
960 RunCallbacks(callbacks
, profile
, Profile::CREATE_STATUS_CREATED
);
962 // Perform initialization.
964 DoFinalInit(profile
, go_off_the_record
);
965 if (go_off_the_record
)
966 profile
= profile
->GetOffTheRecordProfile();
967 info
->created
= true;
970 profiles_info_
.erase(iter
);
971 // TODO(yiyaoliu): This is temporary, remove it after it's not used.
972 UMA_HISTOGRAM_COUNTS_100("UMA.ProfilesCount.AfterErase",
973 profiles_info_
.size());
977 // If this was the guest profile, finish setting its special status.
978 if (profile
->GetPath() == ProfileManager::GetGuestProfilePath())
979 SetGuestProfilePrefs(profile
);
981 // Invoke CREATED callback for incognito profiles.
982 if (go_off_the_record
)
983 RunCallbacks(callbacks
, profile
, Profile::CREATE_STATUS_CREATED
);
986 // Invoke INITIALIZED or FAIL for all profiles.
987 RunCallbacks(callbacks
, profile
,
988 profile
? Profile::CREATE_STATUS_INITIALIZED
:
989 Profile::CREATE_STATUS_LOCAL_FAIL
);
992 void ProfileManager::DoFinalInit(Profile
* profile
, bool go_off_the_record
) {
993 TRACE_EVENT0("browser", "ProfileManager::DoFinalInit");
994 DoFinalInitForServices(profile
, go_off_the_record
);
995 AddProfileToCache(profile
);
996 DoFinalInitLogging(profile
);
998 ProfileMetrics::LogNumberOfProfiles(this);
999 content::NotificationService::current()->Notify(
1000 chrome::NOTIFICATION_PROFILE_ADDED
,
1001 content::Source
<Profile
>(profile
),
1002 content::NotificationService::NoDetails());
1005 void ProfileManager::DoFinalInitForServices(Profile
* profile
,
1006 bool go_off_the_record
) {
1007 TRACE_EVENT0("browser", "ProfileManager::DoFinalInitForServices");
1008 #if defined(ENABLE_EXTENSIONS)
1009 ProfileInfoCache
& cache
= GetProfileInfoCache();
1010 extensions::ExtensionSystem::Get(profile
)->InitForRegularProfile(
1011 !go_off_the_record
);
1012 // During tests, when |profile| is an instance of TestingProfile,
1013 // ExtensionSystem might not create an ExtensionService.
1014 if (extensions::ExtensionSystem::Get(profile
)->extension_service()) {
1015 extensions::ExtensionSystem::Get(profile
)->extension_service()->
1016 RegisterContentSettings(profile
->GetHostContentSettingsMap());
1018 // Set the block extensions bit on the ExtensionService. There likely are no
1019 // blockable extensions to block.
1020 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile
->GetPath());
1021 if (profile_index
!= std::string::npos
&&
1022 cache
.ProfileIsSigninRequiredAtIndex(profile_index
)) {
1023 extensions::ExtensionSystem::Get(profile
)
1024 ->extension_service()
1025 ->BlockAllExtensions();
1029 #if defined(ENABLE_SUPERVISED_USERS)
1030 // Initialization needs to happen after extension system initialization (for
1031 // extension::ManagementPolicy) and InitProfileUserPrefs (for setting the
1032 // initializing the supervised flag if necessary).
1033 ChildAccountServiceFactory::GetForProfile(profile
)->Init();
1034 SupervisedUserServiceFactory::GetForProfile(profile
)->Init();
1036 // Start the deferred task runners once the profile is loaded.
1037 StartupTaskRunnerServiceFactory::GetForProfile(profile
)->
1038 StartDeferredTaskRunners();
1040 // Activate data reduction proxy. This creates a request context and makes a
1041 // URL request to check if the data reduction proxy server is reachable.
1042 DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile
)->
1043 MaybeActivateDataReductionProxy(true);
1045 AccountTrackerServiceFactory::GetForProfile(profile
)->EnableNetworkFetches();
1046 AccountReconcilorFactory::GetForProfile(profile
);
1049 void ProfileManager::DoFinalInitLogging(Profile
* profile
) {
1050 TRACE_EVENT0("browser", "ProfileManager::DoFinalInitLogging");
1051 // Count number of extensions in this profile.
1052 int enabled_app_count
= -1;
1053 #if defined(ENABLE_EXTENSIONS)
1054 enabled_app_count
= GetEnabledAppCount(profile
);
1057 // Log the profile size after a reasonable startup delay.
1058 BrowserThread::PostDelayedTask(
1059 BrowserThread::FILE, FROM_HERE
,
1060 base::Bind(&ProfileSizeTask
, profile
->GetPath(), enabled_app_count
),
1061 base::TimeDelta::FromSeconds(112));
1064 Profile
* ProfileManager::CreateProfileHelper(const base::FilePath
& path
) {
1065 TRACE_EVENT0("browser", "ProfileManager::CreateProfileHelper");
1066 SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateProfileHelperTime");
1068 return Profile::CreateProfile(path
, NULL
, Profile::CREATE_MODE_SYNCHRONOUS
);
1071 Profile
* ProfileManager::CreateProfileAsyncHelper(const base::FilePath
& path
,
1072 Delegate
* delegate
) {
1073 return Profile::CreateProfile(path
,
1075 Profile::CREATE_MODE_ASYNCHRONOUS
);
1078 Profile
* ProfileManager::GetActiveUserOrOffTheRecordProfileFromPath(
1079 const base::FilePath
& user_data_dir
) {
1080 #if defined(OS_CHROMEOS)
1081 base::FilePath
default_profile_dir(user_data_dir
);
1083 default_profile_dir
= profiles::GetDefaultProfileDir(user_data_dir
);
1084 Profile
* profile
= GetProfile(default_profile_dir
);
1085 // For cros, return the OTR profile so we never accidentally keep
1086 // user data in an unencrypted profile. But doing this makes
1087 // many of the browser and ui tests fail. We do return the OTR profile
1088 // if the login-profile switch is passed so that we can test this.
1089 if (ShouldGoOffTheRecord(profile
))
1090 return profile
->GetOffTheRecordProfile();
1091 DCHECK(!user_manager::UserManager::Get()->IsLoggedInAsGuest());
1095 default_profile_dir
= default_profile_dir
.Append(GetInitialProfileDir());
1096 ProfileInfo
* profile_info
= GetProfileInfoByPath(default_profile_dir
);
1097 // Fallback to default off-the-record profile, if user profile has not fully
1099 if (profile_info
&& !profile_info
->created
)
1100 default_profile_dir
= profiles::GetDefaultProfileDir(user_data_dir
);
1102 Profile
* profile
= GetProfile(default_profile_dir
);
1103 // Some unit tests didn't initialize the UserManager.
1104 if (user_manager::UserManager::IsInitialized() &&
1105 user_manager::UserManager::Get()->IsLoggedInAsGuest())
1106 return profile
->GetOffTheRecordProfile();
1109 base::FilePath
default_profile_dir(user_data_dir
);
1110 default_profile_dir
= default_profile_dir
.Append(GetInitialProfileDir());
1111 return GetProfile(default_profile_dir
);
1115 bool ProfileManager::AddProfile(Profile
* profile
) {
1116 TRACE_EVENT0("browser", "ProfileManager::AddProfile");
1119 // Make sure that we're not loading a profile with the same ID as a profile
1120 // that's already loaded.
1121 if (GetProfileByPathInternal(profile
->GetPath())) {
1122 NOTREACHED() << "Attempted to add profile with the same path (" <<
1123 profile
->GetPath().value() <<
1124 ") as an already-loaded profile.";
1128 RegisterProfile(profile
, true);
1129 InitProfileUserPrefs(profile
);
1130 DoFinalInit(profile
, ShouldGoOffTheRecord(profile
));
1134 Profile
* ProfileManager::CreateAndInitializeProfile(
1135 const base::FilePath
& profile_dir
) {
1136 TRACE_EVENT0("browser", "ProfileManager::CreateAndInitializeProfile");
1137 SCOPED_UMA_HISTOGRAM_LONG_TIMER("Profile.CreateAndInitializeProfile");
1139 // CHECK that we are not trying to load the same profile twice, to prevent
1140 // profile corruption. Note that this check also covers the case when we have
1141 // already started loading the profile but it is not fully initialized yet,
1142 // which would make Bad Things happen if we returned it.
1143 CHECK(!GetProfileByPathInternal(profile_dir
));
1144 Profile
* profile
= CreateProfileHelper(profile_dir
);
1147 bool result
= AddProfile(profile
);
1153 void ProfileManager::FinishDeletingProfile(
1154 const base::FilePath
& profile_dir
,
1155 const base::FilePath
& new_active_profile_dir
) {
1156 // Update the last used profile pref before closing browser windows. This
1157 // way the correct last used profile is set for any notification observers.
1158 g_browser_process
->local_state()->SetString(
1159 prefs::kProfileLastUsed
,
1160 new_active_profile_dir
.BaseName().MaybeAsASCII());
1162 ProfileInfoCache
& cache
= GetProfileInfoCache();
1163 // TODO(sail): Due to bug 88586 we don't delete the profile instance. Once we
1164 // start deleting the profile instance we need to close background apps too.
1165 Profile
* profile
= GetProfileByPath(profile_dir
);
1168 // TODO: Migrate additional code in this block to observe this notification
1169 // instead of being implemented here.
1170 content::NotificationService::current()->Notify(
1171 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED
,
1172 content::Source
<Profile
>(profile
),
1173 content::NotificationService::NoDetails());
1175 // By this point, all in-progress downloads for the profile being deleted
1176 // must have been canceled (crbug.com/336725).
1177 DCHECK(DownloadServiceFactory::GetForBrowserContext(profile
)->
1178 NonMaliciousDownloadCount() == 0);
1179 BrowserList::CloseAllBrowsersWithProfile(profile
);
1181 // Disable sync for doomed profile.
1182 if (ProfileSyncServiceFactory::GetInstance()->HasProfileSyncService(
1184 ProfileSyncServiceFactory::GetInstance()->GetForProfile(
1185 profile
)->DisableForUser();
1188 bool profile_is_signed_in
= !cache
.GetUserNameOfProfileAtIndex(
1189 cache
.GetIndexOfProfileWithPath(profile_dir
)).empty();
1190 ProfileMetrics::LogProfileDelete(profile_is_signed_in
);
1191 // Some platforms store passwords in keychains. They should be removed.
1192 scoped_refptr
<password_manager::PasswordStore
> password_store
=
1193 PasswordStoreFactory::GetForProfile(
1194 profile
, ServiceAccessType::EXPLICIT_ACCESS
).get();
1195 if (password_store
.get()) {
1196 password_store
->RemoveLoginsCreatedBetween(base::Time(),
1201 QueueProfileDirectoryForDeletion(profile_dir
);
1202 cache
.DeleteProfileFromCache(profile_dir
);
1203 ProfileMetrics::UpdateReportedProfilesStatistics(this);
1206 ProfileManager::ProfileInfo
* ProfileManager::RegisterProfile(
1209 TRACE_EVENT0("browser", "ProfileManager::RegisterProfile");
1210 ProfileInfo
* info
= new ProfileInfo(profile
, created
);
1211 profiles_info_
.insert(
1212 std::make_pair(profile
->GetPath(), linked_ptr
<ProfileInfo
>(info
)));
1216 ProfileManager::ProfileInfo
* ProfileManager::GetProfileInfoByPath(
1217 const base::FilePath
& path
) const {
1218 ProfilesInfoMap::const_iterator iter
= profiles_info_
.find(path
);
1219 return (iter
== profiles_info_
.end()) ? NULL
: iter
->second
.get();
1222 void ProfileManager::AddProfileToCache(Profile
* profile
) {
1223 TRACE_EVENT0("browser", "ProfileManager::AddProfileToCache");
1224 if (profile
->IsGuestSession() || profile
->IsSystemProfile())
1226 ProfileInfoCache
& cache
= GetProfileInfoCache();
1227 if (profile
->GetPath().DirName() != cache
.GetUserDataDir())
1230 SigninManagerBase
* signin_manager
=
1231 SigninManagerFactory::GetForProfile(profile
);
1232 base::string16 username
= base::UTF8ToUTF16(
1233 signin_manager
->GetAuthenticatedUsername());
1235 size_t profile_index
= cache
.GetIndexOfProfileWithPath(profile
->GetPath());
1236 if (profile_index
!= std::string::npos
) {
1237 // The ProfileInfoCache's username must match the Signin Manager's username.
1238 cache
.SetUserNameOfProfileAtIndex(profile_index
, username
);
1242 // Profile name and avatar are set by InitProfileUserPrefs and stored in the
1243 // profile. Use those values to setup the cache entry.
1244 base::string16 profile_name
=
1245 base::UTF8ToUTF16(profile
->GetPrefs()->GetString(prefs::kProfileName
));
1247 size_t icon_index
= profile
->GetPrefs()->GetInteger(
1248 prefs::kProfileAvatarIndex
);
1250 std::string supervised_user_id
=
1251 profile
->GetPrefs()->GetString(prefs::kSupervisedUserId
);
1253 cache
.AddProfileToCache(profile
->GetPath(),
1257 supervised_user_id
);
1259 if (profile
->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles
)) {
1260 cache
.SetProfileIsEphemeralAtIndex(
1261 cache
.GetIndexOfProfileWithPath(profile
->GetPath()), true);
1265 void ProfileManager::SetGuestProfilePrefs(Profile
* profile
) {
1266 PrefService
* prefs
= profile
->GetPrefs();
1267 prefs
->SetBoolean(prefs::kSigninAllowed
, false);
1268 prefs
->SetBoolean(bookmarks::prefs::kEditBookmarksEnabled
, false);
1269 prefs
->SetBoolean(bookmarks::prefs::kShowBookmarkBar
, false);
1270 prefs
->ClearPref(DefaultSearchManager::kDefaultSearchProviderDataPrefName
);
1271 // This can be removed in the future but needs to be present through
1272 // a release (or two) so that any existing installs get switched to
1273 // the new state and away from the previous "forced" state.
1274 IncognitoModePrefs::SetAvailability(prefs
, IncognitoModePrefs::ENABLED
);
1277 bool ProfileManager::ShouldGoOffTheRecord(Profile
* profile
) {
1278 #if defined(OS_CHROMEOS)
1279 if (profile
->GetPath().BaseName().value() == chrome::kInitialProfile
) {
1283 return profile
->IsGuestSession();
1286 void ProfileManager::RunCallbacks(const std::vector
<CreateCallback
>& callbacks
,
1288 Profile::CreateStatus status
) {
1289 for (size_t i
= 0; i
< callbacks
.size(); ++i
)
1290 callbacks
[i
].Run(profile
, status
);
1293 ProfileManager::ProfileInfo::ProfileInfo(
1300 ProfileManager::ProfileInfo::~ProfileInfo() {
1301 ProfileDestroyer::DestroyProfileWhenAppropriate(profile
.release());
1304 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1305 void ProfileManager::UpdateLastUser(Profile
* last_active
) {
1306 PrefService
* local_state
= g_browser_process
->local_state();
1307 DCHECK(local_state
);
1308 // Only keep track of profiles that we are managing; tests may create others.
1309 if (profiles_info_
.find(last_active
->GetPath()) != profiles_info_
.end()) {
1310 local_state
->SetString(prefs::kProfileLastUsed
,
1311 last_active
->GetPath().BaseName().MaybeAsASCII());
1313 ProfileInfoCache
& cache
= GetProfileInfoCache();
1314 size_t profile_index
=
1315 cache
.GetIndexOfProfileWithPath(last_active
->GetPath());
1316 if (profile_index
!= std::string::npos
)
1317 cache
.SetProfileActiveTimeAtIndex(profile_index
);
1321 ProfileManager::BrowserListObserver::BrowserListObserver(
1322 ProfileManager
* manager
)
1323 : profile_manager_(manager
) {
1324 BrowserList::AddObserver(this);
1327 ProfileManager::BrowserListObserver::~BrowserListObserver() {
1328 BrowserList::RemoveObserver(this);
1331 void ProfileManager::BrowserListObserver::OnBrowserAdded(
1332 Browser
* browser
) {}
1334 void ProfileManager::BrowserListObserver::OnBrowserRemoved(
1336 Profile
* profile
= browser
->profile();
1337 for (chrome::BrowserIterator it
; !it
.done(); it
.Next()) {
1338 if (it
->profile()->GetOriginalProfile() == profile
->GetOriginalProfile())
1339 // Not the last window for this profile.
1343 // If the last browser of a profile that is scheduled for deletion is closed
1345 base::FilePath path
= profile
->GetPath();
1346 if (profile
->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles
) &&
1347 !IsProfileMarkedForDeletion(path
)) {
1348 g_browser_process
->profile_manager()->ScheduleProfileForDeletion(
1349 path
, ProfileManager::CreateCallback());
1353 void ProfileManager::BrowserListObserver::OnBrowserSetLastActive(
1355 // If all browsers are being closed (e.g. the user is in the process of
1356 // shutting down), this event will be fired after each browser is
1357 // closed. This does not represent a user intention to change the active
1358 // browser so is not handled here.
1359 if (profile_manager_
->closing_all_browsers_
)
1362 Profile
* last_active
= browser
->profile();
1364 // Don't remember ephemeral profiles as last because they are not going to
1365 // persist after restart.
1366 if (last_active
->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles
))
1369 profile_manager_
->UpdateLastUser(last_active
);
1371 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
1373 void ProfileManager::OnNewActiveProfileLoaded(
1374 const base::FilePath
& profile_to_delete_path
,
1375 const base::FilePath
& new_active_profile_path
,
1376 const CreateCallback
& original_callback
,
1377 Profile
* loaded_profile
,
1378 Profile::CreateStatus status
) {
1379 DCHECK(status
!= Profile::CREATE_STATUS_LOCAL_FAIL
&&
1380 status
!= Profile::CREATE_STATUS_REMOTE_FAIL
);
1382 // Only run the code if the profile initialization has finished completely.
1383 if (status
!= Profile::CREATE_STATUS_INITIALIZED
)
1386 if (IsProfileMarkedForDeletion(new_active_profile_path
)) {
1387 // If the profile we tried to load as the next active profile has been
1388 // deleted, then retry deleting this profile to redo the logic to load
1389 // the next available profile.
1390 ScheduleProfileForDeletion(profile_to_delete_path
, original_callback
);
1394 FinishDeletingProfile(profile_to_delete_path
, new_active_profile_path
);
1395 if (!original_callback
.is_null())
1396 original_callback
.Run(loaded_profile
, status
);
1399 ProfileManagerWithoutInit::ProfileManagerWithoutInit(
1400 const base::FilePath
& user_data_dir
) : ProfileManager(user_data_dir
) {