1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/sync/profile_sync_service_factory.h"
6 
7 #include <string>
8 #include <utility>
9 
10 #include "base/bind.h"
11 #include "base/feature_list.h"
12 #include "base/memory/singleton.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/time/time.h"
15 #include "build/build_config.h"
16 #include "chrome/browser/autofill/personal_data_manager_factory.h"
17 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
18 #include "chrome/browser/browser_process.h"
19 #include "chrome/browser/consent_auditor/consent_auditor_factory.h"
20 #include "chrome/browser/defaults.h"
21 #include "chrome/browser/favicon/favicon_service_factory.h"
22 #include "chrome/browser/gcm/gcm_profile_service_factory.h"
23 #include "chrome/browser/history/history_service_factory.h"
24 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
25 #include "chrome/browser/password_manager/account_password_store_factory.h"
26 #include "chrome/browser/password_manager/password_store_factory.h"
27 #include "chrome/browser/policy/profile_policy_connector.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/profiles/profile_manager.h"
30 #include "chrome/browser/search_engines/template_url_service_factory.h"
31 #include "chrome/browser/security_events/security_event_recorder_factory.h"
32 #include "chrome/browser/sharing/sharing_message_bridge_factory.h"
33 #include "chrome/browser/signin/about_signin_internals_factory.h"
34 #include "chrome/browser/signin/identity_manager_factory.h"
35 #include "chrome/browser/spellchecker/spellcheck_factory.h"
36 #include "chrome/browser/sync/bookmark_sync_service_factory.h"
37 #include "chrome/browser/sync/chrome_sync_client.h"
38 #include "chrome/browser/sync/device_info_sync_service_factory.h"
39 #include "chrome/browser/sync/model_type_store_service_factory.h"
40 #include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h"
41 #include "chrome/browser/sync/session_sync_service_factory.h"
42 #include "chrome/browser/sync/sync_invalidations_service_factory.h"
43 #include "chrome/browser/sync/user_event_service_factory.h"
44 #include "chrome/browser/themes/theme_service_factory.h"
45 #include "chrome/browser/undo/bookmark_undo_service_factory.h"
46 #include "chrome/browser/web_applications/web_app_provider_factory.h"
47 #include "chrome/browser/web_data_service_factory.h"
48 #include "chrome/common/buildflags.h"
49 #include "chrome/common/channel_info.h"
50 #include "components/autofill/core/browser/personal_data_manager.h"
51 #include "components/invalidation/impl/profile_identity_provider.h"
52 #include "components/invalidation/impl/profile_invalidation_provider.h"
53 #include "components/keyed_service/content/browser_context_dependency_manager.h"
54 #include "components/network_time/network_time_tracker.h"
55 #include "components/sync/driver/profile_sync_service.h"
56 #include "components/sync/driver/sync_driver_switches.h"
57 #include "content/public/browser/browser_context.h"
58 #include "content/public/browser/browser_task_traits.h"
59 #include "content/public/browser/network_service_instance.h"
60 #include "content/public/browser/storage_partition.h"
61 #include "extensions/buildflags/buildflags.h"
62 #include "services/network/public/cpp/shared_url_loader_factory.h"
63 #include "url/gurl.h"
64 
65 #if BUILDFLAG(ENABLE_EXTENSIONS)
66 #include "extensions/browser/api/storage/storage_frontend.h"
67 #include "extensions/browser/extension_system_provider.h"
68 #include "extensions/browser/extensions_browser_client.h"
69 #endif  // BUILDFLAG(ENABLE_EXTENSIONS)
70 
71 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
72 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
73 #include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
74 #endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)
75 
76 #if defined(OS_CHROMEOS)
77 #include "chrome/browser/chromeos/printing/synced_printers_manager_factory.h"
78 #include "chrome/browser/sync/wifi_configuration_sync_service_factory.h"
79 #include "chromeos/constants/chromeos_features.h"
80 #endif  // defined(OS_CHROMEOS)
81 
82 namespace {
83 
UpdateNetworkTimeOnUIThread(base::Time network_time,base::TimeDelta resolution,base::TimeDelta latency,base::TimeTicks post_time)84 void UpdateNetworkTimeOnUIThread(base::Time network_time,
85                                  base::TimeDelta resolution,
86                                  base::TimeDelta latency,
87                                  base::TimeTicks post_time) {
88   g_browser_process->network_time_tracker()->UpdateNetworkTime(
89       network_time, resolution, latency, post_time);
90 }
91 
UpdateNetworkTime(const base::Time & network_time,const base::TimeDelta & resolution,const base::TimeDelta & latency)92 void UpdateNetworkTime(const base::Time& network_time,
93                        const base::TimeDelta& resolution,
94                        const base::TimeDelta& latency) {
95   content::GetUIThreadTaskRunner({})->PostTask(
96       FROM_HERE, base::BindOnce(&UpdateNetworkTimeOnUIThread, network_time,
97                                 resolution, latency, base::TimeTicks::Now()));
98 }
99 
100 }  // anonymous namespace
101 
102 // static
GetInstance()103 ProfileSyncServiceFactory* ProfileSyncServiceFactory::GetInstance() {
104   return base::Singleton<ProfileSyncServiceFactory>::get();
105 }
106 
107 // static
GetForProfile(Profile * profile)108 syncer::SyncService* ProfileSyncServiceFactory::GetForProfile(
109     Profile* profile) {
110   if (!switches::IsSyncAllowedByFlag()) {
111     return nullptr;
112   }
113 
114   return static_cast<syncer::SyncService*>(
115       GetInstance()->GetServiceForBrowserContext(profile, true));
116 }
117 
118 // static
119 syncer::ProfileSyncService*
GetAsProfileSyncServiceForProfile(Profile * profile)120 ProfileSyncServiceFactory::GetAsProfileSyncServiceForProfile(Profile* profile) {
121   return static_cast<syncer::ProfileSyncService*>(GetForProfile(profile));
122 }
123 
ProfileSyncServiceFactory()124 ProfileSyncServiceFactory::ProfileSyncServiceFactory()
125     : BrowserContextKeyedServiceFactory(
126         "ProfileSyncService",
127         BrowserContextDependencyManager::GetInstance()) {
128   // The ProfileSyncService depends on various SyncableServices being around
129   // when it is shut down.  Specify those dependencies here to build the proper
130   // destruction order. Note that some of the dependencies are listed here but
131   // actually plumbed in ChromeSyncClient, which this factory constructs.
132   DependsOn(AboutSigninInternalsFactory::GetInstance());
133   DependsOn(AccountPasswordStoreFactory::GetInstance());
134   DependsOn(autofill::PersonalDataManagerFactory::GetInstance());
135   DependsOn(BookmarkModelFactory::GetInstance());
136   DependsOn(BookmarkSyncServiceFactory::GetInstance());
137   DependsOn(BookmarkUndoServiceFactory::GetInstance());
138   DependsOn(browser_sync::UserEventServiceFactory::GetInstance());
139   DependsOn(ConsentAuditorFactory::GetInstance());
140   DependsOn(DeviceInfoSyncServiceFactory::GetInstance());
141   DependsOn(FaviconServiceFactory::GetInstance());
142   DependsOn(gcm::GCMProfileServiceFactory::GetInstance());
143   DependsOn(HistoryServiceFactory::GetInstance());
144   DependsOn(IdentityManagerFactory::GetInstance());
145   DependsOn(invalidation::ProfileInvalidationProviderFactory::GetInstance());
146   DependsOn(SyncInvalidationsServiceFactory::GetInstance());
147   DependsOn(ModelTypeStoreServiceFactory::GetInstance());
148   DependsOn(PasswordStoreFactory::GetInstance());
149   DependsOn(SecurityEventRecorderFactory::GetInstance());
150   DependsOn(SendTabToSelfSyncServiceFactory::GetInstance());
151   DependsOn(SharingMessageBridgeFactory::GetInstance());
152   DependsOn(SpellcheckServiceFactory::GetInstance());
153 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
154   DependsOn(SupervisedUserServiceFactory::GetInstance());
155   DependsOn(SupervisedUserSettingsServiceFactory::GetInstance());
156 #endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)
157   DependsOn(SessionSyncServiceFactory::GetInstance());
158   DependsOn(TemplateURLServiceFactory::GetInstance());
159 #if !defined(OS_ANDROID)
160   DependsOn(ThemeServiceFactory::GetInstance());
161 #endif  // !defined(OS_ANDROID)
162   DependsOn(WebDataServiceFactory::GetInstance());
163 #if BUILDFLAG(ENABLE_EXTENSIONS)
164   DependsOn(
165       extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
166   DependsOn(extensions::StorageFrontend::GetFactoryInstance());
167   DependsOn(web_app::WebAppProviderFactory::GetInstance());
168 #endif  // BUILDFLAG(ENABLE_EXTENSIONS)
169 #if defined(OS_CHROMEOS)
170   DependsOn(chromeos::SyncedPrintersManagerFactory::GetInstance());
171   DependsOn(WifiConfigurationSyncServiceFactory::GetInstance());
172 #endif  // defined(OS_CHROMEOS)
173 }
174 
175 ProfileSyncServiceFactory::~ProfileSyncServiceFactory() = default;
176 
BuildServiceInstanceFor(content::BrowserContext * context) const177 KeyedService* ProfileSyncServiceFactory::BuildServiceInstanceFor(
178     content::BrowserContext* context) const {
179   syncer::ProfileSyncService::InitParams init_params;
180 
181   Profile* profile = Profile::FromBrowserContext(context);
182 
183   std::unique_ptr<browser_sync::ChromeSyncClient> sync_client =
184       client_factory_
185           ? client_factory_->Run(profile)
186           : std::make_unique<browser_sync::ChromeSyncClient>(profile);
187 
188   init_params.sync_client = std::move(sync_client);
189   init_params.network_time_update_callback =
190       base::BindRepeating(&UpdateNetworkTime);
191   init_params.url_loader_factory =
192       content::BrowserContext::GetDefaultStoragePartition(profile)
193           ->GetURLLoaderFactoryForBrowserProcess();
194   init_params.network_connection_tracker =
195       content::GetNetworkConnectionTracker();
196   init_params.channel = chrome::GetChannel();
197   init_params.debug_identifier = profile->GetDebugName();
198 
199   init_params.policy_service =
200       profile->GetProfilePolicyConnector()->policy_service();
201   bool local_sync_backend_enabled = false;
202 
203 // Only check the local sync backend pref on the supported platforms of
204 // Windows, Mac and Linux.
205 #if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || defined(OS_BSD)
206   syncer::SyncPrefs prefs(profile->GetPrefs());
207   local_sync_backend_enabled = prefs.IsLocalSyncEnabled();
208   UMA_HISTOGRAM_BOOLEAN("Sync.Local.Enabled", local_sync_backend_enabled);
209 
210   if (local_sync_backend_enabled) {
211     base::FilePath local_sync_backend_folder =
212         init_params.sync_client->GetLocalSyncBackendFolder();
213 
214     // If the user has not specified a folder and we can't get the default
215     // roaming profile location the sync service will not be created.
216     UMA_HISTOGRAM_BOOLEAN("Sync.Local.RoamingProfileUnavailable",
217                           local_sync_backend_folder.empty());
218     if (local_sync_backend_folder.empty())
219       return nullptr;
220 
221     init_params.start_behavior = syncer::ProfileSyncService::AUTO_START;
222   }
223 #endif  // defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || defined(OS_BSD)
224 
225   if (!local_sync_backend_enabled) {
226     // Always create the GCMProfileService instance such that we can listen to
227     // the profile notifications and purge the GCM store when the profile is
228     // being signed out.
229     gcm::GCMProfileServiceFactory::GetForProfile(profile);
230 
231     // TODO(atwilson): Change AboutSigninInternalsFactory to load on startup
232     // once http://crbug.com/171406 has been fixed.
233     AboutSigninInternalsFactory::GetForProfile(profile);
234 
235     init_params.identity_manager =
236         IdentityManagerFactory::GetForProfile(profile);
237 
238     auto* fcm_invalidation_provider =
239         invalidation::ProfileInvalidationProviderFactory::GetForProfile(
240             profile);
241     if (fcm_invalidation_provider) {
242       init_params.invalidations_identity_provider =
243           fcm_invalidation_provider->GetIdentityProvider();
244     }
245 
246     // TODO(tim): Currently, AUTO/MANUAL settings refer to the *first* time sync
247     // is set up and *not* a browser restart for a manual-start platform (where
248     // sync has already been set up, and should be able to start without user
249     // intervention). We can get rid of the browser_default eventually, but
250     // need to take care that ProfileSyncService doesn't get tripped up between
251     // those two cases. Bug 88109.
252     bool is_auto_start = browser_defaults::kSyncAutoStarts;
253 #if defined(OS_CHROMEOS)
254     if (chromeos::features::IsSplitSettingsSyncEnabled())
255       is_auto_start = false;
256 #endif
257     init_params.start_behavior = is_auto_start
258                                      ? syncer::ProfileSyncService::AUTO_START
259                                      : syncer::ProfileSyncService::MANUAL_START;
260   }
261 
262   auto pss =
263       std::make_unique<syncer::ProfileSyncService>(std::move(init_params));
264   pss->Initialize();
265 
266   // Hook PSS into PersonalDataManager (a circular dependency).
267   autofill::PersonalDataManager* pdm =
268       autofill::PersonalDataManagerFactory::GetForProfile(profile);
269   pdm->OnSyncServiceInitialized(pss.get());
270 
271   return pss.release();
272 }
273 
274 // static
HasSyncService(Profile * profile)275 bool ProfileSyncServiceFactory::HasSyncService(Profile* profile) {
276   return GetInstance()->GetServiceForBrowserContext(profile, false) != nullptr;
277 }
278 
279 // static
IsSyncAllowed(Profile * profile)280 bool ProfileSyncServiceFactory::IsSyncAllowed(Profile* profile) {
281   DCHECK(profile);
282   if (HasSyncService(profile)) {
283     syncer::SyncService* sync_service = GetForProfile(profile);
284     return !sync_service->HasDisableReason(
285                syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY);
286   }
287 
288   // No ProfileSyncService created yet - we don't want to create one, so just
289   // infer the accessible state by looking at prefs/command line flags.
290   syncer::SyncPrefs prefs(profile->GetPrefs());
291   return switches::IsSyncAllowedByFlag() &&
292          (!prefs.IsManaged() || prefs.IsLocalSyncEnabled());
293 }
294 
295 // static
296 std::vector<const syncer::SyncService*>
GetAllSyncServices()297 ProfileSyncServiceFactory::GetAllSyncServices() {
298   std::vector<Profile*> profiles =
299       g_browser_process->profile_manager()->GetLoadedProfiles();
300   std::vector<const syncer::SyncService*> sync_services;
301   for (Profile* profile : profiles) {
302     if (HasSyncService(profile)) {
303       sync_services.push_back(GetForProfile(profile));
304     }
305   }
306   return sync_services;
307 }
308 
309 // static
SetSyncClientFactoryForTest(SyncClientFactory * client_factory)310 void ProfileSyncServiceFactory::SetSyncClientFactoryForTest(
311     SyncClientFactory* client_factory) {
312   client_factory_ = client_factory;
313 }
314 
315 // static
316 ProfileSyncServiceFactory::SyncClientFactory*
317     ProfileSyncServiceFactory::client_factory_ = nullptr;
318