-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile_manager.cc
1427 lines (1247 loc) · 53.9 KB
/
profile_manager.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/profiles/profile_manager.h"
#include <set>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/deferred_sequenced_task_runner.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/profiles/profile_destroyer.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/profiles/startup_task_runner_service.h"
#include "chrome/browser/profiles/startup_task_runner_service_factory.h"
#include "chrome/browser/signin/account_reconcilor_factory.h"
#include "chrome/browser/signin/account_tracker_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_iterator.h"
#include "chrome/browser/ui/sync/sync_promo_ui.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/user_metrics.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/extension_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest.h"
#endif
#if defined(ENABLE_SUPERVISED_USERS)
#include "chrome/browser/supervised_user/child_accounts/child_account_service.h"
#include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_service.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#endif
#if !defined(OS_IOS)
#include "chrome/browser/sessions/session_service_factory.h"
#include "chrome/browser/ui/browser_list.h"
#endif // !defined (OS_IOS)
#if defined(OS_WIN)
#include "base/win/metro.h"
#include "chrome/installer/util/browser_distribution.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/browser_process_platform_part_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#endif
using base::UserMetricsAction;
using content::BrowserThread;
namespace {
// Profiles that should be deleted on shutdown.
std::vector<base::FilePath>& ProfilesToDelete() {
CR_DEFINE_STATIC_LOCAL(std::vector<base::FilePath>, profiles_to_delete, ());
return profiles_to_delete;
}
int64 ComputeFilesSize(const base::FilePath& directory,
const base::FilePath::StringType& pattern) {
int64 running_size = 0;
base::FileEnumerator iter(directory, false, base::FileEnumerator::FILES,
pattern);
while (!iter.Next().empty())
running_size += iter.GetInfo().GetSize();
return running_size;
}
// Simple task to log the size of the current profile.
void ProfileSizeTask(const base::FilePath& path, int enabled_app_count) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
const int64 kBytesInOneMB = 1024 * 1024;
int64 size = ComputeFilesSize(path, FILE_PATH_LITERAL("*"));
int size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("History"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.HistorySize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("History*"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.TotalHistorySize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Cookies"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.CookiesSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Bookmarks"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.BookmarksSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Favicons"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.FaviconsSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Top Sites"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.TopSitesSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Visited Links"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.VisitedLinksSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Web Data"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.WebDataSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Extension*"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.ExtensionSize", size_MB);
size = ComputeFilesSize(path, FILE_PATH_LITERAL("Policy"));
size_MB = static_cast<int>(size / kBytesInOneMB);
UMA_HISTOGRAM_COUNTS_10000("Profile.PolicySize", size_MB);
// Count number of enabled apps in this profile, if we know.
if (enabled_app_count != -1)
UMA_HISTOGRAM_COUNTS_10000("Profile.AppCount", enabled_app_count);
}
void QueueProfileDirectoryForDeletion(const base::FilePath& path) {
ProfilesToDelete().push_back(path);
}
bool IsProfileMarkedForDeletion(const base::FilePath& profile_path) {
return std::find(ProfilesToDelete().begin(), ProfilesToDelete().end(),
profile_path) != ProfilesToDelete().end();
}
// Physically remove deleted profile directories from disk.
void NukeProfileFromDisk(const base::FilePath& profile_path) {
// Delete both the profile directory and its corresponding cache.
base::FilePath cache_path;
chrome::GetUserCacheDirectory(profile_path, &cache_path);
base::DeleteFile(profile_path, true);
base::DeleteFile(cache_path, true);
}
#if defined(OS_CHROMEOS)
void CheckCryptohomeIsMounted(chromeos::DBusMethodCallStatus call_status,
bool is_mounted) {
if (call_status != chromeos::DBUS_METHOD_CALL_SUCCESS) {
LOG(ERROR) << "IsMounted call failed.";
return;
}
if (!is_mounted)
LOG(ERROR) << "Cryptohome is not mounted.";
}
#endif
#if defined(ENABLE_EXTENSIONS)
// Returns the number of installed (and enabled) apps, excluding any component
// apps.
size_t GetEnabledAppCount(Profile* profile) {
size_t installed_apps = 0u;
const extensions::ExtensionSet& extensions =
extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
for (extensions::ExtensionSet::const_iterator iter = extensions.begin();
iter != extensions.end();
++iter) {
if ((*iter)->is_app() &&
(*iter)->location() != extensions::Manifest::COMPONENT) {
++installed_apps;
}
}
return installed_apps;
}
#endif // ENABLE_EXTENSIONS
} // namespace
//start NCSU
int applyIncognito=0;
//end NCSU
ProfileManager::ProfileManager(const base::FilePath& user_data_dir)
: user_data_dir_(user_data_dir),
logged_in_(false),
#if !defined(OS_ANDROID) && !defined(OS_IOS)
browser_list_observer_(this),
#endif
closing_all_browsers_(false) {
#if defined(OS_CHROMEOS)
registrar_.Add(
this,
chrome::NOTIFICATION_LOGIN_USER_CHANGED,
content::NotificationService::AllSources());
#endif
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_OPENED,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSED,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
content::NotificationService::AllSources());
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED,
content::NotificationService::AllSources());
if (ProfileShortcutManager::IsFeatureEnabled() && !user_data_dir_.empty())
profile_shortcut_manager_.reset(ProfileShortcutManager::Create(
this));
}
ProfileManager::~ProfileManager() {
}
#if defined(ENABLE_SESSION_SERVICE)
// static
void ProfileManager::ShutdownSessionServices() {
ProfileManager* pm = g_browser_process->profile_manager();
if (!pm) // Is NULL when running unit tests.
return;
std::vector<Profile*> profiles(pm->GetLoadedProfiles());
for (size_t i = 0; i < profiles.size(); ++i)
SessionServiceFactory::ShutdownForProfile(profiles[i]);
}
#endif
// static
void ProfileManager::NukeDeletedProfilesFromDisk() {
for (std::vector<base::FilePath>::iterator it =
ProfilesToDelete().begin();
it != ProfilesToDelete().end();
++it) {
NukeProfileFromDisk(*it);
}
ProfilesToDelete().clear();
}
// static
Profile* ProfileManager::GetLastUsedProfile() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
return profile_manager->GetLastUsedProfile(profile_manager->user_data_dir_);
}
// static
Profile* ProfileManager::GetLastUsedProfileAllowedByPolicy() {
Profile* profile = GetLastUsedProfile();
if (profile->IsGuestSession() ||
IncognitoModePrefs::GetAvailability(profile->GetPrefs()) ==
IncognitoModePrefs::FORCED) {
return profile->GetOffTheRecordProfile();
}
return profile;
}
// static
std::vector<Profile*> ProfileManager::GetLastOpenedProfiles() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
return profile_manager->GetLastOpenedProfiles(
profile_manager->user_data_dir_);
}
// static
Profile* ProfileManager::GetPrimaryUserProfile() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
#if defined(OS_CHROMEOS)
if (!profile_manager->IsLoggedIn() ||
!user_manager::UserManager::IsInitialized())
return profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
profile_manager->user_data_dir());
user_manager::UserManager* manager = user_manager::UserManager::Get();
// Note: The ProfileHelper will take care of guest profiles.
return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(
manager->GetPrimaryUser());
#else
return profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
profile_manager->user_data_dir());
#endif
}
// static
Profile* ProfileManager::GetActiveUserProfile() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
#if defined(OS_CHROMEOS)
if (!profile_manager)
return NULL;
if (!profile_manager->IsLoggedIn() ||
!user_manager::UserManager::IsInitialized()) {
return profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
profile_manager->user_data_dir());
}
user_manager::UserManager* manager = user_manager::UserManager::Get();
const user_manager::User* user = manager->GetActiveUser();
// To avoid an endless loop (crbug.com/334098) we have to additionally check
// if the profile of the user was already created. If the profile was not yet
// created we load the profile using the profile directly.
// TODO: This should be cleaned up with the new profile manager.
if (user && user->is_profile_created())
return chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user);
#endif
Profile* profile =
profile_manager->GetActiveUserOrOffTheRecordProfileFromPath(
profile_manager->user_data_dir());
// |profile| could be null if the user doesn't have a profile yet and the path
// is on a read-only volume (preventing Chrome from making a new one).
// However, most callers of this function immediately dereference the result
// which would lead to crashes in a variety of call sites. Assert here to
// figure out how common this is. http://crbug.com/383019
CHECK(profile) << profile_manager->user_data_dir().AsUTF8Unsafe();
return profile;
}
Profile* ProfileManager::GetProfile(const base::FilePath& profile_dir) {
TRACE_EVENT0("browser", "ProfileManager::GetProfile");
// If the profile is already loaded (e.g., chrome.exe launched twice), just
// return it.
Profile* profile = GetProfileByPath(profile_dir);
if (profile)
return profile;
return CreateAndInitializeProfile(profile_dir);
}
size_t ProfileManager::GetNumberOfProfiles() {
return GetProfileInfoCache().GetNumberOfProfiles();
}
void ProfileManager::CreateProfileAsync(
const base::FilePath& profile_path,
const CreateCallback& callback,
const base::string16& name,
const base::string16& icon_url,
const std::string& supervised_user_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
TRACE_EVENT1("browser,startup",
"ProfileManager::CreateProfileAsync",
"profile_path",
profile_path.AsUTF8Unsafe());
// Make sure that this profile is not pending deletion.
if (IsProfileMarkedForDeletion(profile_path)) {
if (!callback.is_null())
callback.Run(NULL, Profile::CREATE_STATUS_LOCAL_FAIL);
return;
}
// Create the profile if needed and collect its ProfileInfo.
ProfilesInfoMap::iterator iter = profiles_info_.find(profile_path);
ProfileInfo* info = NULL;
if (iter != profiles_info_.end()) {
info = iter->second.get();
} else {
// Initiate asynchronous creation process.
info = RegisterProfile(CreateProfileAsyncHelper(profile_path, this), false);
ProfileInfoCache& cache = GetProfileInfoCache();
// Get the icon index from the user's icon url
size_t icon_index;
std::string icon_url_std = base::UTF16ToASCII(icon_url);
if (profiles::IsDefaultAvatarIconUrl(icon_url_std, &icon_index)) {
// add profile to cache with user selected name and avatar
cache.AddProfileToCache(profile_path, name, base::string16(), icon_index,
supervised_user_id);
}
if (!supervised_user_id.empty()) {
content::RecordAction(
UserMetricsAction("ManagedMode_LocallyManagedUserCreated"));
}
ProfileMetrics::UpdateReportedProfilesStatistics(this);
}
// Call or enqueue the callback.
if (!callback.is_null()) {
if (iter != profiles_info_.end() && info->created) {
Profile* profile = info->profile.get();
// If this was the guest profile, apply settings and go OffTheRecord.
if (profile->GetPath() == ProfileManager::GetGuestProfilePath()) {
SetGuestProfilePrefs(profile);
profile = profile->GetOffTheRecordProfile();
}
// Profile has already been created. Run callback immediately.
callback.Run(profile, Profile::CREATE_STATUS_INITIALIZED);
} else {
// Profile is either already in the process of being created, or new.
// Add callback to the list.
info->callbacks.push_back(callback);
}
}
}
bool ProfileManager::IsValidProfile(Profile* profile) {
for (ProfilesInfoMap::iterator iter = profiles_info_.begin();
iter != profiles_info_.end(); ++iter) {
if (iter->second->created) {
Profile* candidate = iter->second->profile.get();
if (candidate == profile ||
(candidate->HasOffTheRecordProfile() &&
candidate->GetOffTheRecordProfile() == profile)) {
return true;
}
}
}
return false;
}
base::FilePath ProfileManager::GetInitialProfileDir() {
#if defined(OS_CHROMEOS)
if (logged_in_) {
return chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
}
#endif
base::FilePath relative_profile_dir;
// TODO(mirandac): should not automatically be default profile.
return relative_profile_dir.AppendASCII(chrome::kInitialProfile);
}
Profile* ProfileManager::GetLastUsedProfile(
const base::FilePath& user_data_dir) {
#if defined(OS_CHROMEOS)
// Use default login profile if user has not logged in yet.
if (!logged_in_) {
return GetActiveUserOrOffTheRecordProfileFromPath(user_data_dir);
} else {
// CrOS multi-profiles implementation is different so GetLastUsedProfile
// has custom implementation too.
base::FilePath profile_dir;
// In case of multi-profiles we ignore "last used profile" preference
// since it may refer to profile that has been in use in previous session.
// That profile dir may not be mounted in this session so instead return
// active profile from current session.
profile_dir = chromeos::ProfileHelper::Get()->GetActiveUserProfileDir();
base::FilePath profile_path(user_data_dir);
Profile* profile = GetProfile(profile_path.Append(profile_dir));
return profile->IsGuestSession() ? profile->GetOffTheRecordProfile() :
profile;
}
#endif
return GetProfile(GetLastUsedProfileDir(user_data_dir));
}
base::FilePath ProfileManager::GetLastUsedProfileDir(
const base::FilePath& user_data_dir) {
base::FilePath last_used_profile_dir(user_data_dir);
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
if (local_state->HasPrefPath(prefs::kProfileLastUsed)) {
return last_used_profile_dir.AppendASCII(
local_state->GetString(prefs::kProfileLastUsed));
}
return last_used_profile_dir.AppendASCII(chrome::kInitialProfile);
}
std::vector<Profile*> ProfileManager::GetLastOpenedProfiles(
const base::FilePath& user_data_dir) {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
std::vector<Profile*> to_return;
if (local_state->HasPrefPath(prefs::kProfilesLastActive) &&
local_state->GetList(prefs::kProfilesLastActive)) {
// Make a copy because the list might change in the calls to GetProfile.
scoped_ptr<base::ListValue> profile_list(
local_state->GetList(prefs::kProfilesLastActive)->DeepCopy());
base::ListValue::const_iterator it;
std::string profile;
for (it = profile_list->begin(); it != profile_list->end(); ++it) {
if (!(*it)->GetAsString(&profile) || profile.empty()) {
LOG(WARNING) << "Invalid entry in " << prefs::kProfilesLastActive;
continue;
}
to_return.push_back(GetProfile(user_data_dir.AppendASCII(profile)));
}
}
return to_return;
}
std::vector<Profile*> ProfileManager::GetLoadedProfiles() const {
std::vector<Profile*> profiles;
for (ProfilesInfoMap::const_iterator iter = profiles_info_.begin();
iter != profiles_info_.end(); ++iter) {
if (iter->second->created)
profiles.push_back(iter->second->profile.get());
}
return profiles;
}
Profile* ProfileManager::GetProfileByPathInternal(
const base::FilePath& path) const {
TRACE_EVENT0("browser", "ProfileManager::GetProfileByPathInternal");
ProfileInfo* profile_info = GetProfileInfoByPath(path);
return profile_info ? profile_info->profile.get() : nullptr;
}
Profile* ProfileManager::GetProfileByPath(const base::FilePath& path) const {
TRACE_EVENT0("browser", "ProfileManager::GetProfileByPath");
ProfileInfo* profile_info = GetProfileInfoByPath(path);
return (profile_info && profile_info->created) ? profile_info->profile.get()
: nullptr;
}
// static
base::FilePath ProfileManager::CreateMultiProfileAsync(
const base::string16& name,
const base::string16& icon_url,
const CreateCallback& callback,
const std::string& supervised_user_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
profile_manager->CreateProfileAsync(new_path,
callback,
name,
icon_url,
supervised_user_id);
return new_path;
}
//start NCSU
// static
base::FilePath ProfileManager::CreateMultiProfileAsyncIncognito(
const base::string16& name,
const base::string16& icon_url,
const CreateCallback& callback,
const std::string& supervised_user_id) {
applyIncognito = 2;
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
profile_manager->CreateProfileAsync(new_path,
callback,
name,
icon_url,
supervised_user_id);
return new_path;
}
//end NCSU
// static
base::FilePath ProfileManager::GetGuestProfilePath() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath guest_path = profile_manager->user_data_dir();
return guest_path.Append(chrome::kGuestProfileDir);
}
// static
base::FilePath ProfileManager::GetSystemProfilePath() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfileManager* profile_manager = g_browser_process->profile_manager();
base::FilePath system_path = profile_manager->user_data_dir();
return system_path.Append(chrome::kSystemProfileDir);
}
base::FilePath ProfileManager::GenerateNextProfileDirectoryPath() {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
DCHECK(profiles::IsMultipleProfilesEnabled());
// Create the next profile in the next available directory slot.
int next_directory = local_state->GetInteger(prefs::kProfilesNumCreated);
std::string profile_name = chrome::kMultiProfileDirPrefix;
profile_name.append(base::IntToString(next_directory));
base::FilePath new_path = user_data_dir_;
#if defined(OS_WIN)
new_path = new_path.Append(base::ASCIIToUTF16(profile_name));
#else
new_path = new_path.Append(profile_name);
#endif
local_state->SetInteger(prefs::kProfilesNumCreated, ++next_directory);
return new_path;
}
ProfileInfoCache& ProfileManager::GetProfileInfoCache() {
TRACE_EVENT0("browser", "ProfileManager::GetProfileInfoCache");
if (!profile_info_cache_) {
profile_info_cache_.reset(new ProfileInfoCache(
g_browser_process->local_state(), user_data_dir_));
}
return *profile_info_cache_.get();
}
ProfileShortcutManager* ProfileManager::profile_shortcut_manager() {
return profile_shortcut_manager_.get();
}
void ProfileManager::ScheduleProfileForDeletion(
const base::FilePath& profile_dir,
const CreateCallback& callback) {
DCHECK(profiles::IsMultipleProfilesEnabled());
// Cancel all in-progress downloads before deleting the profile to prevent a
// "Do you want to exit Google Chrome and cancel the downloads?" prompt
// (crbug.com/336725).
Profile* profile = GetProfileByPath(profile_dir);
if (profile) {
DownloadService* service =
DownloadServiceFactory::GetForBrowserContext(profile);
service->CancelDownloads();
}
ProfileInfoCache& cache = GetProfileInfoCache();
// If we're deleting the last (non-legacy-supervised) profile, then create a
// new profile in its place.
base::FilePath last_non_supervised_profile_path;
for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
base::FilePath cur_path = cache.GetPathOfProfileAtIndex(i);
// Make sure that this profile is not pending deletion, and is not
// legacy-supervised.
if (cur_path != profile_dir &&
!cache.ProfileIsLegacySupervisedAtIndex(i) &&
!IsProfileMarkedForDeletion(cur_path)) {
last_non_supervised_profile_path = cur_path;
break;
}
}
base::FilePath new_path;
if (last_non_supervised_profile_path.empty()) {
// If we are using --new-avatar-menu, then assign the default
// placeholder avatar and name. Otherwise, use random ones.
bool is_new_avatar_menu = switches::IsNewAvatarMenu();
int avatar_index = profiles::GetPlaceholderAvatarIndex();
base::string16 new_avatar_url = is_new_avatar_menu ?
base::UTF8ToUTF16(profiles::GetDefaultAvatarIconUrl(avatar_index)) :
base::string16();
base::string16 new_profile_name = is_new_avatar_menu ?
cache.ChooseNameForNewProfile(avatar_index) : base::string16();
new_path = GenerateNextProfileDirectoryPath();
CreateProfileAsync(new_path,
base::Bind(&ProfileManager::OnNewActiveProfileLoaded,
base::Unretained(this),
profile_dir,
new_path,
callback),
new_profile_name,
new_avatar_url,
std::string());
ProfileMetrics::LogProfileAddNewUser(
ProfileMetrics::ADD_NEW_USER_LAST_DELETED);
return;
}
#if defined(OS_MACOSX)
// On the Mac, the browser process is not killed when all browser windows are
// closed, so just in case we are deleting the active profile, and no other
// profile has been loaded, we must pre-load a next one.
const std::string last_used_profile =
g_browser_process->local_state()->GetString(prefs::kProfileLastUsed);
if (last_used_profile == profile_dir.BaseName().MaybeAsASCII() ||
last_used_profile == GetGuestProfilePath().BaseName().MaybeAsASCII()) {
CreateProfileAsync(last_non_supervised_profile_path,
base::Bind(&ProfileManager::OnNewActiveProfileLoaded,
base::Unretained(this),
profile_dir,
last_non_supervised_profile_path,
CreateCallback()),
base::string16(),
base::string16(),
std::string());
return;
}
#endif // defined(OS_MACOSX)
FinishDeletingProfile(profile_dir, last_non_supervised_profile_path);
}
// static
void ProfileManager::CleanUpStaleProfiles(
const std::vector<base::FilePath>& profile_paths) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
for (std::vector<base::FilePath>::const_iterator it = profile_paths.begin();
it != profile_paths.end(); ++it) {
NukeProfileFromDisk(*it);
}
}
void ProfileManager::AutoloadProfiles() {
// If running in the background is disabled for the browser, do not autoload
// any profiles.
PrefService* local_state = g_browser_process->local_state();
if (!local_state->HasPrefPath(prefs::kBackgroundModeEnabled) ||
!local_state->GetBoolean(prefs::kBackgroundModeEnabled)) {
return;
}
ProfileInfoCache& cache = GetProfileInfoCache();
size_t number_of_profiles = cache.GetNumberOfProfiles();
for (size_t p = 0; p < number_of_profiles; ++p) {
if (cache.GetBackgroundStatusOfProfileAtIndex(p)) {
// If status is true, that profile is running background apps. By calling
// GetProfile, we automatically cause the profile to be loaded which will
// register it with the BackgroundModeManager.
GetProfile(cache.GetPathOfProfileAtIndex(p));
}
}
}
void ProfileManager::InitProfileUserPrefs(Profile* profile) {
TRACE_EVENT0("browser", "ProfileManager::InitProfileUserPrefs");
ProfileInfoCache& cache = GetProfileInfoCache();
if (profile->GetPath().DirName() != cache.GetUserDataDir())
return;
size_t avatar_index;
std::string profile_name;
std::string supervised_user_id;
if (profile->IsGuestSession()) {
profile_name = l10n_util::GetStringUTF8(IDS_PROFILES_GUEST_PROFILE_NAME);
avatar_index = 0;
} else {
size_t profile_cache_index =
cache.GetIndexOfProfileWithPath(profile->GetPath());
// If the cache has an entry for this profile, use the cache data.
if (profile_cache_index != std::string::npos) {
avatar_index =
cache.GetAvatarIconIndexOfProfileAtIndex(profile_cache_index);
profile_name =
base::UTF16ToUTF8(cache.GetNameOfProfileAtIndex(profile_cache_index));
supervised_user_id =
cache.GetSupervisedUserIdOfProfileAtIndex(profile_cache_index);
} else if (profile->GetPath() ==
profiles::GetDefaultProfileDir(cache.GetUserDataDir())) {
// The --new-avatar-menu flag no longer uses the "First User" name.
bool is_new_avatar_menu = switches::IsNewAvatarMenu();
avatar_index = profiles::GetPlaceholderAvatarIndex();
profile_name = is_new_avatar_menu ?
base::UTF16ToUTF8(cache.ChooseNameForNewProfile(avatar_index)) :
l10n_util::GetStringUTF8(IDS_DEFAULT_PROFILE_NAME);
} else {
avatar_index = cache.ChooseAvatarIconIndexForNewProfile();
profile_name =
base::UTF16ToUTF8(cache.ChooseNameForNewProfile(avatar_index));
}
}
if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileAvatarIndex))
profile->GetPrefs()->SetInteger(prefs::kProfileAvatarIndex, avatar_index);
if (!profile->GetPrefs()->HasPrefPath(prefs::kProfileName))
profile->GetPrefs()->SetString(prefs::kProfileName, profile_name);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
bool force_supervised_user_id =
#if defined(OS_CHROMEOS)
g_browser_process->platform_part()
->profile_helper()
->GetSigninProfileDir() != profile->GetPath() &&
#endif
command_line->HasSwitch(switches::kSupervisedUserId);
if (force_supervised_user_id) {
supervised_user_id =
command_line->GetSwitchValueASCII(switches::kSupervisedUserId);
}
if (force_supervised_user_id ||
!profile->GetPrefs()->HasPrefPath(prefs::kSupervisedUserId)) {
profile->GetPrefs()->SetString(prefs::kSupervisedUserId,
supervised_user_id);
}
#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
// If the lock enabled algorithm changed, update this profile's lock status.
if (switches::IsNewProfileManagement())
profiles::UpdateIsProfileLockEnabledIfNeeded(profile);
#endif
}
void ProfileManager::RegisterTestingProfile(Profile* profile,
bool add_to_cache,
bool start_deferred_task_runners) {
RegisterProfile(profile, true);
if (add_to_cache) {
InitProfileUserPrefs(profile);
AddProfileToCache(profile);
}
if (start_deferred_task_runners) {
StartupTaskRunnerServiceFactory::GetForProfile(profile)->
StartDeferredTaskRunners();
}
}
void ProfileManager::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
#if defined(OS_CHROMEOS)
if (type == chrome::NOTIFICATION_LOGIN_USER_CHANGED) {
logged_in_ = true;
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kTestType)) {
// If we don't have a mounted profile directory we're in trouble.
// TODO(davemoore) Once we have better api this check should ensure that
// our profile directory is the one that's mounted, and that it's mounted
// as the current user.
chromeos::DBusThreadManager::Get()->GetCryptohomeClient()->IsMounted(
base::Bind(&CheckCryptohomeIsMounted));
// Confirm that we hadn't loaded the new profile previously.
base::FilePath default_profile_dir = user_data_dir_.Append(
GetInitialProfileDir());
CHECK(!GetProfileByPathInternal(default_profile_dir))
<< "The default profile was loaded before we mounted the cryptohome.";
}
return;
}
#endif
bool save_active_profiles = false;
switch (type) {
case chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST: {
// Ignore any browsers closing from now on.
closing_all_browsers_ = true;
save_active_profiles = true;
break;
}
case chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED: {
// This will cancel the shutdown process, so the active profiles are
// tracked again. Also, as the active profiles may have changed (i.e. if
// some windows were closed) we save the current list of active profiles
// again.
closing_all_browsers_ = false;
save_active_profiles = true;
break;
}
case chrome::NOTIFICATION_BROWSER_OPENED: {
Browser* browser = content::Source<Browser>(source).ptr();
DCHECK(browser);
Profile* profile = browser->profile();
DCHECK(profile);
bool is_ephemeral =
profile->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles);
if (!profile->IsOffTheRecord() && !is_ephemeral &&
++browser_counts_[profile] == 1) {
active_profiles_.push_back(profile);
save_active_profiles = true;
}
// If browsers are opening, we can't be closing all the browsers. This
// can happen if the application was exited, but background mode or
// packaged apps prevented the process from shutting down, and then
// a new browser window was opened.
closing_all_browsers_ = false;
break;
}
case chrome::NOTIFICATION_BROWSER_CLOSED: {
Browser* browser = content::Source<Browser>(source).ptr();
DCHECK(browser);
Profile* profile = browser->profile();
DCHECK(profile);
if (!profile->IsOffTheRecord() && --browser_counts_[profile] == 0) {
active_profiles_.erase(std::find(active_profiles_.begin(),
active_profiles_.end(), profile));
save_active_profiles = !closing_all_browsers_;
}
break;
}
default: {
NOTREACHED();
break;
}
}
if (save_active_profiles) {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
ListPrefUpdate update(local_state, prefs::kProfilesLastActive);
base::ListValue* profile_list = update.Get();
profile_list->Clear();
// crbug.com/120112 -> several non-incognito profiles might have the same
// GetPath().BaseName(). In that case, we cannot restore both
// profiles. Include each base name only once in the last active profile
// list.
std::set<std::string> profile_paths;
std::vector<Profile*>::const_iterator it;
for (it = active_profiles_.begin(); it != active_profiles_.end(); ++it) {
std::string profile_path = (*it)->GetPath().BaseName().MaybeAsASCII();
// Some profiles might become ephemeral after they are created.
if (!(*it)->GetPrefs()->GetBoolean(prefs::kForceEphemeralProfiles) &&
profile_paths.find(profile_path) == profile_paths.end()) {
profile_paths.insert(profile_path);
profile_list->Append(new base::StringValue(profile_path));
}
}
}
}
void ProfileManager::OnProfileCreated(Profile* profile,
bool success,
bool is_new_profile) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ProfilesInfoMap::iterator iter = profiles_info_.find(profile->GetPath());
DCHECK(iter != profiles_info_.end());
ProfileInfo* info = iter->second.get();
std::vector<CreateCallback> callbacks;
info->callbacks.swap(callbacks);
// Invoke CREATED callback for normal profiles.
bool go_off_the_record = ShouldGoOffTheRecord(profile);
if (applyIncognito>0) {go_off_the_record=true;}
if (success && !go_off_the_record)
RunCallbacks(callbacks, profile, Profile::CREATE_STATUS_CREATED);
// Perform initialization.
if (success) {
DoFinalInit(profile, go_off_the_record);
if (go_off_the_record)
profile = profile->GetOffTheRecordProfile();
info->created = true;
} else {
profile = NULL;
profiles_info_.erase(iter);
// TODO(yiyaoliu): This is temporary, remove it after it's not used.
UMA_HISTOGRAM_COUNTS_100("UMA.ProfilesCount.AfterErase",
profiles_info_.size());
}