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/sync/profile_sync_service.h"
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/logging.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/metrics/histogram.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "build/build_config.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/defaults.h"
28 #include "chrome/browser/net/chrome_cookie_notification_details.h"
29 #include "chrome/browser/prefs/pref_service_syncable.h"
30 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/signin/about_signin_internals.h"
32 #include "chrome/browser/signin/about_signin_internals_factory.h"
33 #include "chrome/browser/signin/profile_oauth2_token_service.h"
34 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
35 #include "chrome/browser/signin/signin_manager.h"
36 #include "chrome/browser/signin/signin_manager_factory.h"
37 #include "chrome/browser/sync/backend_migrator.h"
38 #include "chrome/browser/sync/glue/change_processor.h"
39 #include "chrome/browser/sync/glue/chrome_encryptor.h"
40 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
41 #include "chrome/browser/sync/glue/data_type_controller.h"
42 #include "chrome/browser/sync/glue/device_info.h"
43 #include "chrome/browser/sync/glue/favicon_cache.h"
44 #include "chrome/browser/sync/glue/session_data_type_controller.h"
45 #include "chrome/browser/sync/glue/session_model_associator.h"
46 #include "chrome/browser/sync/glue/sync_backend_host.h"
47 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
48 #include "chrome/browser/sync/glue/sync_start_util.h"
49 #include "chrome/browser/sync/glue/synced_device_tracker.h"
50 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
51 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
52 #include "chrome/browser/sync/sessions2/notification_service_sessions_router.h"
53 #include "chrome/browser/sync/sessions2/sessions_sync_manager.h"
54 #include "chrome/browser/sync/sync_global_error.h"
55 #include "chrome/browser/sync/user_selectable_sync_type.h"
56 #include "chrome/browser/ui/browser.h"
57 #include "chrome/browser/ui/browser_list.h"
58 #include "chrome/browser/ui/browser_window.h"
59 #include "chrome/browser/ui/global_error/global_error_service.h"
60 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
61 #include "chrome/common/chrome_switches.h"
62 #include "chrome/common/chrome_version_info.h"
63 #include "chrome/common/pref_names.h"
64 #include "chrome/common/url_constants.h"
65 #include "components/user_prefs/pref_registry_syncable.h"
66 #include "content/public/browser/notification_details.h"
67 #include "content/public/browser/notification_service.h"
68 #include "content/public/browser/notification_source.h"
69 #include "google_apis/gaia/gaia_constants.h"
70 #include "grit/generated_resources.h"
71 #include "net/cookies/cookie_monster.h"
72 #include "net/url_request/url_request_context_getter.h"
73 #include "sync/api/sync_error.h"
74 #include "sync/internal_api/public/configure_reason.h"
75 #include "sync/internal_api/public/http_bridge_network_resources.h"
76 #include "sync/internal_api/public/network_resources.h"
77 #include "sync/internal_api/public/sync_encryption_handler.h"
78 #include "sync/internal_api/public/util/experiments.h"
79 #include "sync/internal_api/public/util/sync_string_conversions.h"
80 #include "sync/js/js_arg_list.h"
81 #include "sync/js/js_event_details.h"
82 #include "sync/util/cryptographer.h"
83 #include "ui/base/l10n/l10n_util.h"
84 #include "ui/base/l10n/time_format.h"
86 #if defined(ENABLE_MANAGED_USERS)
87 #include "chrome/browser/managed_mode/managed_user_constants.h"
90 #if defined(OS_ANDROID)
91 #include "sync/internal_api/public/read_transaction.h"
94 using browser_sync::ChangeProcessor
;
95 using browser_sync::DataTypeController
;
96 using browser_sync::DataTypeManager
;
97 using browser_sync::FailedDataTypesHandler
;
98 using browser_sync::NotificationServiceSessionsRouter
;
99 using browser_sync::SyncBackendHost
;
100 using syncer::ModelType
;
101 using syncer::ModelTypeSet
;
102 using syncer::JsBackend
;
103 using syncer::JsController
;
104 using syncer::JsEventDetails
;
105 using syncer::JsEventHandler
;
106 using syncer::ModelSafeRoutingInfo
;
107 using syncer::SyncCredentials
;
108 using syncer::SyncProtocolError
;
109 using syncer::WeakHandle
;
111 typedef GoogleServiceAuthError AuthError
;
113 const char* ProfileSyncService::kSyncServerUrl
=
114 "https://clients4.google.com/chrome-sync";
116 const char* ProfileSyncService::kDevServerUrl
=
117 "https://clients4.google.com/chrome-sync/dev";
119 const char kSyncUnrecoverableErrorHistogram
[] =
120 "Sync.UnrecoverableErrors";
122 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
123 // Number of initial errors (in sequence) to ignore before applying
124 // exponential back-off rules.
127 // Initial delay for exponential back-off in ms.
130 // Factor by which the waiting time will be multiplied.
133 // Fuzzing percentage. ex: 10% will spread requests randomly
134 // between 90%-100% of the calculated time.
137 // Maximum amount of time we are willing to delay our request in ms.
138 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
139 // RequestAccessToken on connection state change after backoff
140 1000 * 3600 * 4, // 4 hours.
142 // Time to keep an entry from being discarded even when it
143 // has no significant state, -1 to never discard.
146 // Don't use initial delay unless the last request was an error.
150 bool ShouldShowActionOnUI(
151 const syncer::SyncProtocolError
& error
) {
152 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
153 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
154 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
157 ProfileSyncService::ProfileSyncService(
158 ProfileSyncComponentsFactory
* factory
,
160 SigninManagerBase
* signin_manager
,
161 ProfileOAuth2TokenService
* oauth2_token_service
,
162 StartBehavior start_behavior
)
163 : OAuth2TokenService::Consumer("sync"),
164 last_auth_error_(AuthError::AuthErrorNone()),
165 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
168 sync_prefs_(profile_
->GetPrefs()),
169 sync_service_url_(kDevServerUrl
),
170 data_type_requested_sync_startup_(false),
171 is_first_time_sync_configure_(false),
172 backend_initialized_(false),
173 sync_disabled_by_admin_(false),
174 is_auth_in_progress_(false),
175 signin_(signin_manager
),
176 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
177 expect_sync_configuration_aborted_(false),
178 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
179 encrypt_everything_(false),
180 encryption_pending_(false),
181 auto_start_enabled_(start_behavior
== AUTO_START
),
182 configure_status_(DataTypeManager::UNKNOWN
),
183 setup_in_progress_(false),
184 oauth2_token_service_(oauth2_token_service
),
185 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
187 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
188 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
189 network_resources_(new syncer::HttpBridgeNetworkResources
) {
191 // By default, dev, canary, and unbranded Chromium users will go to the
192 // development servers. Development servers have more features than standard
193 // sync servers. Users with officially-branded Chrome stable and beta builds
194 // will go to the standard sync servers.
196 // GetChannel hits the registry on Windows. See http://crbug.com/70380.
197 base::ThreadRestrictions::ScopedAllowIO allow_io
;
198 chrome::VersionInfo::Channel channel
= chrome::VersionInfo::GetChannel();
199 if (channel
== chrome::VersionInfo::CHANNEL_STABLE
||
200 channel
== chrome::VersionInfo::CHANNEL_BETA
) {
201 sync_service_url_
= GURL(kSyncServerUrl
);
204 if (CommandLine::ForCurrentProcess()->HasSwitch(
205 switches::kEnableSyncSessionsV2
)) {
206 syncer::SyncableService::StartSyncFlare
flare(
207 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
208 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
209 new NotificationServiceSessionsRouter(profile
, flare
));
210 sessions_sync_manager_
.reset(
211 new SessionsSyncManager(profile
, this, router
.Pass()));
215 ProfileSyncService::~ProfileSyncService() {
216 sync_prefs_
.RemoveSyncPrefObserver(this);
217 // Shutdown() should have been called before destruction.
218 CHECK(!backend_initialized_
);
221 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
222 // Exit if sync is disabled.
223 if (IsManaged() || sync_prefs_
.IsStartSuppressed())
226 // Sync is logged in if there is a non-empty effective username.
227 return !GetEffectiveUsername().empty();
230 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
231 if (!oauth2_token_service_
)
234 return oauth2_token_service_
->RefreshTokenIsAvailable(GetAccountIdToUse());
237 void ProfileSyncService::Initialize() {
240 // We clear this here (vs Shutdown) because we want to remember that an error
241 // happened on shutdown so we can display details (message, location) about it
245 sync_prefs_
.AddSyncPrefObserver(this);
247 // For now, the only thing we can do through policy is to turn sync off.
253 RegisterAuthNotifications();
255 if (!HasSyncSetupCompleted() || GetEffectiveUsername().empty()) {
256 // Clean up in case of previous crash / setup abort / signout.
260 TrySyncDatatypePrefRecovery();
265 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
266 DCHECK(!sync_initialized());
267 if (!HasSyncSetupCompleted())
270 // There was a bug where OnUserChoseDatatypes was not properly called on
271 // configuration (see crbug.com/154940). We detect this by checking whether
272 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
273 // completed, it means sync was not properly configured, so we manually
274 // set kSyncKeepEverythingSynced.
275 PrefService
* const pref_service
= profile_
->GetPrefs();
278 if (GetPreferredDataTypes().Size() > 1)
281 const PrefService::Preference
* keep_everything_synced
=
282 pref_service
->FindPreference(prefs::kSyncKeepEverythingSynced
);
283 // This will be false if the preference was properly set or if it's controlled
285 if (!keep_everything_synced
->IsDefaultValue())
288 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
289 // types now, before we configure.
290 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
291 sync_prefs_
.SetKeepEverythingSynced(true);
292 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
293 sync_prefs_
.SetPreferredDataTypes(registered_types
,
297 void ProfileSyncService::TryStart() {
298 if (!IsSyncEnabledAndLoggedIn())
301 // Don't start sync until tokens are loaded, because the user can be
302 // "signed in" long before the tokens get loaded, and we don't want to
303 // generate spurious auth errors.
304 if (!IsOAuthRefreshTokenAvailable())
307 // If we got here then tokens are loaded and user logged in and sync is
308 // enabled. If OAuth refresh token is not available then something is wrong.
309 // When PSS requests access token, OAuth2TokenService will return error and
310 // PSS will show error to user asking to reauthenticate.
311 UMA_HISTOGRAM_BOOLEAN("Sync.RefreshTokenAvailable",
312 IsOAuthRefreshTokenAvailable());
314 // If sync setup has completed we always start the backend. If the user is in
315 // the process of setting up now, we should start the backend to download
316 // account control state / encryption information). If autostart is enabled,
317 // but we haven't completed sync setup, we try to start sync anyway, since
318 // it's possible we crashed/shutdown after logging in but before the backend
319 // finished initializing the last time.
321 // However, the only time we actually need to start sync _immediately_ is if
322 // we haven't completed sync setup and the user is in the process of setting
323 // up - either they just signed in (for the first time) on an auto-start
324 // platform or they explicitly kicked off sync setup, and e.g we need to
325 // fetch account details like encryption state to populate UI. Otherwise,
326 // for performance reasons and maximizing parallelism at chrome startup, we
327 // defer the heavy lifting for sync init until things have calmed down.
328 if (HasSyncSetupCompleted()) {
329 if (!data_type_requested_sync_startup_
)
330 StartUp(STARTUP_BACKEND_DEFERRED
);
331 else if (start_up_time_
.is_null())
332 StartUp(STARTUP_IMMEDIATE
);
334 StartUpSlowBackendComponents();
335 } else if (setup_in_progress_
|| auto_start_enabled_
) {
336 // We haven't completed sync setup. Start immediately if the user explicitly
337 // kicked this off or we're supposed to automatically start syncing.
338 StartUp(STARTUP_IMMEDIATE
);
342 void ProfileSyncService::StartSyncingWithServer() {
344 backend_
->StartSyncingWithServer();
347 void ProfileSyncService::RegisterAuthNotifications() {
348 oauth2_token_service_
->AddObserver(this);
351 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
352 content::Source
<Profile
>(profile_
));
354 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT
,
355 content::Source
<Profile
>(profile_
));
358 void ProfileSyncService::UnregisterAuthNotifications() {
359 oauth2_token_service_
->RemoveObserver(this);
360 registrar_
.RemoveAll();
363 void ProfileSyncService::RegisterDataTypeController(
364 DataTypeController
* data_type_controller
) {
365 DCHECK_EQ(data_type_controllers_
.count(data_type_controller
->type()), 0U);
366 data_type_controllers_
[data_type_controller
->type()] =
367 data_type_controller
;
370 browser_sync::SessionModelAssociator
*
371 ProfileSyncService::GetSessionModelAssociatorDeprecated() {
372 if (!IsSessionsDataTypeControllerRunning())
375 // If we're using sessions V2, there's no model associator.
376 if (sessions_sync_manager_
.get())
379 return static_cast<browser_sync::SessionDataTypeController
*>(
380 data_type_controllers_
.find(
381 syncer::SESSIONS
)->second
.get())->GetModelAssociator();
384 bool ProfileSyncService::IsSessionsDataTypeControllerRunning() const {
385 return data_type_controllers_
.find(syncer::SESSIONS
) !=
386 data_type_controllers_
.end() &&
387 data_type_controllers_
.find(syncer::SESSIONS
)->second
->state() ==
388 DataTypeController::RUNNING
;
391 browser_sync::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
392 if (!IsSessionsDataTypeControllerRunning())
395 if (CommandLine::ForCurrentProcess()->HasSwitch(
396 switches::kEnableSyncSessionsV2
)) {
397 return sessions_sync_manager_
.get();
399 return GetSessionModelAssociatorDeprecated();
403 browser_sync::FaviconCache
* ProfileSyncService::GetFaviconCache() {
404 // TODO(tim): Clean this up (or remove) once there's only one implementation.
406 if (CommandLine::ForCurrentProcess()->HasSwitch(
407 switches::kEnableSyncSessionsV2
)) {
408 return sessions_sync_manager_
->GetFaviconCache();
409 } else if (GetSessionModelAssociatorDeprecated()) {
410 return GetSessionModelAssociatorDeprecated()->GetFaviconCache();
416 scoped_ptr
<browser_sync::DeviceInfo
>
417 ProfileSyncService::GetLocalDeviceInfo() const {
419 browser_sync::SyncedDeviceTracker
* device_tracker
=
420 backend_
->GetSyncedDeviceTracker();
422 return device_tracker
->ReadLocalDeviceInfo();
424 return scoped_ptr
<browser_sync::DeviceInfo
>();
427 scoped_ptr
<browser_sync::DeviceInfo
>
428 ProfileSyncService::GetDeviceInfo(const std::string
& client_id
) const {
430 browser_sync::SyncedDeviceTracker
* device_tracker
=
431 backend_
->GetSyncedDeviceTracker();
433 return device_tracker
->ReadDeviceInfo(client_id
);
435 return scoped_ptr
<browser_sync::DeviceInfo
>();
438 ScopedVector
<browser_sync::DeviceInfo
>
439 ProfileSyncService::GetAllSignedInDevices() const {
440 ScopedVector
<browser_sync::DeviceInfo
> devices
;
442 browser_sync::SyncedDeviceTracker
* device_tracker
=
443 backend_
->GetSyncedDeviceTracker();
444 if (device_tracker
) {
445 // TODO(lipalani) - Make device tracker return a scoped vector.
446 device_tracker
->GetAllSyncedDeviceInfo(&devices
);
449 return devices
.Pass();
452 std::string
ProfileSyncService::GetLocalSyncCacheGUID() const {
454 browser_sync::SyncedDeviceTracker
* device_tracker
=
455 backend_
->GetSyncedDeviceTracker();
456 if (device_tracker
) {
457 return device_tracker
->cache_guid();
460 return std::string();
463 // Notifies the observer of any device info changes.
464 void ProfileSyncService::AddObserverForDeviceInfoChange(
465 browser_sync::SyncedDeviceTracker::Observer
* observer
) {
467 browser_sync::SyncedDeviceTracker
* device_tracker
=
468 backend_
->GetSyncedDeviceTracker();
469 if (device_tracker
) {
470 device_tracker
->AddObserver(observer
);
475 // Removes the observer from device info change notification.
476 void ProfileSyncService::RemoveObserverForDeviceInfoChange(
477 browser_sync::SyncedDeviceTracker::Observer
* observer
) {
479 browser_sync::SyncedDeviceTracker
* device_tracker
=
480 backend_
->GetSyncedDeviceTracker();
481 if (device_tracker
) {
482 device_tracker
->RemoveObserver(observer
);
487 void ProfileSyncService::GetDataTypeControllerStates(
488 browser_sync::DataTypeController::StateMap
* state_map
) const {
489 for (browser_sync::DataTypeController::TypeMap::const_iterator iter
=
490 data_type_controllers_
.begin(); iter
!= data_type_controllers_
.end();
492 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
495 void ProfileSyncService::InitSettings() {
496 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
498 // Override the sync server URL from the command-line, if sync server
499 // command-line argument exists.
500 if (command_line
.HasSwitch(switches::kSyncServiceURL
)) {
501 std::string
value(command_line
.GetSwitchValueASCII(
502 switches::kSyncServiceURL
));
503 if (!value
.empty()) {
504 GURL
custom_sync_url(value
);
505 if (custom_sync_url
.is_valid()) {
506 sync_service_url_
= custom_sync_url
;
508 LOG(WARNING
) << "The following sync URL specified at the command-line "
509 << "is invalid: " << value
;
515 SyncCredentials
ProfileSyncService::GetCredentials() {
516 SyncCredentials credentials
;
517 credentials
.email
= GetEffectiveUsername();
518 DCHECK(!credentials
.email
.empty());
519 credentials
.sync_token
= access_token_
;
521 if (credentials
.sync_token
.empty())
522 credentials
.sync_token
= "credentials_lost";
526 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
532 SyncCredentials credentials
= GetCredentials();
534 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
535 profile_
->GetRequestContext());
537 if (delete_stale_data
)
540 scoped_ptr
<syncer::UnrecoverableErrorHandler
>
541 backend_unrecoverable_error_handler(
542 new browser_sync::BackendUnrecoverableErrorHandler(
543 MakeWeakHandle(weak_factory_
.GetWeakPtr())));
545 backend_
->Initialize(
552 scoped_ptr
<syncer::SyncManagerFactory
>(
553 new syncer::SyncManagerFactory
).Pass(),
554 backend_unrecoverable_error_handler
.Pass(),
555 &browser_sync::ChromeReportUnrecoverableError
,
556 network_resources_
.get());
559 void ProfileSyncService::CreateBackend() {
561 factory_
->CreateSyncBackendHost(
562 profile_
->GetDebugName(),
564 sync_prefs_
.AsWeakPtr()));
567 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
568 if (encryption_pending())
570 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
571 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
572 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
573 return !Intersection(preferred_types
, encrypted_types
).Empty();
576 void ProfileSyncService::OnSyncConfigureRetry() {
577 // Note: in order to handle auth failures that arise before the backend is
578 // initialized (e.g. from invalidation notifier, or downloading new control
579 // types), we have to gracefully handle configuration retries at all times.
580 // At this point an auth error badge should be shown, which once resolved
581 // will trigger a new sync cycle.
585 void ProfileSyncService::StartUp(StartUpDeferredOption deferred_option
) {
586 // Don't start up multiple times.
588 DVLOG(1) << "Skipping bringing up backend host.";
592 DCHECK(IsSyncEnabledAndLoggedIn());
594 if (start_up_time_
.is_null()) {
595 start_up_time_
= base::Time::Now();
596 last_synced_time_
= sync_prefs_
.GetLastSyncedTime();
598 #if defined(OS_CHROMEOS)
599 std::string bootstrap_token
= sync_prefs_
.GetEncryptionBootstrapToken();
600 if (bootstrap_token
.empty()) {
601 sync_prefs_
.SetEncryptionBootstrapToken(
602 sync_prefs_
.GetSpareBootstrapToken());
606 #if !defined(OS_ANDROID)
607 if (!sync_global_error_
) {
608 sync_global_error_
.reset(new SyncGlobalError(this, signin()));
609 GlobalErrorServiceFactory::GetForProfile(profile_
)->AddGlobalError(
610 sync_global_error_
.get());
611 AddObserver(sync_global_error_
.get());
615 // We don't care to prevent multiple calls to StartUp in deferred mode
616 // because it's fast and has no side effects.
617 DCHECK_EQ(STARTUP_BACKEND_DEFERRED
, deferred_option
);
620 if (deferred_option
== STARTUP_BACKEND_DEFERRED
&&
621 CommandLine::ForCurrentProcess()->
622 HasSwitch(switches::kSyncEnableDeferredStartup
)) {
626 StartUpSlowBackendComponents();
629 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
630 syncer::ModelType type
) {
631 DCHECK(syncer::UserTypes().Has(type
));
632 if (backend_
.get()) {
633 DVLOG(1) << "A data type requested sync startup, but it looks like "
634 "something else beat it to the punch.";
638 if (!GetActiveDataTypes().Has(type
)) {
639 // We can get here as datatype SyncableServices are typically wired up
640 // to the native datatype even if sync isn't enabled.
641 DVLOG(1) << "Dropping sync startup request because type "
642 << syncer::ModelTypeToString(type
) << "not enabled.";
646 if (CommandLine::ForCurrentProcess()->HasSwitch(
647 switches::kSyncEnableDeferredStartup
)) {
648 DVLOG(2) << "Data type requesting sync startup: "
649 << syncer::ModelTypeToString(type
);
650 // Measure the time spent waiting for init and the type that triggered it.
651 // We could measure the time spent deferred on a per-datatype basis, but
652 // for now this is probably sufficient.
653 if (!start_up_time_
.is_null()) {
654 // TODO(tim): Cache |type| and move this tracking to StartUp. I'd like
655 // to pull all the complicated init logic and state out of
656 // ProfileSyncService and have only a StartUp method, though. One step
657 // at a time. Bug 80149.
658 base::TimeDelta time_deferred
= base::Time::Now() - start_up_time_
;
659 UMA_HISTOGRAM_TIMES("Sync.Startup.TimeDeferred", time_deferred
);
660 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.TypeTriggeringInit",
661 ModelTypeToHistogramInt(type
),
662 syncer::MODEL_TYPE_COUNT
);
664 data_type_requested_sync_startup_
= true;
667 DVLOG(2) << "Ignoring data type request for sync startup: "
668 << syncer::ModelTypeToString(type
);
671 void ProfileSyncService::StartUpSlowBackendComponents() {
672 // Don't start up multiple times.
674 DVLOG(1) << "Skipping bringing up backend host.";
678 DCHECK(IsSyncEnabledAndLoggedIn());
681 // Initialize the backend. Every time we start up a new SyncBackendHost,
682 // we'll want to start from a fresh SyncDB, so delete any old one that might
684 InitializeBackend(!HasSyncSetupCompleted());
687 void ProfileSyncService::OnGetTokenSuccess(
688 const OAuth2TokenService::Request
* request
,
689 const std::string
& access_token
,
690 const base::Time
& expiration_time
) {
691 DCHECK_EQ(access_token_request_
, request
);
692 access_token_request_
.reset();
693 access_token_
= access_token
;
694 token_receive_time_
= base::Time::Now();
695 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
697 if (sync_prefs_
.SyncHasAuthError()) {
698 sync_prefs_
.SetSyncAuthError(false);
699 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
705 backend_
->UpdateCredentials(GetCredentials());
710 void ProfileSyncService::OnGetTokenFailure(
711 const OAuth2TokenService::Request
* request
,
712 const GoogleServiceAuthError
& error
) {
713 DCHECK_EQ(access_token_request_
, request
);
714 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
715 access_token_request_
.reset();
716 last_get_token_error_
= error
;
717 switch (error
.state()) {
718 case GoogleServiceAuthError::CONNECTION_FAILED
:
719 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
720 // Transient error. Retry after some time.
721 request_access_token_backoff_
.InformOfRequest(false);
722 next_token_request_time_
= base::Time::Now() +
723 request_access_token_backoff_
.GetTimeUntilRelease();
724 request_access_token_retry_timer_
.Start(
726 request_access_token_backoff_
.GetTimeUntilRelease(),
727 base::Bind(&ProfileSyncService::RequestAccessToken
,
728 weak_factory_
.GetWeakPtr()));
732 case GoogleServiceAuthError::SERVICE_ERROR
:
733 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
734 if (!sync_prefs_
.SyncHasAuthError()) {
735 sync_prefs_
.SetSyncAuthError(true);
736 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
737 AUTH_ERROR_ENCOUNTERED
,
743 // Show error to user.
744 UpdateAuthErrorState(error
);
749 void ProfileSyncService::OnRefreshTokenAvailable(
750 const std::string
& account_id
) {
751 if (account_id
== GetAccountIdToUse())
752 OnRefreshTokensLoaded();
755 void ProfileSyncService::OnRefreshTokenRevoked(
756 const std::string
& account_id
) {
757 if (!IsOAuthRefreshTokenAvailable()) {
758 access_token_
.clear();
759 // The additional check around IsOAuthRefreshTokenAvailable() above
760 // prevents us sounding the alarm if we actually have a valid token but
761 // a refresh attempt failed for any variety of reasons
762 // (e.g. flaky network). It's possible the token we do have is also
763 // invalid, but in that case we should already have (or can expect) an
764 // auth error sent from the sync backend.
765 UpdateAuthErrorState(
766 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
770 void ProfileSyncService::OnRefreshTokensLoaded() {
771 // This notification gets fired when OAuth2TokenService loads the tokens
773 // Initialize the backend if sync is enabled. If the sync token was
774 // not loaded, GetCredentials() will generate invalid credentials to
775 // cause the backend to generate an auth error (crbug.com/121755).
777 RequestAccessToken();
783 void ProfileSyncService::Shutdown() {
784 UnregisterAuthNotifications();
786 ShutdownImpl(browser_sync::SyncBackendHost::STOP
);
789 sync_thread_
->Stop();
792 void ProfileSyncService::ShutdownImpl(
793 browser_sync::SyncBackendHost::ShutdownOption option
) {
797 // First, we spin down the backend to stop change processing as soon as
799 base::Time shutdown_start_time
= base::Time::Now();
800 backend_
->StopSyncingForShutdown();
802 // Stop all data type controllers, if needed. Note that until Stop
803 // completes, it is possible in theory to have a ChangeProcessor apply a
804 // change from a native model. In that case, it will get applied to the sync
805 // database (which doesn't get destroyed until we destroy the backend below)
806 // as an unsynced change. That will be persisted, and committed on restart.
807 if (data_type_manager_
) {
808 if (data_type_manager_
->state() != DataTypeManager::STOPPED
) {
809 // When aborting as part of shutdown, we should expect an aborted sync
810 // configure result, else we'll dcheck when we try to read the sync error.
811 expect_sync_configuration_aborted_
= true;
812 data_type_manager_
->Stop();
814 data_type_manager_
.reset();
817 // Shutdown the migrator before the backend to ensure it doesn't pull a null
820 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
822 // Move aside the backend so nobody else tries to use it while we are
824 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
825 if (doomed_backend
) {
826 sync_thread_
= doomed_backend
->Shutdown(option
);
827 doomed_backend
.reset();
829 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
830 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
832 weak_factory_
.InvalidateWeakPtrs();
834 // Clear various flags.
835 start_up_time_
= base::Time();
836 expect_sync_configuration_aborted_
= false;
837 is_auth_in_progress_
= false;
838 backend_initialized_
= false;
839 cached_passphrase_
.clear();
840 access_token_
.clear();
841 encryption_pending_
= false;
842 encrypt_everything_
= false;
843 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
844 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
845 request_access_token_retry_timer_
.Stop();
846 // Revert to "no auth error".
847 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
848 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
850 if (sync_global_error_
) {
851 GlobalErrorServiceFactory::GetForProfile(profile_
)->RemoveGlobalError(
852 sync_global_error_
.get());
853 RemoveObserver(sync_global_error_
.get());
854 sync_global_error_
.reset(NULL
);
860 void ProfileSyncService::DisableForUser() {
861 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
862 // PSS clients don't think we're set up while we're shutting down.
863 sync_prefs_
.ClearPreferences();
864 ClearUnrecoverableError();
865 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD
);
868 bool ProfileSyncService::HasSyncSetupCompleted() const {
869 return sync_prefs_
.HasSyncSetupCompleted();
872 void ProfileSyncService::SetSyncSetupCompleted() {
873 sync_prefs_
.SetSyncSetupCompleted();
876 void ProfileSyncService::UpdateLastSyncedTime() {
877 last_synced_time_
= base::Time::Now();
878 sync_prefs_
.SetLastSyncedTime(last_synced_time_
);
881 void ProfileSyncService::NotifyObservers() {
882 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer
, observers_
,
884 // TODO(akalin): Make an Observer subclass that listens and does the
886 sync_js_controller_
.HandleJsEvent("onServiceStateChanged", JsEventDetails());
889 void ProfileSyncService::NotifySyncCycleCompleted() {
890 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer
, observers_
,
891 OnSyncCycleCompleted());
892 sync_js_controller_
.HandleJsEvent(
893 "onServiceStateChanged", JsEventDetails());
896 void ProfileSyncService::ClearStaleErrors() {
897 ClearUnrecoverableError();
898 last_actionable_error_
= SyncProtocolError();
899 // Clear the data type errors as well.
900 failed_data_types_handler_
.Reset();
903 void ProfileSyncService::ClearUnrecoverableError() {
904 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
905 unrecoverable_error_message_
.clear();
906 unrecoverable_error_location_
= tracked_objects::Location();
909 void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type
) {
910 if (data_type_controllers_
.count(data_type
) > 0)
915 // An invariant has been violated. Transition to an error state where we try
916 // to do as little work as possible, to avoid further corruption or crashes.
917 void ProfileSyncService::OnUnrecoverableError(
918 const tracked_objects::Location
& from_here
,
919 const std::string
& message
) {
920 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
921 // interface are assumed to originate within the syncer.
922 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
923 OnUnrecoverableErrorImpl(from_here
, message
, true);
926 void ProfileSyncService::OnUnrecoverableErrorImpl(
927 const tracked_objects::Location
& from_here
,
928 const std::string
& message
,
929 bool delete_sync_database
) {
930 DCHECK(HasUnrecoverableError());
931 unrecoverable_error_message_
= message
;
932 unrecoverable_error_location_
= from_here
;
934 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
935 unrecoverable_error_reason_
,
938 std::string location
;
939 from_here
.Write(true, true, &location
);
941 << "Unrecoverable error detected at " << location
942 << " -- ProfileSyncService unusable: " << message
;
944 // Shut all data types down.
945 base::MessageLoop::current()->PostTask(FROM_HERE
,
946 base::Bind(&ProfileSyncService::ShutdownImpl
,
947 weak_factory_
.GetWeakPtr(),
948 delete_sync_database
?
949 browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD
:
950 browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD
));
953 // TODO(zea): Move this logic into the DataTypeController/DataTypeManager.
954 void ProfileSyncService::DisableBrokenDatatype(
955 syncer::ModelType type
,
956 const tracked_objects::Location
& from_here
,
957 std::string message
) {
958 // First deactivate the type so that no further server changes are
959 // passed onto the change processor.
960 DeactivateDataType(type
);
962 syncer::SyncError
error(from_here
,
963 syncer::SyncError::DATATYPE_ERROR
,
967 std::map
<syncer::ModelType
, syncer::SyncError
> errors
;
968 errors
[type
] = error
;
970 // Update this before posting a task. So if a configure happens before
971 // the task that we are going to post, this type would still be disabled.
972 failed_data_types_handler_
.UpdateFailedDataTypes(errors
);
974 base::MessageLoop::current()->PostTask(FROM_HERE
,
975 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager
,
976 weak_factory_
.GetWeakPtr()));
979 void ProfileSyncService::OnBackendInitialized(
980 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
981 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
984 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
986 if (is_first_time_sync_configure_
) {
987 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
989 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
992 DCHECK(!start_up_time_
.is_null());
993 base::Time on_backend_initialized_time
= base::Time::Now();
994 base::TimeDelta delta
= on_backend_initialized_time
- start_up_time_
;
995 if (is_first_time_sync_configure_
) {
996 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
998 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1002 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1003 // and surface error UI to alert the user sync has stopped.
1004 // Keep the directory around for now so that on restart we will retry
1005 // again and potentially succeed in presence of transient file IO failures
1006 // or permissions issues, etc.
1008 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1009 // Unlike every other UnrecoverableError, it does not delete our sync data.
1010 // This exception made sense at the time it was implemented, but our new
1011 // directory corruption recovery mechanism makes it obsolete. By the time
1012 // we get here, we will have already tried and failed to delete the
1013 // directory. It would be no big deal if we tried to delete it again.
1014 OnInternalUnrecoverableError(FROM_HERE
,
1015 "BackendInitialize failure",
1017 ERROR_REASON_BACKEND_INIT_FAILURE
);
1021 backend_initialized_
= true;
1023 sync_js_controller_
.AttachJsBackend(js_backend
);
1024 debug_info_listener_
= debug_info_listener
;
1026 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1027 // backend is initialized. We want to call this before notifying observers in
1028 // case this operation affects the "passphrase required" status.
1029 ConsumeCachedPassphraseIfPossible();
1031 // The very first time the backend initializes is effectively the first time
1032 // we can say we successfully "synced". last_synced_time_ will only be null
1033 // in this case, because the pref wasn't restored on StartUp.
1034 if (last_synced_time_
.is_null()) {
1035 UpdateLastSyncedTime();
1038 if (auto_start_enabled_
&& !FirstSetupInProgress()) {
1039 // Backend is initialized but we're not in sync setup, so this must be an
1040 // autostart - mark our sync setup as completed and we'll start syncing
1042 SetSyncSetupCompleted();
1045 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1046 // data type configuration because observer may flag setup as complete and
1047 // trigger data type configuration.
1048 if (HasSyncSetupCompleted()) {
1049 ConfigureDataTypeManager();
1051 DCHECK(FirstSetupInProgress());
1057 void ProfileSyncService::OnSyncCycleCompleted() {
1058 UpdateLastSyncedTime();
1059 if (IsSessionsDataTypeControllerRunning()) {
1060 // Trigger garbage collection of old sessions now that we've downloaded
1061 // any new session data.
1062 if (sessions_sync_manager_
) {
1064 base::MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
1065 &browser_sync::SessionsSyncManager::DoGarbageCollection
,
1066 base::AsWeakPtr(sessions_sync_manager_
.get())));
1068 base::MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
1069 &browser_sync::SessionModelAssociator::DeleteStaleSessions
,
1070 GetSessionModelAssociatorDeprecated()->AsWeakPtr()));
1073 DVLOG(2) << "Notifying observers sync cycle completed";
1074 NotifySyncCycleCompleted();
1077 void ProfileSyncService::OnExperimentsChanged(
1078 const syncer::Experiments
& experiments
) {
1079 if (current_experiments_
.Matches(experiments
))
1082 // If this is a first time sync for a client, this will be called before
1083 // OnBackendInitialized() to ensure the new datatypes are available at sync
1084 // setup. As a result, the migrator won't exist yet. This is fine because for
1085 // first time sync cases we're only concerned with making the datatype
1087 if (migrator_
.get() &&
1088 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1089 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1093 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1094 syncer::ModelTypeSet to_add
;
1095 const syncer::ModelTypeSet to_register
=
1096 Difference(to_add
, registered_types
);
1097 DVLOG(2) << "OnExperimentsChanged called with types: "
1098 << syncer::ModelTypeSetToString(to_add
);
1099 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register
);
1101 for (syncer::ModelTypeSet::Iterator it
= to_register
.First();
1102 it
.Good(); it
.Inc()) {
1103 // Received notice to enable experimental type. Check if the type is
1104 // registered, and if not register a new datatype controller.
1105 RegisterNewDataType(it
.Get());
1108 // Check if the user has "Keep Everything Synced" enabled. If so, we want
1109 // to turn on all experimental types if they're not already on. Otherwise we
1111 // Note: if any types are already registered, we don't turn them on. This
1112 // covers the case where we're already in the process of reconfiguring
1113 // to turn an experimental type on.
1114 if (sync_prefs_
.HasKeepEverythingSynced()) {
1115 // Mark all data types as preferred.
1116 sync_prefs_
.SetPreferredDataTypes(registered_types
, registered_types
);
1118 // Only automatically turn on types if we have already finished set up.
1119 // Otherwise, just leave the experimental types on by default.
1120 if (!to_register
.Empty() && HasSyncSetupCompleted() && migrator_
) {
1121 DVLOG(1) << "Dynamically enabling new datatypes: "
1122 << syncer::ModelTypeSetToString(to_register
);
1123 OnMigrationNeededForTypes(to_register
);
1127 current_experiments_
= experiments
;
1130 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1131 is_auth_in_progress_
= false;
1132 last_auth_error_
= error
;
1139 AuthError
ConnectionStatusToAuthError(
1140 syncer::ConnectionStatus status
) {
1142 case syncer::CONNECTION_OK
:
1143 return AuthError::AuthErrorNone();
1145 case syncer::CONNECTION_AUTH_ERROR
:
1146 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1148 case syncer::CONNECTION_SERVER_ERROR
:
1149 return AuthError(AuthError::CONNECTION_FAILED
);
1153 return AuthError(AuthError::CONNECTION_FAILED
);
1159 void ProfileSyncService::OnConnectionStatusChange(
1160 syncer::ConnectionStatus status
) {
1161 connection_status_update_time_
= base::Time::Now();
1162 connection_status_
= status
;
1163 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1164 // Sync server returned error indicating that access token is invalid. It
1165 // could be either expired or access is revoked. Let's request another
1166 // access token and if access is revoked then request for token will fail
1167 // with corresponding error. If access token is repeatedly reported
1168 // invalid, there may be some issues with server, e.g. authentication
1169 // state is inconsistent on sync and token server. In that case, we
1170 // backoff token requests exponentially to avoid hammering token server
1171 // too much and to avoid getting same token due to token server's caching
1172 // policy. |request_access_token_retry_timer_| is used to backoff request
1173 // triggered by both auth error and failure talking to GAIA server.
1174 // Therefore, we're likely to reach the backoff ceiling more quickly than
1175 // you would expect from looking at the BackoffPolicy if both types of
1176 // errors happen. We shouldn't receive two errors back-to-back without
1177 // attempting a token/sync request in between, thus crank up request delay
1178 // unnecessary. This is because we won't make a sync request if we hit an
1179 // error until GAIA succeeds at sending a new token, and we won't request
1180 // a new token unless sync reports a token failure. But to be safe, don't
1181 // schedule request if this happens.
1182 if (request_access_token_retry_timer_
.IsRunning()) {
1184 } else if (request_access_token_backoff_
.failure_count() == 0) {
1185 // First time request without delay. Currently invalid token is used
1186 // to initialize sync backend and we'll always end up here. We don't
1187 // want to delay initialization.
1188 request_access_token_backoff_
.InformOfRequest(false);
1189 RequestAccessToken();
1191 request_access_token_backoff_
.InformOfRequest(false);
1192 request_access_token_retry_timer_
.Start(
1194 request_access_token_backoff_
.GetTimeUntilRelease(),
1195 base::Bind(&ProfileSyncService::RequestAccessToken
,
1196 weak_factory_
.GetWeakPtr()));
1199 // Reset backoff time after successful connection.
1200 if (status
== syncer::CONNECTION_OK
) {
1201 // Request shouldn't be scheduled at this time. But if it is, it's
1202 // possible that sync flips between OK and auth error states rapidly,
1203 // thus hammers token server. To be safe, only reset backoff delay when
1204 // no scheduled request.
1205 if (request_access_token_retry_timer_
.IsRunning()) {
1208 request_access_token_backoff_
.Reset();
1212 const GoogleServiceAuthError auth_error
=
1213 ConnectionStatusToAuthError(status
);
1214 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1215 UpdateAuthErrorState(auth_error
);
1219 void ProfileSyncService::OnStopSyncingPermanently() {
1220 sync_prefs_
.SetStartSuppressed(true);
1224 void ProfileSyncService::OnPassphraseRequired(
1225 syncer::PassphraseRequiredReason reason
,
1226 const sync_pb::EncryptedData
& pending_keys
) {
1227 DCHECK(backend_
.get());
1228 DCHECK(backend_
->IsNigoriEnabled());
1230 // TODO(lipalani) : add this check to other locations as well.
1231 if (HasUnrecoverableError()) {
1232 // When unrecoverable error is detected we post a task to shutdown the
1233 // backend. The task might not have executed yet.
1237 DVLOG(1) << "Passphrase required with reason: "
1238 << syncer::PassphraseRequiredReasonToString(reason
);
1239 passphrase_required_reason_
= reason
;
1241 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1242 if (data_type_manager_
) {
1243 // Reconfigure without the encrypted types (excluded implicitly via the
1244 // failed datatypes handler).
1245 data_type_manager_
->Configure(types
,
1246 syncer::CONFIGURE_REASON_CRYPTO
);
1249 // Notify observers that the passphrase status may have changed.
1253 void ProfileSyncService::OnPassphraseAccepted() {
1254 DVLOG(1) << "Received OnPassphraseAccepted.";
1256 // If the pending keys were resolved via keystore, it's possible we never
1257 // consumed our cached passphrase. Clear it now.
1258 if (!cached_passphrase_
.empty())
1259 cached_passphrase_
.clear();
1261 // Reset passphrase_required_reason_ since we know we no longer require the
1262 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1263 // because that can be called by OnPassphraseRequired() if no encrypted data
1264 // types are enabled, and we don't want to clobber the true passphrase error.
1265 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1267 // Make sure the data types that depend on the passphrase are started at
1269 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1270 if (data_type_manager_
) {
1271 // Re-enable any encrypted types if necessary.
1272 data_type_manager_
->Configure(types
,
1273 syncer::CONFIGURE_REASON_CRYPTO
);
1279 void ProfileSyncService::OnEncryptedTypesChanged(
1280 syncer::ModelTypeSet encrypted_types
,
1281 bool encrypt_everything
) {
1282 encrypted_types_
= encrypted_types
;
1283 encrypt_everything_
= encrypt_everything
;
1284 DVLOG(1) << "Encrypted types changed to "
1285 << syncer::ModelTypeSetToString(encrypted_types_
)
1286 << " (encrypt everything is set to "
1287 << (encrypt_everything_
? "true" : "false") << ")";
1288 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1290 // If sessions are encrypted, full history sync is not possible, and
1291 // delete directives are unnecessary.
1292 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES
) &&
1293 encrypted_types_
.Has(syncer::SESSIONS
)) {
1294 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES
,
1296 "Delete directives not supported with encryption.");
1300 void ProfileSyncService::OnEncryptionComplete() {
1301 DVLOG(1) << "Encryption complete";
1302 if (encryption_pending_
&& encrypt_everything_
) {
1303 encryption_pending_
= false;
1304 // This is to nudge the integration tests when encryption is
1310 void ProfileSyncService::OnMigrationNeededForTypes(
1311 syncer::ModelTypeSet types
) {
1312 DCHECK(backend_initialized_
);
1313 DCHECK(data_type_manager_
.get());
1315 // Migrator must be valid, because we don't sync until it is created and this
1316 // callback originates from a sync cycle.
1317 migrator_
->MigrateTypes(types
);
1320 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1321 last_actionable_error_
= error
;
1322 DCHECK_NE(last_actionable_error_
.action
,
1323 syncer::UNKNOWN_ACTION
);
1324 switch (error
.action
) {
1325 case syncer::UPGRADE_CLIENT
:
1326 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1327 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1328 case syncer::STOP_AND_RESTART_SYNC
:
1329 // TODO(lipalani) : if setup in progress we want to display these
1330 // actions in the popup. The current experience might not be optimal for
1331 // the user. We just dismiss the dialog.
1332 if (setup_in_progress_
) {
1333 OnStopSyncingPermanently();
1334 expect_sync_configuration_aborted_
= true;
1336 // Trigger an unrecoverable error to stop syncing.
1337 OnInternalUnrecoverableError(FROM_HERE
,
1338 last_actionable_error_
.error_description
,
1340 ERROR_REASON_ACTIONABLE_ERROR
);
1342 case syncer::DISABLE_SYNC_ON_CLIENT
:
1343 OnStopSyncingPermanently();
1344 #if !defined(OS_CHROMEOS)
1345 // On desktop Chrome, sign out the user after a dashboard clear.
1346 // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049.
1347 if (!auto_start_enabled_
) // Skip sign out on ChromeOS/Android.
1348 SigninManagerFactory::GetForProfile(profile_
)->SignOut();
1351 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1352 // Sync disabled by domain admin. we should stop syncing until next
1354 sync_disabled_by_admin_
= true;
1355 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD
);
1363 void ProfileSyncService::OnConfigureDone(
1364 const browser_sync::DataTypeManager::ConfigureResult
& result
) {
1365 // We should have cleared our cached passphrase before we get here (in
1366 // OnBackendInitialized()).
1367 DCHECK(cached_passphrase_
.empty());
1369 if (!sync_configure_start_time_
.is_null()) {
1370 if (result
.status
== DataTypeManager::OK
||
1371 result
.status
== DataTypeManager::PARTIAL_SUCCESS
) {
1372 base::Time sync_configure_stop_time
= base::Time::Now();
1373 base::TimeDelta delta
= sync_configure_stop_time
-
1374 sync_configure_start_time_
;
1375 if (is_first_time_sync_configure_
) {
1376 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1378 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1382 sync_configure_start_time_
= base::Time();
1385 // Notify listeners that configuration is done.
1386 content::NotificationService::current()->Notify(
1387 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1388 content::Source
<ProfileSyncService
>(this),
1389 content::NotificationService::NoDetails());
1391 configure_status_
= result
.status
;
1392 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1393 // The possible status values:
1394 // ABORT - Configuration was aborted. This is not an error, if
1395 // initiated by user.
1396 // OK - Everything succeeded.
1397 // PARTIAL_SUCCESS - Some datatypes failed to start.
1398 // Everything else is an UnrecoverableError. So treat it as such.
1400 // First handle the abort case.
1401 if (configure_status_
== DataTypeManager::ABORTED
&&
1402 expect_sync_configuration_aborted_
) {
1403 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1404 expect_sync_configuration_aborted_
= false;
1408 // Handle unrecoverable error.
1409 if (configure_status_
!= DataTypeManager::OK
&&
1410 configure_status_
!= DataTypeManager::PARTIAL_SUCCESS
) {
1411 // Something catastrophic had happened. We should only have one
1412 // error representing it.
1413 DCHECK_EQ(result
.failed_data_types
.size(),
1414 static_cast<unsigned int>(1));
1415 syncer::SyncError error
= result
.failed_data_types
.begin()->second
;
1416 DCHECK(error
.IsSet());
1417 std::string message
=
1418 "Sync configuration failed with status " +
1419 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1420 " during " + syncer::ModelTypeToString(error
.model_type()) +
1421 ": " + error
.message();
1422 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1423 OnInternalUnrecoverableError(error
.location(),
1426 ERROR_REASON_CONFIGURATION_FAILURE
);
1430 // We should never get in a state where we have no encrypted datatypes
1431 // enabled, and yet we still think we require a passphrase for decryption.
1432 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1433 !IsEncryptedDatatypeEnabled()));
1435 // This must be done before we start syncing with the server to avoid
1436 // sending unencrypted data up on a first time sync.
1437 if (encryption_pending_
)
1438 backend_
->EnableEncryptEverything();
1441 if (migrator_
.get() &&
1442 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1443 // Migration in progress. Let the migrator know we just finished
1444 // configuring something. It will be up to the migrator to call
1445 // StartSyncingWithServer() if migration is now finished.
1446 migrator_
->OnConfigureDone(result
);
1448 StartSyncingWithServer();
1452 void ProfileSyncService::OnConfigureRetry() {
1453 // We should have cleared our cached passphrase before we get here (in
1454 // OnBackendInitialized()).
1455 DCHECK(cached_passphrase_
.empty());
1457 OnSyncConfigureRetry();
1460 void ProfileSyncService::OnConfigureStart() {
1461 sync_configure_start_time_
= base::Time::Now();
1465 ProfileSyncService::SyncStatusSummary
1466 ProfileSyncService::QuerySyncStatusSummary() {
1467 if (HasUnrecoverableError()) {
1468 return UNRECOVERABLE_ERROR
;
1469 } else if (!backend_
) {
1471 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1472 return SETUP_INCOMPLETE
;
1473 } else if (backend_
.get() && HasSyncSetupCompleted() &&
1474 data_type_manager_
.get() &&
1475 data_type_manager_
->state() != DataTypeManager::CONFIGURED
) {
1476 return DATATYPES_NOT_INITIALIZED
;
1477 } else if (ShouldPushChanges()) {
1480 return UNKNOWN_ERROR
;
1483 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1484 SyncStatusSummary status
= QuerySyncStatusSummary();
1486 case UNRECOVERABLE_ERROR
:
1487 return "Unrecoverable error detected";
1489 return "Syncing not enabled";
1490 case SETUP_INCOMPLETE
:
1491 return "First time sync setup incomplete";
1492 case DATATYPES_NOT_INITIALIZED
:
1493 return "Datatypes not fully initialized";
1495 return "Sync service initialized";
1497 return "Status unknown: Internal error?";
1501 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1502 if (sync_initialized())
1504 else if (!start_up_time_
.is_null())
1507 return "Not started";
1510 bool ProfileSyncService::QueryDetailedSyncStatus(
1511 SyncBackendHost::Status
* result
) {
1512 if (backend_
.get() && backend_initialized_
) {
1513 *result
= backend_
->GetDetailedStatus();
1516 SyncBackendHost::Status status
;
1517 status
.sync_protocol_error
= last_actionable_error_
;
1523 const AuthError
& ProfileSyncService::GetAuthError() const {
1524 return last_auth_error_
;
1527 bool ProfileSyncService::FirstSetupInProgress() const {
1528 return !HasSyncSetupCompleted() && setup_in_progress_
;
1531 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1532 // This method is a no-op if |setup_in_progress_| remains unchanged.
1533 if (setup_in_progress_
== setup_in_progress
)
1536 setup_in_progress_
= setup_in_progress
;
1537 if (!setup_in_progress
&& sync_initialized())
1538 ReconfigureDatatypeManager();
1542 bool ProfileSyncService::sync_initialized() const {
1543 return backend_initialized_
;
1546 bool ProfileSyncService::waiting_for_auth() const {
1547 return is_auth_in_progress_
;
1550 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1551 return current_experiments_
;
1554 bool ProfileSyncService::HasUnrecoverableError() const {
1555 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1558 bool ProfileSyncService::IsPassphraseRequired() const {
1559 return passphrase_required_reason_
!=
1560 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1563 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1564 // If there is an encrypted datatype enabled and we don't have the proper
1565 // passphrase, we must prompt the user for a passphrase. The only way for the
1566 // user to avoid entering their passphrase is to disable the encrypted types.
1567 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1570 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1571 if (last_synced_time_
.is_null())
1572 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1574 base::TimeDelta last_synced
= base::Time::Now() - last_synced_time_
;
1576 if (last_synced
< base::TimeDelta::FromMinutes(1))
1577 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1579 return ui::TimeFormat::TimeElapsed(last_synced
);
1582 void ProfileSyncService::UpdateSelectedTypesHistogram(
1583 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1584 if (!HasSyncSetupCompleted() ||
1585 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1586 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1589 // Only log the data types that are shown in the sync settings ui.
1590 // Note: the order of these types must match the ordering of
1591 // the respective types in ModelType
1592 const browser_sync::user_selectable_type::UserSelectableSyncType
1593 user_selectable_types
[] = {
1594 browser_sync::user_selectable_type::BOOKMARKS
,
1595 browser_sync::user_selectable_type::PREFERENCES
,
1596 browser_sync::user_selectable_type::PASSWORDS
,
1597 browser_sync::user_selectable_type::AUTOFILL
,
1598 browser_sync::user_selectable_type::THEMES
,
1599 browser_sync::user_selectable_type::TYPED_URLS
,
1600 browser_sync::user_selectable_type::EXTENSIONS
,
1601 browser_sync::user_selectable_type::APPS
,
1602 browser_sync::user_selectable_type::PROXY_TABS
1605 COMPILE_ASSERT(31 == syncer::MODEL_TYPE_COUNT
, UpdateCustomConfigHistogram
);
1607 if (!sync_everything
) {
1608 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1610 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1611 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1613 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1615 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1617 const syncer::ModelType type
= it
.Get();
1618 if (chosen_types
.Has(type
) &&
1619 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1620 // Selected type has changed - log it.
1621 UMA_HISTOGRAM_ENUMERATION(
1623 user_selectable_types
[i
],
1624 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1630 #if defined(OS_CHROMEOS)
1631 void ProfileSyncService::RefreshSpareBootstrapToken(
1632 const std::string
& passphrase
) {
1633 browser_sync::ChromeEncryptor encryptor
;
1634 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1635 // The first 2 params (hostname and username) doesn't have any effect here.
1636 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1638 std::string bootstrap_token
;
1639 if (!temp_cryptographer
.AddKey(key_params
)) {
1640 NOTREACHED() << "Failed to add key to cryptographer.";
1642 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1643 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1647 void ProfileSyncService::OnUserChoseDatatypes(
1648 bool sync_everything
,
1649 syncer::ModelTypeSet chosen_types
) {
1650 if (!backend_
.get() && !HasUnrecoverableError()) {
1655 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1656 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1658 failed_data_types_handler_
.Reset();
1659 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES
) &&
1660 encrypted_types_
.Has(syncer::SESSIONS
)) {
1661 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES
,
1663 "Delete directives not supported with encryption.");
1665 ChangePreferredDataTypes(chosen_types
);
1666 AcknowledgeSyncedTypes();
1670 void ProfileSyncService::ChangePreferredDataTypes(
1671 syncer::ModelTypeSet preferred_types
) {
1673 DVLOG(1) << "ChangePreferredDataTypes invoked";
1674 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1675 const syncer::ModelTypeSet registered_preferred_types
=
1676 Intersection(registered_types
, preferred_types
);
1677 sync_prefs_
.SetPreferredDataTypes(registered_types
,
1678 registered_preferred_types
);
1680 // Now reconfigure the DTM.
1681 ReconfigureDatatypeManager();
1684 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1685 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1686 const syncer::ModelTypeSet failed_types
=
1687 failed_data_types_handler_
.GetFailedTypes();
1688 return Difference(preferred_types
, failed_types
);
1691 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1692 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1693 const syncer::ModelTypeSet preferred_types
=
1694 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1695 return preferred_types
;
1698 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1699 syncer::ModelTypeSet registered_types
;
1700 // The data_type_controllers_ are determined by command-line flags; that's
1701 // effectively what controls the values returned here.
1702 for (DataTypeController::TypeMap::const_iterator it
=
1703 data_type_controllers_
.begin();
1704 it
!= data_type_controllers_
.end(); ++it
) {
1705 registered_types
.Put(it
->first
);
1707 return registered_types
;
1710 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1711 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1712 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1713 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1716 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1717 return backend_
->GetPassphraseType();
1720 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1721 return backend_
->GetExplicitPassphraseTime();
1724 bool ProfileSyncService::IsCryptographerReady(
1725 const syncer::BaseTransaction
* trans
) const {
1726 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1729 void ProfileSyncService::ConfigurePriorityDataTypes() {
1730 const syncer::ModelTypeSet priority_types
=
1731 Intersection(GetPreferredDataTypes(), syncer::PriorityUserTypes());
1732 if (!priority_types
.Empty()) {
1733 const syncer::ConfigureReason reason
= HasSyncSetupCompleted() ?
1734 syncer::CONFIGURE_REASON_RECONFIGURATION
:
1735 syncer::CONFIGURE_REASON_NEW_CLIENT
;
1736 data_type_manager_
->Configure(priority_types
, reason
);
1740 void ProfileSyncService::ConfigureDataTypeManager() {
1741 // Don't configure datatypes if the setup UI is still on the screen - this
1742 // is to help multi-screen setting UIs (like iOS) where they don't want to
1743 // start syncing data until the user is done configuring encryption options,
1744 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1745 // SetSetupInProgress(false).
1746 if (setup_in_progress_
)
1749 bool restart
= false;
1750 if (!data_type_manager_
) {
1752 data_type_manager_
.reset(
1753 factory_
->CreateDataTypeManager(debug_info_listener_
,
1754 &data_type_controllers_
,
1758 &failed_data_types_handler_
));
1760 // We create the migrator at the same time.
1762 new browser_sync::BackendMigrator(
1763 profile_
->GetDebugName(), GetUserShare(),
1764 this, data_type_manager_
.get(),
1765 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1766 base::Unretained(this))));
1769 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1770 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1771 if (!HasSyncSetupCompleted()) {
1772 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1773 } else if (restart
) {
1774 // Datatype downloads on restart are generally due to newly supported
1775 // datatypes (although it's also possible we're picking up where a failed
1776 // previous configuration left off).
1777 // TODO(sync): consider detecting configuration recovery and setting
1778 // the reason here appropriately.
1779 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1781 // The user initiated a reconfiguration (either to add or remove types).
1782 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1785 data_type_manager_
->Configure(types
, reason
);
1788 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1789 if (backend_
.get() && backend_initialized_
) {
1790 return backend_
->GetUserShare();
1796 syncer::sessions::SyncSessionSnapshot
1797 ProfileSyncService::GetLastSessionSnapshot() const {
1798 if (backend_
.get() && backend_initialized_
) {
1799 return backend_
->GetLastSessionSnapshot();
1802 return syncer::sessions::SyncSessionSnapshot();
1805 bool ProfileSyncService::HasUnsyncedItems() const {
1806 if (backend_
.get() && backend_initialized_
) {
1807 return backend_
->HasUnsyncedItems();
1813 browser_sync::BackendMigrator
*
1814 ProfileSyncService::GetBackendMigratorForTest() {
1815 return migrator_
.get();
1818 void ProfileSyncService::GetModelSafeRoutingInfo(
1819 syncer::ModelSafeRoutingInfo
* out
) const {
1820 if (backend_
.get() && backend_initialized_
) {
1821 backend_
->GetModelSafeRoutingInfo(out
);
1827 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
1828 scoped_ptr
<base::ListValue
> result(new base::ListValue());
1830 if (!backend_
.get() || !backend_initialized_
) {
1831 return result
.release();
1834 FailedDataTypesHandler::TypeErrorMap error_map
=
1835 failed_data_types_handler_
.GetAllErrors();
1837 ModelTypeSet active_types
;
1838 ModelTypeSet passive_types
;
1839 ModelSafeRoutingInfo routing_info
;
1840 backend_
->GetModelSafeRoutingInfo(&routing_info
);
1841 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
1842 it
!= routing_info
.end(); ++it
) {
1843 if (it
->second
== syncer::GROUP_PASSIVE
) {
1844 passive_types
.Put(it
->first
);
1846 active_types
.Put(it
->first
);
1850 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
1851 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
1852 ModelTypeSet registered
= GetRegisteredDataTypes();
1853 scoped_ptr
<base::DictionaryValue
> type_status_header(
1854 new base::DictionaryValue());
1856 type_status_header
->SetString("name", "Model Type");
1857 type_status_header
->SetString("status", "header");
1858 type_status_header
->SetString("value", "Group Type");
1859 type_status_header
->SetString("num_entries", "Total Entries");
1860 type_status_header
->SetString("num_live", "Live Entries");
1861 result
->Append(type_status_header
.release());
1863 scoped_ptr
<base::DictionaryValue
> type_status
;
1864 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
1865 ModelType type
= it
.Get();
1867 type_status
.reset(new base::DictionaryValue());
1868 type_status
->SetString("name", ModelTypeToString(type
));
1870 if (error_map
.find(type
) != error_map
.end()) {
1871 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
1872 DCHECK(error
.IsSet());
1873 std::string error_text
= "Error: " + error
.location().ToString() +
1874 ", " + error
.message();
1875 type_status
->SetString("status", "error");
1876 type_status
->SetString("value", error_text
);
1877 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
1878 type_status
->SetString("status", "warning");
1879 type_status
->SetString("value", "Passive, Throttled");
1880 } else if (passive_types
.Has(type
)) {
1881 type_status
->SetString("status", "warning");
1882 type_status
->SetString("value", "Passive");
1883 } else if (throttled_types
.Has(type
)) {
1884 type_status
->SetString("status", "warning");
1885 type_status
->SetString("value", "Throttled");
1886 } else if (active_types
.Has(type
)) {
1887 type_status
->SetString("status", "ok");
1888 type_status
->SetString("value", "Active: " +
1889 ModelSafeGroupToString(routing_info
[type
]));
1891 type_status
->SetString("status", "warning");
1892 type_status
->SetString("value", "Disabled by User");
1895 int live_count
= detailed_status
.num_entries_by_type
[type
] -
1896 detailed_status
.num_to_delete_entries_by_type
[type
];
1897 type_status
->SetInteger("num_entries",
1898 detailed_status
.num_entries_by_type
[type
]);
1899 type_status
->SetInteger("num_live", live_count
);
1901 result
->Append(type_status
.release());
1903 return result
.release();
1906 void ProfileSyncService::ActivateDataType(
1907 syncer::ModelType type
, syncer::ModelSafeGroup group
,
1908 ChangeProcessor
* change_processor
) {
1913 DCHECK(backend_initialized_
);
1914 backend_
->ActivateDataType(type
, group
, change_processor
);
1917 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
1920 backend_
->DeactivateDataType(type
);
1923 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
1924 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
1925 // If the backend isn't running yet, OnBackendInitialized() will call this
1926 // method again after the backend starts up.
1927 if (cached_passphrase_
.empty() || !sync_initialized())
1930 // Backend is up and running, so we can consume the cached passphrase.
1931 std::string passphrase
= cached_passphrase_
;
1932 cached_passphrase_
.clear();
1934 // If we need a passphrase to decrypt data, try the cached passphrase.
1935 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
1936 if (SetDecryptionPassphrase(passphrase
)) {
1937 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
1942 // If we get here, we don't have pending keys (or at least, the passphrase
1943 // doesn't decrypt them) - just try to re-encrypt using the encryption
1945 if (!IsUsingSecondaryPassphrase())
1946 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
1949 void ProfileSyncService::RequestAccessToken() {
1950 // Only one active request at a time.
1951 if (access_token_request_
!= NULL
)
1953 request_access_token_retry_timer_
.Stop();
1954 OAuth2TokenService::ScopeSet oauth2_scopes
;
1955 if (profile_
->IsManaged()) {
1956 oauth2_scopes
.insert(GaiaConstants::kChromeSyncManagedOAuth2Scope
);
1958 oauth2_scopes
.insert(GaiaConstants::kChromeSyncOAuth2Scope
);
1961 // Invalidate previous token, otherwise token service will return the same
1963 const std::string
& account_id
= GetAccountIdToUse();
1964 if (!access_token_
.empty()) {
1965 oauth2_token_service_
->InvalidateToken(
1966 account_id
, oauth2_scopes
, access_token_
);
1969 access_token_
.clear();
1971 token_request_time_
= base::Time::Now();
1972 token_receive_time_
= base::Time();
1973 next_token_request_time_
= base::Time();
1974 access_token_request_
=
1975 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
1978 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
1979 PassphraseType type
) {
1980 // This should only be called when the backend has been initialized.
1981 DCHECK(sync_initialized());
1982 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
1983 "Data is already encrypted using an explicit passphrase";
1984 DCHECK(!(type
== EXPLICIT
&&
1985 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
1986 "Can not set explicit passphrase when decryption is needed.";
1988 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
1989 << " passphrase for encryption.";
1990 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
1991 // REASON_ENCRYPTION implies that the cryptographer does not have pending
1992 // keys. Hence, as long as we're not trying to do an invalid passphrase
1993 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
1994 // will succeed. If for some reason a new encryption key arrives via
1995 // sync later, the SBH will trigger another OnPassphraseRequired().
1996 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1999 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2002 bool ProfileSyncService::SetDecryptionPassphrase(
2003 const std::string
& passphrase
) {
2004 if (IsPassphraseRequired()) {
2005 DVLOG(1) << "Setting passphrase for decryption.";
2006 return backend_
->SetDecryptionPassphrase(passphrase
);
2008 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2009 "IsPassphraseRequired() is false.";
2014 void ProfileSyncService::EnableEncryptEverything() {
2015 // Tests override sync_initialized() to always return true, so we
2016 // must check that instead of |backend_initialized_|.
2017 // TODO(akalin): Fix the above. :/
2018 DCHECK(sync_initialized());
2019 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2020 // problems around cancelling encryption in the background (crbug.com/119649).
2021 if (!encrypt_everything_
)
2022 encryption_pending_
= true;
2025 bool ProfileSyncService::encryption_pending() const {
2026 // We may be called during the setup process before we're
2027 // initialized (via IsEncryptedDatatypeEnabled and
2028 // IsPassphraseRequiredForDecryption).
2029 return encryption_pending_
;
2032 bool ProfileSyncService::EncryptEverythingEnabled() const {
2033 DCHECK(backend_initialized_
);
2034 return encrypt_everything_
|| encryption_pending_
;
2037 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2038 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2039 // We may be called during the setup process before we're
2040 // initialized. In this case, we default to the sensitive types.
2041 return encrypted_types_
;
2044 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2046 if (is_sync_managed
) {
2049 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2054 void ProfileSyncService::Observe(int type
,
2055 const content::NotificationSource
& source
,
2056 const content::NotificationDetails
& details
) {
2058 case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
: {
2059 const GoogleServiceSigninSuccessDetails
* successful
=
2060 content::Details
<const GoogleServiceSigninSuccessDetails
>(
2062 if (!sync_prefs_
.IsStartSuppressed() &&
2063 !successful
->password
.empty()) {
2064 cached_passphrase_
= successful
->password
;
2065 // Try to consume the passphrase we just cached. If the sync backend
2066 // is not running yet, the passphrase will remain cached until the
2067 // backend starts up.
2068 ConsumeCachedPassphraseIfPossible();
2070 #if defined(OS_CHROMEOS)
2071 RefreshSpareBootstrapToken(successful
->password
);
2073 if (!sync_initialized() ||
2074 GetAuthError().state() != AuthError::NONE
) {
2075 // Track the fact that we're still waiting for auth to complete.
2076 is_auth_in_progress_
= true;
2080 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT
:
2081 sync_disabled_by_admin_
= false;
2090 void ProfileSyncService::AddObserver(
2091 ProfileSyncServiceBase::Observer
* observer
) {
2092 observers_
.AddObserver(observer
);
2095 void ProfileSyncService::RemoveObserver(
2096 ProfileSyncServiceBase::Observer
* observer
) {
2097 observers_
.RemoveObserver(observer
);
2100 bool ProfileSyncService::HasObserver(
2101 ProfileSyncServiceBase::Observer
* observer
) const {
2102 return observers_
.HasObserver(observer
);
2105 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2106 return sync_js_controller_
.AsWeakPtr();
2109 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2110 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2114 bool ProfileSyncService::IsSyncEnabled() {
2115 // We have switches::kEnableSync just in case we need to change back to
2116 // sync-disabled-by-default on a platform.
2117 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync
);
2120 bool ProfileSyncService::IsManaged() const {
2121 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2124 bool ProfileSyncService::ShouldPushChanges() {
2125 // True only after all bootstrapping has succeeded: the sync backend
2126 // is initialized, all enabled data types are consistent with one
2127 // another, and no unrecoverable error has transpired.
2128 if (HasUnrecoverableError())
2131 if (!data_type_manager_
)
2134 return data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
2137 void ProfileSyncService::StopAndSuppress() {
2138 sync_prefs_
.SetStartSuppressed(true);
2140 backend_
->UnregisterInvalidationIds();
2142 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD
);
2145 bool ProfileSyncService::IsStartSuppressed() const {
2146 return sync_prefs_
.IsStartSuppressed();
2149 void ProfileSyncService::UnsuppressAndStart() {
2151 sync_prefs_
.SetStartSuppressed(false);
2152 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess
2153 // is never called for some clients.
2154 if (signin_
&& signin_
->GetAuthenticatedUsername().empty()) {
2155 signin_
->SetAuthenticatedUsername(sync_prefs_
.GetGoogleServicesUsername());
2160 void ProfileSyncService::AcknowledgeSyncedTypes() {
2161 sync_prefs_
.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2164 void ProfileSyncService::ReconfigureDatatypeManager() {
2165 // If we haven't initialized yet, don't configure the DTM as it could cause
2166 // association to start before a Directory has even been created.
2167 if (backend_initialized_
) {
2168 DCHECK(backend_
.get());
2169 ConfigureDataTypeManager();
2170 } else if (HasUnrecoverableError()) {
2171 // There is nothing more to configure. So inform the listeners,
2174 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2175 << "Unrecoverable error.";
2177 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2182 const FailedDataTypesHandler
& ProfileSyncService::failed_data_types_handler()
2184 return failed_data_types_handler_
;
2187 void ProfileSyncService::OnInternalUnrecoverableError(
2188 const tracked_objects::Location
& from_here
,
2189 const std::string
& message
,
2190 bool delete_sync_database
,
2191 UnrecoverableErrorReason reason
) {
2192 DCHECK(!HasUnrecoverableError());
2193 unrecoverable_error_reason_
= reason
;
2194 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2197 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2198 return request_access_token_retry_timer_
.IsRunning();
2201 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2202 return access_token_
;
2205 std::string
ProfileSyncService::GetEffectiveUsername() {
2206 if (profile_
->IsManaged()) {
2207 #if defined(ENABLE_MANAGED_USERS)
2208 DCHECK_EQ(std::string(), signin_
->GetAuthenticatedUsername());
2209 return managed_users::kManagedUserPseudoEmail
;
2215 return signin_
->GetAuthenticatedUsername();
2218 std::string
ProfileSyncService::GetAccountIdToUse() {
2219 if (profile_
->IsManaged()) {
2220 #if defined(ENABLE_MANAGED_USERS)
2221 return managed_users::kManagedUserPseudoEmail
;
2227 // TODO(fgorski): Use GetPrimaryAccountId() when it's available.
2228 return signin_
->GetAuthenticatedUsername();
2231 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2232 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2235 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2236 return sessions_sync_manager_
.get();
2239 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2240 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED
),
2241 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2242 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2244 ProfileSyncService::SyncTokenStatus
2245 ProfileSyncService::GetSyncTokenStatus() const {
2246 SyncTokenStatus status
;
2247 status
.connection_status_update_time
= connection_status_update_time_
;
2248 status
.connection_status
= connection_status_
;
2249 status
.token_request_time
= token_request_time_
;
2250 status
.token_receive_time
= token_receive_time_
;
2251 status
.last_get_token_error
= last_get_token_error_
;
2252 if (request_access_token_retry_timer_
.IsRunning())
2253 status
.next_token_request_time
= next_token_request_time_
;
2257 void ProfileSyncService::OverrideNetworkResourcesForTest(
2258 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2259 network_resources_
= network_resources
.Pass();